From 82cceaff537d94d584c8a69b9bdc4a649b4230c9 Mon Sep 17 00:00:00 2001 From: arnaucode Date: Fri, 23 Jun 2017 16:45:13 +0200 Subject: [PATCH] implemented upload file image for new event --- .gitignore | 2 +- config.xml | 2 + plugins/android.json | 12 +- plugins/cordova-plugin-camera/CONTRIBUTING.md | 37 + plugins/cordova-plugin-camera/LICENSE | 202 + plugins/cordova-plugin-camera/NOTICE | 5 + plugins/cordova-plugin-camera/README.md | 793 ++++ plugins/cordova-plugin-camera/RELEASENOTES.md | 367 ++ .../appium-tests/android/android.spec.js | 672 +++ .../appium-tests/helpers/cameraHelper.js | 308 ++ .../appium-tests/ios/ios.spec.js | 489 ++ .../cordova-plugin-camera/doc/de/README.md | 421 ++ plugins/cordova-plugin-camera/doc/de/index.md | 434 ++ .../cordova-plugin-camera/doc/es/README.md | 411 ++ plugins/cordova-plugin-camera/doc/es/index.md | 391 ++ .../cordova-plugin-camera/doc/fr/README.md | 378 ++ plugins/cordova-plugin-camera/doc/fr/index.md | 391 ++ .../doc/img/android-fail.png | Bin 0 -> 753 bytes .../doc/img/android-success.png | Bin 0 -> 716 bytes .../doc/img/blackberry-fail.png | Bin 0 -> 1009 bytes .../doc/img/blackberry-success.png | Bin 0 -> 984 bytes .../doc/img/browser-fail.png | Bin 0 -> 806 bytes .../doc/img/browser-success.png | Bin 0 -> 776 bytes .../doc/img/firefox-fail.png | Bin 0 -> 802 bytes .../doc/img/firefox-success.png | Bin 0 -> 770 bytes .../doc/img/fireos-fail.png | Bin 0 -> 965 bytes .../doc/img/fireos-success.png | Bin 0 -> 936 bytes .../doc/img/ios-fail.png | Bin 0 -> 573 bytes .../doc/img/ios-success.png | Bin 0 -> 550 bytes .../doc/img/ubuntu-fail.png | Bin 0 -> 649 bytes .../doc/img/ubuntu-success.png | Bin 0 -> 622 bytes .../doc/img/windows-fail.png | Bin 0 -> 784 bytes .../doc/img/windows-success.png | Bin 0 -> 759 bytes .../doc/img/wp8-fail.png | Bin 0 -> 714 bytes .../doc/img/wp8-success.png | Bin 0 -> 679 bytes .../cordova-plugin-camera/doc/it/README.md | 421 ++ plugins/cordova-plugin-camera/doc/it/index.md | 434 ++ .../cordova-plugin-camera/doc/ja/README.md | 421 ++ plugins/cordova-plugin-camera/doc/ja/index.md | 434 ++ .../cordova-plugin-camera/doc/ko/README.md | 421 ++ plugins/cordova-plugin-camera/doc/ko/index.md | 434 ++ .../cordova-plugin-camera/doc/pl/README.md | 421 ++ plugins/cordova-plugin-camera/doc/pl/index.md | 434 ++ plugins/cordova-plugin-camera/doc/ru/index.md | 417 ++ .../cordova-plugin-camera/doc/zh/README.md | 421 ++ plugins/cordova-plugin-camera/doc/zh/index.md | 435 ++ .../jsdoc2md/TEMPLATE.md | 443 ++ plugins/cordova-plugin-camera/package.json | 63 + plugins/cordova-plugin-camera/plugin.xml | 285 ++ .../src/android/CameraLauncher.java | 1399 ++++++ .../src/android/CordovaUri.java | 104 + .../src/android/ExifHelper.java | 185 + .../src/android/FileHelper.java | 319 ++ .../src/android/xml/provider_paths.xml | 21 + .../src/blackberry10/index.js | 227 + .../src/browser/CameraProxy.js | 123 + .../src/firefoxos/CameraProxy.js | 53 + .../cordova-plugin-camera/src/ios/CDVCamera.h | 116 + .../cordova-plugin-camera/src/ios/CDVCamera.m | 771 ++++ .../cordova-plugin-camera/src/ios/CDVExif.h | 43 + .../src/ios/CDVJpegHeaderWriter.h | 62 + .../src/ios/CDVJpegHeaderWriter.m | 547 +++ .../src/ios/UIImage+CropScaleOrientation.h | 29 + .../src/ios/UIImage+CropScaleOrientation.m | 175 + .../src/ubuntu/CaptureWidget.qml | 118 + .../cordova-plugin-camera/src/ubuntu/back.png | Bin 0 -> 12428 bytes .../src/ubuntu/camera.cpp | 140 + .../cordova-plugin-camera/src/ubuntu/camera.h | 86 + .../src/ubuntu/shoot.png | Bin 0 -> 14430 bytes .../src/ubuntu/toolbar-left.png | Bin 0 -> 1212 bytes .../src/ubuntu/toolbar-middle.png | Bin 0 -> 4416 bytes .../src/ubuntu/toolbar-right.png | Bin 0 -> 1161 bytes .../src/windows/CameraProxy.js | 882 ++++ .../cordova-plugin-camera/src/wp/Camera.cs | 534 +++ .../tests/ios/.npmignore | 1 + .../contents.xcworkspacedata | 7 + .../xcshareddata/CDVCameraTest.xccheckout | 41 + .../xcschemes/CordovaLib.xcscheme | 77 + .../CDVCameraLibTests/CameraTest.m | 511 +++ .../CDVCameraLibTests/Info.plist | 44 + .../CDVCameraTest.xcodeproj/project.pbxproj | 561 +++ .../contents.xcworkspacedata | 7 + .../xcshareddata/CDVCameraTest.xccheckout | 41 + .../xcschemes/CDVCameraLib.xcscheme | 77 + .../xcschemes/CDVCameraLibTests.xcscheme | 96 + .../cordova-plugin-camera/tests/ios/README.md | 40 + .../tests/ios/doc/de/README.md | 39 + .../tests/ios/doc/es/README.md | 39 + .../tests/ios/doc/fr/README.md | 39 + .../tests/ios/doc/it/README.md | 39 + .../tests/ios/doc/ja/README.md | 39 + .../tests/ios/doc/ko/README.md | 39 + .../tests/ios/doc/pl/README.md | 39 + .../tests/ios/doc/zh/README.md | 39 + .../tests/ios/package.json | 13 + .../cordova-plugin-camera/tests/package.json | 14 + .../cordova-plugin-camera/tests/plugin.xml | 33 + plugins/cordova-plugin-camera/tests/tests.js | 510 +++ .../cordova-plugin-camera/types/index.d.ts | 174 + plugins/cordova-plugin-camera/www/Camera.js | 185 + .../www/CameraConstants.js | 101 + .../www/CameraPopoverHandle.js | 32 + .../www/CameraPopoverOptions.js | 52 + .../www/blackberry10/assets/camera.html | 82 + .../www/blackberry10/assets/camera.js | 46 + .../www/ios/CameraPopoverHandle.js | 66 + plugins/cordova-plugin-compat/README.md | 31 + plugins/cordova-plugin-compat/RELEASENOTES.md | 29 + plugins/cordova-plugin-compat/package.json | 32 + plugins/cordova-plugin-compat/plugin.xml | 37 + .../src/android/BuildHelper.java | 70 + .../src/android/PermissionHelper.java | 138 + plugins/cordova-plugin-file/CONTRIBUTING.md | 37 + plugins/cordova-plugin-file/LICENSE | 202 + plugins/cordova-plugin-file/NOTICE | 5 + plugins/cordova-plugin-file/README.md | 868 ++++ plugins/cordova-plugin-file/RELEASENOTES.md | 455 ++ plugins/cordova-plugin-file/doc/de/README.md | 335 ++ plugins/cordova-plugin-file/doc/de/index.md | 338 ++ plugins/cordova-plugin-file/doc/de/plugins.md | 101 + plugins/cordova-plugin-file/doc/es/README.md | 335 ++ plugins/cordova-plugin-file/doc/es/index.md | 336 ++ plugins/cordova-plugin-file/doc/es/plugins.md | 101 + plugins/cordova-plugin-file/doc/fr/README.md | 328 ++ plugins/cordova-plugin-file/doc/fr/index.md | 331 ++ plugins/cordova-plugin-file/doc/fr/plugins.md | 101 + plugins/cordova-plugin-file/doc/it/README.md | 335 ++ plugins/cordova-plugin-file/doc/it/index.md | 338 ++ plugins/cordova-plugin-file/doc/it/plugins.md | 101 + plugins/cordova-plugin-file/doc/ja/README.md | 335 ++ plugins/cordova-plugin-file/doc/ja/index.md | 338 ++ plugins/cordova-plugin-file/doc/ja/plugins.md | 101 + plugins/cordova-plugin-file/doc/ko/README.md | 335 ++ plugins/cordova-plugin-file/doc/ko/index.md | 338 ++ plugins/cordova-plugin-file/doc/ko/plugins.md | 101 + plugins/cordova-plugin-file/doc/pl/README.md | 335 ++ plugins/cordova-plugin-file/doc/pl/index.md | 338 ++ plugins/cordova-plugin-file/doc/pl/plugins.md | 101 + plugins/cordova-plugin-file/doc/plugins.md | 120 + plugins/cordova-plugin-file/doc/ru/index.md | 275 ++ plugins/cordova-plugin-file/doc/ru/plugins.md | 124 + plugins/cordova-plugin-file/doc/zh/README.md | 335 ++ plugins/cordova-plugin-file/doc/zh/index.md | 343 ++ plugins/cordova-plugin-file/doc/zh/plugins.md | 101 + plugins/cordova-plugin-file/package.json | 58 + plugins/cordova-plugin-file/plugin.xml | 424 ++ .../src/android/AssetFilesystem.java | 294 ++ .../src/android/ContentFilesystem.java | 223 + .../src/android/DirectoryManager.java | 134 + .../src/android/EncodingException.java | 29 + .../src/android/FileExistsException.java | 29 + .../src/android/FileUtils.java | 1224 +++++ .../src/android/Filesystem.java | 331 ++ .../android/InvalidModificationException.java | 30 + .../src/android/LocalFilesystem.java | 513 +++ .../src/android/LocalFilesystemURL.java | 64 + .../NoModificationAllowedException.java | 29 + .../src/android/PendingRequests.java | 94 + .../src/android/TypeMismatchException.java | 30 + .../src/android/build-extras.gradle | 47 + .../src/blackberry10/index.js | 47 + .../src/browser/FileProxy.js | 984 ++++ .../src/firefoxos/FileProxy.js | 805 ++++ .../src/ios/CDVAssetLibraryFilesystem.h | 30 + .../src/ios/CDVAssetLibraryFilesystem.m | 253 ++ plugins/cordova-plugin-file/src/ios/CDVFile.h | 157 + plugins/cordova-plugin-file/src/ios/CDVFile.m | 1119 +++++ .../src/ios/CDVLocalFilesystem.h | 32 + .../src/ios/CDVLocalFilesystem.m | 734 +++ plugins/cordova-plugin-file/src/osx/CDVFile.h | 189 + plugins/cordova-plugin-file/src/osx/CDVFile.m | 1056 +++++ .../src/osx/CDVLocalFilesystem.h | 32 + .../src/osx/CDVLocalFilesystem.m | 733 +++ .../cordova-plugin-file/src/ubuntu/file.cpp | 912 ++++ plugins/cordova-plugin-file/src/ubuntu/file.h | 81 + .../src/windows/FileProxy.js | 1209 +++++ plugins/cordova-plugin-file/src/wp/File.cs | 1800 ++++++++ .../cordova-plugin-file/tests/package.json | 17 + plugins/cordova-plugin-file/tests/plugin.xml | 44 + .../src/android/TestContentProvider.java | 93 + plugins/cordova-plugin-file/tests/tests.js | 4012 +++++++++++++++++ .../www/fixtures/asset-test/asset-test.txt | 1 + plugins/cordova-plugin-file/types/index.d.ts | 378 ++ .../cordova-plugin-file/www/DirectoryEntry.js | 117 + .../www/DirectoryReader.js | 73 + plugins/cordova-plugin-file/www/Entry.js | 262 ++ plugins/cordova-plugin-file/www/File.js | 79 + plugins/cordova-plugin-file/www/FileEntry.js | 93 + plugins/cordova-plugin-file/www/FileError.js | 46 + plugins/cordova-plugin-file/www/FileReader.js | 299 ++ plugins/cordova-plugin-file/www/FileSystem.js | 55 + .../www/FileUploadOptions.js | 41 + .../www/FileUploadResult.js | 30 + plugins/cordova-plugin-file/www/FileWriter.js | 324 ++ plugins/cordova-plugin-file/www/Flags.js | 36 + .../www/LocalFileSystem.js | 23 + plugins/cordova-plugin-file/www/Metadata.js | 40 + .../cordova-plugin-file/www/ProgressEvent.js | 67 + .../www/android/FileSystem.js | 49 + .../www/blackberry10/.jshintrc | 5 + .../www/blackberry10/FileProxy.js | 51 + .../www/blackberry10/FileSystem.js | 47 + .../www/blackberry10/copyTo.js | 143 + .../www/blackberry10/createEntryFromNative.js | 75 + .../www/blackberry10/getDirectory.js | 72 + .../www/blackberry10/getFile.js | 57 + .../www/blackberry10/getFileMetadata.js | 65 + .../www/blackberry10/getMetadata.js | 54 + .../www/blackberry10/getParent.js | 57 + .../www/blackberry10/info.js | 52 + .../www/blackberry10/moveTo.js | 39 + .../www/blackberry10/readAsArrayBuffer.js | 68 + .../www/blackberry10/readAsBinaryString.js | 68 + .../www/blackberry10/readAsDataURL.js | 65 + .../www/blackberry10/readAsText.js | 77 + .../www/blackberry10/readEntries.js | 70 + .../www/blackberry10/remove.js | 61 + .../www/blackberry10/removeRecursively.js | 62 + .../www/blackberry10/requestAllFileSystems.js | 42 + .../www/blackberry10/requestAnimationFrame.js | 38 + .../www/blackberry10/requestFileSystem.js | 53 + .../blackberry10/resolveLocalFileSystemURI.js | 172 + .../www/blackberry10/setMetadata.js | 33 + .../www/blackberry10/truncate.js | 74 + .../www/blackberry10/write.js | 73 + .../www/browser/FileSystem.js | 31 + .../www/browser/Preparing.js | 192 + .../www/browser/isChrome.js | 26 + .../www/fileSystemPaths.js | 63 + .../www/fileSystems-roots.js | 45 + .../cordova-plugin-file/www/fileSystems.js | 25 + .../www/firefoxos/FileSystem.js | 29 + .../cordova-plugin-file/www/ios/FileSystem.js | 30 + .../cordova-plugin-file/www/osx/FileSystem.js | 30 + .../www/requestFileSystem.js | 82 + .../www/resolveLocalFileSystemURI.js | 92 + .../www/ubuntu/FileSystem.js | 34 + .../www/ubuntu/FileWriter.js | 135 + .../www/ubuntu/fileSystems-roots.js | 53 + .../www/wp/FileUploadOptions.js | 49 + plugins/fetch.json | 24 + www/js/app.js | 2 +- www/js/mapEvents.js | 87 +- www/js/newEvent.js | 27 +- www/templates/events.html | 1 + www/templates/menu.html | 2 +- www/templates/newEvent.html | 6 +- 247 files changed, 51054 insertions(+), 49 deletions(-) create mode 100644 plugins/cordova-plugin-camera/CONTRIBUTING.md create mode 100644 plugins/cordova-plugin-camera/LICENSE create mode 100644 plugins/cordova-plugin-camera/NOTICE create mode 100644 plugins/cordova-plugin-camera/README.md create mode 100644 plugins/cordova-plugin-camera/RELEASENOTES.md create mode 100644 plugins/cordova-plugin-camera/appium-tests/android/android.spec.js create mode 100644 plugins/cordova-plugin-camera/appium-tests/helpers/cameraHelper.js create mode 100644 plugins/cordova-plugin-camera/appium-tests/ios/ios.spec.js create mode 100644 plugins/cordova-plugin-camera/doc/de/README.md create mode 100644 plugins/cordova-plugin-camera/doc/de/index.md create mode 100644 plugins/cordova-plugin-camera/doc/es/README.md create mode 100644 plugins/cordova-plugin-camera/doc/es/index.md create mode 100644 plugins/cordova-plugin-camera/doc/fr/README.md create mode 100644 plugins/cordova-plugin-camera/doc/fr/index.md create mode 100644 plugins/cordova-plugin-camera/doc/img/android-fail.png create mode 100644 plugins/cordova-plugin-camera/doc/img/android-success.png create mode 100644 plugins/cordova-plugin-camera/doc/img/blackberry-fail.png create mode 100644 plugins/cordova-plugin-camera/doc/img/blackberry-success.png create mode 100644 plugins/cordova-plugin-camera/doc/img/browser-fail.png create mode 100644 plugins/cordova-plugin-camera/doc/img/browser-success.png create mode 100644 plugins/cordova-plugin-camera/doc/img/firefox-fail.png create mode 100644 plugins/cordova-plugin-camera/doc/img/firefox-success.png create mode 100644 plugins/cordova-plugin-camera/doc/img/fireos-fail.png create mode 100644 plugins/cordova-plugin-camera/doc/img/fireos-success.png create mode 100644 plugins/cordova-plugin-camera/doc/img/ios-fail.png create mode 100644 plugins/cordova-plugin-camera/doc/img/ios-success.png create mode 100644 plugins/cordova-plugin-camera/doc/img/ubuntu-fail.png create mode 100644 plugins/cordova-plugin-camera/doc/img/ubuntu-success.png create mode 100644 plugins/cordova-plugin-camera/doc/img/windows-fail.png create mode 100644 plugins/cordova-plugin-camera/doc/img/windows-success.png create mode 100644 plugins/cordova-plugin-camera/doc/img/wp8-fail.png create mode 100644 plugins/cordova-plugin-camera/doc/img/wp8-success.png create mode 100644 plugins/cordova-plugin-camera/doc/it/README.md create mode 100644 plugins/cordova-plugin-camera/doc/it/index.md create mode 100644 plugins/cordova-plugin-camera/doc/ja/README.md create mode 100644 plugins/cordova-plugin-camera/doc/ja/index.md create mode 100644 plugins/cordova-plugin-camera/doc/ko/README.md create mode 100644 plugins/cordova-plugin-camera/doc/ko/index.md create mode 100644 plugins/cordova-plugin-camera/doc/pl/README.md create mode 100644 plugins/cordova-plugin-camera/doc/pl/index.md create mode 100644 plugins/cordova-plugin-camera/doc/ru/index.md create mode 100644 plugins/cordova-plugin-camera/doc/zh/README.md create mode 100644 plugins/cordova-plugin-camera/doc/zh/index.md create mode 100644 plugins/cordova-plugin-camera/jsdoc2md/TEMPLATE.md create mode 100644 plugins/cordova-plugin-camera/package.json create mode 100644 plugins/cordova-plugin-camera/plugin.xml create mode 100644 plugins/cordova-plugin-camera/src/android/CameraLauncher.java create mode 100644 plugins/cordova-plugin-camera/src/android/CordovaUri.java create mode 100644 plugins/cordova-plugin-camera/src/android/ExifHelper.java create mode 100644 plugins/cordova-plugin-camera/src/android/FileHelper.java create mode 100644 plugins/cordova-plugin-camera/src/android/xml/provider_paths.xml create mode 100644 plugins/cordova-plugin-camera/src/blackberry10/index.js create mode 100644 plugins/cordova-plugin-camera/src/browser/CameraProxy.js create mode 100644 plugins/cordova-plugin-camera/src/firefoxos/CameraProxy.js create mode 100644 plugins/cordova-plugin-camera/src/ios/CDVCamera.h create mode 100644 plugins/cordova-plugin-camera/src/ios/CDVCamera.m create mode 100644 plugins/cordova-plugin-camera/src/ios/CDVExif.h create mode 100644 plugins/cordova-plugin-camera/src/ios/CDVJpegHeaderWriter.h create mode 100644 plugins/cordova-plugin-camera/src/ios/CDVJpegHeaderWriter.m create mode 100644 plugins/cordova-plugin-camera/src/ios/UIImage+CropScaleOrientation.h create mode 100644 plugins/cordova-plugin-camera/src/ios/UIImage+CropScaleOrientation.m create mode 100644 plugins/cordova-plugin-camera/src/ubuntu/CaptureWidget.qml create mode 100644 plugins/cordova-plugin-camera/src/ubuntu/back.png create mode 100644 plugins/cordova-plugin-camera/src/ubuntu/camera.cpp create mode 100644 plugins/cordova-plugin-camera/src/ubuntu/camera.h create mode 100644 plugins/cordova-plugin-camera/src/ubuntu/shoot.png create mode 100644 plugins/cordova-plugin-camera/src/ubuntu/toolbar-left.png create mode 100644 plugins/cordova-plugin-camera/src/ubuntu/toolbar-middle.png create mode 100644 plugins/cordova-plugin-camera/src/ubuntu/toolbar-right.png create mode 100644 plugins/cordova-plugin-camera/src/windows/CameraProxy.js create mode 100644 plugins/cordova-plugin-camera/src/wp/Camera.cs create mode 100644 plugins/cordova-plugin-camera/tests/ios/.npmignore create mode 100644 plugins/cordova-plugin-camera/tests/ios/CDVCameraTest.xcworkspace/contents.xcworkspacedata create mode 100644 plugins/cordova-plugin-camera/tests/ios/CDVCameraTest.xcworkspace/xcshareddata/CDVCameraTest.xccheckout create mode 100644 plugins/cordova-plugin-camera/tests/ios/CDVCameraTest.xcworkspace/xcshareddata/xcschemes/CordovaLib.xcscheme create mode 100644 plugins/cordova-plugin-camera/tests/ios/CDVCameraTest/CDVCameraLibTests/CameraTest.m create mode 100644 plugins/cordova-plugin-camera/tests/ios/CDVCameraTest/CDVCameraLibTests/Info.plist create mode 100644 plugins/cordova-plugin-camera/tests/ios/CDVCameraTest/CDVCameraTest.xcodeproj/project.pbxproj create mode 100644 plugins/cordova-plugin-camera/tests/ios/CDVCameraTest/CDVCameraTest.xcodeproj/project.xcworkspace/contents.xcworkspacedata create mode 100644 plugins/cordova-plugin-camera/tests/ios/CDVCameraTest/CDVCameraTest.xcodeproj/project.xcworkspace/xcshareddata/CDVCameraTest.xccheckout create mode 100644 plugins/cordova-plugin-camera/tests/ios/CDVCameraTest/CDVCameraTest.xcodeproj/xcshareddata/xcschemes/CDVCameraLib.xcscheme create mode 100644 plugins/cordova-plugin-camera/tests/ios/CDVCameraTest/CDVCameraTest.xcodeproj/xcshareddata/xcschemes/CDVCameraLibTests.xcscheme create mode 100644 plugins/cordova-plugin-camera/tests/ios/README.md create mode 100644 plugins/cordova-plugin-camera/tests/ios/doc/de/README.md create mode 100644 plugins/cordova-plugin-camera/tests/ios/doc/es/README.md create mode 100644 plugins/cordova-plugin-camera/tests/ios/doc/fr/README.md create mode 100644 plugins/cordova-plugin-camera/tests/ios/doc/it/README.md create mode 100644 plugins/cordova-plugin-camera/tests/ios/doc/ja/README.md create mode 100644 plugins/cordova-plugin-camera/tests/ios/doc/ko/README.md create mode 100644 plugins/cordova-plugin-camera/tests/ios/doc/pl/README.md create mode 100644 plugins/cordova-plugin-camera/tests/ios/doc/zh/README.md create mode 100644 plugins/cordova-plugin-camera/tests/ios/package.json create mode 100644 plugins/cordova-plugin-camera/tests/package.json create mode 100644 plugins/cordova-plugin-camera/tests/plugin.xml create mode 100644 plugins/cordova-plugin-camera/tests/tests.js create mode 100644 plugins/cordova-plugin-camera/types/index.d.ts create mode 100644 plugins/cordova-plugin-camera/www/Camera.js create mode 100644 plugins/cordova-plugin-camera/www/CameraConstants.js create mode 100644 plugins/cordova-plugin-camera/www/CameraPopoverHandle.js create mode 100644 plugins/cordova-plugin-camera/www/CameraPopoverOptions.js create mode 100644 plugins/cordova-plugin-camera/www/blackberry10/assets/camera.html create mode 100644 plugins/cordova-plugin-camera/www/blackberry10/assets/camera.js create mode 100644 plugins/cordova-plugin-camera/www/ios/CameraPopoverHandle.js create mode 100644 plugins/cordova-plugin-compat/README.md create mode 100644 plugins/cordova-plugin-compat/RELEASENOTES.md create mode 100644 plugins/cordova-plugin-compat/package.json create mode 100644 plugins/cordova-plugin-compat/plugin.xml create mode 100644 plugins/cordova-plugin-compat/src/android/BuildHelper.java create mode 100644 plugins/cordova-plugin-compat/src/android/PermissionHelper.java create mode 100644 plugins/cordova-plugin-file/CONTRIBUTING.md create mode 100644 plugins/cordova-plugin-file/LICENSE create mode 100644 plugins/cordova-plugin-file/NOTICE create mode 100644 plugins/cordova-plugin-file/README.md create mode 100644 plugins/cordova-plugin-file/RELEASENOTES.md create mode 100644 plugins/cordova-plugin-file/doc/de/README.md create mode 100644 plugins/cordova-plugin-file/doc/de/index.md create mode 100644 plugins/cordova-plugin-file/doc/de/plugins.md create mode 100644 plugins/cordova-plugin-file/doc/es/README.md create mode 100644 plugins/cordova-plugin-file/doc/es/index.md create mode 100644 plugins/cordova-plugin-file/doc/es/plugins.md create mode 100644 plugins/cordova-plugin-file/doc/fr/README.md create mode 100644 plugins/cordova-plugin-file/doc/fr/index.md create mode 100644 plugins/cordova-plugin-file/doc/fr/plugins.md create mode 100644 plugins/cordova-plugin-file/doc/it/README.md create mode 100644 plugins/cordova-plugin-file/doc/it/index.md create mode 100644 plugins/cordova-plugin-file/doc/it/plugins.md create mode 100644 plugins/cordova-plugin-file/doc/ja/README.md create mode 100644 plugins/cordova-plugin-file/doc/ja/index.md create mode 100644 plugins/cordova-plugin-file/doc/ja/plugins.md create mode 100644 plugins/cordova-plugin-file/doc/ko/README.md create mode 100644 plugins/cordova-plugin-file/doc/ko/index.md create mode 100644 plugins/cordova-plugin-file/doc/ko/plugins.md create mode 100644 plugins/cordova-plugin-file/doc/pl/README.md create mode 100644 plugins/cordova-plugin-file/doc/pl/index.md create mode 100644 plugins/cordova-plugin-file/doc/pl/plugins.md create mode 100644 plugins/cordova-plugin-file/doc/plugins.md create mode 100644 plugins/cordova-plugin-file/doc/ru/index.md create mode 100644 plugins/cordova-plugin-file/doc/ru/plugins.md create mode 100644 plugins/cordova-plugin-file/doc/zh/README.md create mode 100644 plugins/cordova-plugin-file/doc/zh/index.md create mode 100644 plugins/cordova-plugin-file/doc/zh/plugins.md create mode 100644 plugins/cordova-plugin-file/package.json create mode 100644 plugins/cordova-plugin-file/plugin.xml create mode 100644 plugins/cordova-plugin-file/src/android/AssetFilesystem.java create mode 100644 plugins/cordova-plugin-file/src/android/ContentFilesystem.java create mode 100644 plugins/cordova-plugin-file/src/android/DirectoryManager.java create mode 100644 plugins/cordova-plugin-file/src/android/EncodingException.java create mode 100644 plugins/cordova-plugin-file/src/android/FileExistsException.java create mode 100644 plugins/cordova-plugin-file/src/android/FileUtils.java create mode 100644 plugins/cordova-plugin-file/src/android/Filesystem.java create mode 100644 plugins/cordova-plugin-file/src/android/InvalidModificationException.java create mode 100644 plugins/cordova-plugin-file/src/android/LocalFilesystem.java create mode 100644 plugins/cordova-plugin-file/src/android/LocalFilesystemURL.java create mode 100644 plugins/cordova-plugin-file/src/android/NoModificationAllowedException.java create mode 100644 plugins/cordova-plugin-file/src/android/PendingRequests.java create mode 100644 plugins/cordova-plugin-file/src/android/TypeMismatchException.java create mode 100644 plugins/cordova-plugin-file/src/android/build-extras.gradle create mode 100644 plugins/cordova-plugin-file/src/blackberry10/index.js create mode 100644 plugins/cordova-plugin-file/src/browser/FileProxy.js create mode 100644 plugins/cordova-plugin-file/src/firefoxos/FileProxy.js create mode 100644 plugins/cordova-plugin-file/src/ios/CDVAssetLibraryFilesystem.h create mode 100644 plugins/cordova-plugin-file/src/ios/CDVAssetLibraryFilesystem.m create mode 100644 plugins/cordova-plugin-file/src/ios/CDVFile.h create mode 100644 plugins/cordova-plugin-file/src/ios/CDVFile.m create mode 100644 plugins/cordova-plugin-file/src/ios/CDVLocalFilesystem.h create mode 100644 plugins/cordova-plugin-file/src/ios/CDVLocalFilesystem.m create mode 100644 plugins/cordova-plugin-file/src/osx/CDVFile.h create mode 100644 plugins/cordova-plugin-file/src/osx/CDVFile.m create mode 100644 plugins/cordova-plugin-file/src/osx/CDVLocalFilesystem.h create mode 100644 plugins/cordova-plugin-file/src/osx/CDVLocalFilesystem.m create mode 100644 plugins/cordova-plugin-file/src/ubuntu/file.cpp create mode 100644 plugins/cordova-plugin-file/src/ubuntu/file.h create mode 100644 plugins/cordova-plugin-file/src/windows/FileProxy.js create mode 100644 plugins/cordova-plugin-file/src/wp/File.cs create mode 100644 plugins/cordova-plugin-file/tests/package.json create mode 100644 plugins/cordova-plugin-file/tests/plugin.xml create mode 100644 plugins/cordova-plugin-file/tests/src/android/TestContentProvider.java create mode 100644 plugins/cordova-plugin-file/tests/tests.js create mode 100644 plugins/cordova-plugin-file/tests/www/fixtures/asset-test/asset-test.txt create mode 100644 plugins/cordova-plugin-file/types/index.d.ts create mode 100644 plugins/cordova-plugin-file/www/DirectoryEntry.js create mode 100644 plugins/cordova-plugin-file/www/DirectoryReader.js create mode 100644 plugins/cordova-plugin-file/www/Entry.js create mode 100644 plugins/cordova-plugin-file/www/File.js create mode 100644 plugins/cordova-plugin-file/www/FileEntry.js create mode 100644 plugins/cordova-plugin-file/www/FileError.js create mode 100644 plugins/cordova-plugin-file/www/FileReader.js create mode 100644 plugins/cordova-plugin-file/www/FileSystem.js create mode 100644 plugins/cordova-plugin-file/www/FileUploadOptions.js create mode 100644 plugins/cordova-plugin-file/www/FileUploadResult.js create mode 100644 plugins/cordova-plugin-file/www/FileWriter.js create mode 100644 plugins/cordova-plugin-file/www/Flags.js create mode 100644 plugins/cordova-plugin-file/www/LocalFileSystem.js create mode 100644 plugins/cordova-plugin-file/www/Metadata.js create mode 100644 plugins/cordova-plugin-file/www/ProgressEvent.js create mode 100644 plugins/cordova-plugin-file/www/android/FileSystem.js create mode 100644 plugins/cordova-plugin-file/www/blackberry10/.jshintrc create mode 100644 plugins/cordova-plugin-file/www/blackberry10/FileProxy.js create mode 100644 plugins/cordova-plugin-file/www/blackberry10/FileSystem.js create mode 100644 plugins/cordova-plugin-file/www/blackberry10/copyTo.js create mode 100644 plugins/cordova-plugin-file/www/blackberry10/createEntryFromNative.js create mode 100644 plugins/cordova-plugin-file/www/blackberry10/getDirectory.js create mode 100644 plugins/cordova-plugin-file/www/blackberry10/getFile.js create mode 100644 plugins/cordova-plugin-file/www/blackberry10/getFileMetadata.js create mode 100644 plugins/cordova-plugin-file/www/blackberry10/getMetadata.js create mode 100644 plugins/cordova-plugin-file/www/blackberry10/getParent.js create mode 100644 plugins/cordova-plugin-file/www/blackberry10/info.js create mode 100644 plugins/cordova-plugin-file/www/blackberry10/moveTo.js create mode 100644 plugins/cordova-plugin-file/www/blackberry10/readAsArrayBuffer.js create mode 100644 plugins/cordova-plugin-file/www/blackberry10/readAsBinaryString.js create mode 100644 plugins/cordova-plugin-file/www/blackberry10/readAsDataURL.js create mode 100644 plugins/cordova-plugin-file/www/blackberry10/readAsText.js create mode 100644 plugins/cordova-plugin-file/www/blackberry10/readEntries.js create mode 100644 plugins/cordova-plugin-file/www/blackberry10/remove.js create mode 100644 plugins/cordova-plugin-file/www/blackberry10/removeRecursively.js create mode 100644 plugins/cordova-plugin-file/www/blackberry10/requestAllFileSystems.js create mode 100644 plugins/cordova-plugin-file/www/blackberry10/requestAnimationFrame.js create mode 100644 plugins/cordova-plugin-file/www/blackberry10/requestFileSystem.js create mode 100644 plugins/cordova-plugin-file/www/blackberry10/resolveLocalFileSystemURI.js create mode 100644 plugins/cordova-plugin-file/www/blackberry10/setMetadata.js create mode 100644 plugins/cordova-plugin-file/www/blackberry10/truncate.js create mode 100644 plugins/cordova-plugin-file/www/blackberry10/write.js create mode 100644 plugins/cordova-plugin-file/www/browser/FileSystem.js create mode 100644 plugins/cordova-plugin-file/www/browser/Preparing.js create mode 100644 plugins/cordova-plugin-file/www/browser/isChrome.js create mode 100644 plugins/cordova-plugin-file/www/fileSystemPaths.js create mode 100644 plugins/cordova-plugin-file/www/fileSystems-roots.js create mode 100644 plugins/cordova-plugin-file/www/fileSystems.js create mode 100644 plugins/cordova-plugin-file/www/firefoxos/FileSystem.js create mode 100644 plugins/cordova-plugin-file/www/ios/FileSystem.js create mode 100644 plugins/cordova-plugin-file/www/osx/FileSystem.js create mode 100644 plugins/cordova-plugin-file/www/requestFileSystem.js create mode 100644 plugins/cordova-plugin-file/www/resolveLocalFileSystemURI.js create mode 100644 plugins/cordova-plugin-file/www/ubuntu/FileSystem.js create mode 100644 plugins/cordova-plugin-file/www/ubuntu/FileWriter.js create mode 100644 plugins/cordova-plugin-file/www/ubuntu/fileSystems-roots.js create mode 100644 plugins/cordova-plugin-file/www/wp/FileUploadOptions.js diff --git a/.gitignore b/.gitignore index 1ee312a..e7a72b0 100644 --- a/.gitignore +++ b/.gitignore @@ -3,7 +3,7 @@ node_modules/ platforms/ -#plugins/ +plugins/ npm-debug.log .idea/ www/lib/ diff --git a/config.xml b/config.xml index 553e761..2372c31 100644 --- a/config.xml +++ b/config.xml @@ -21,4 +21,6 @@ + + diff --git a/plugins/android.json b/plugins/android.json index 7046885..7241842 100644 --- a/plugins/android.json +++ b/plugins/android.json @@ -27,7 +27,17 @@ }, "cordova-plugin-whitelist": { "PACKAGE_NAME": "com.ionicframework.openeventsplatformapp652778" + }, + "cordova-plugin-file": { + "PACKAGE_NAME": "com.ionicframework.openeventsplatformapp652778" + }, + "cordova-plugin-camera": { + "PACKAGE_NAME": "com.ionicframework.openeventsplatformapp652778" } }, - "dependent_plugins": {} + "dependent_plugins": { + "cordova-plugin-compat": { + "PACKAGE_NAME": "com.ionicframework.openeventsplatformapp652778" + } + } } \ No newline at end of file diff --git a/plugins/cordova-plugin-camera/CONTRIBUTING.md b/plugins/cordova-plugin-camera/CONTRIBUTING.md new file mode 100644 index 0000000..4c8e6a5 --- /dev/null +++ b/plugins/cordova-plugin-camera/CONTRIBUTING.md @@ -0,0 +1,37 @@ + + +# Contributing to Apache Cordova + +Anyone can contribute to Cordova. And we need your contributions. + +There are multiple ways to contribute: report bugs, improve the docs, and +contribute code. + +For instructions on this, start with the +[contribution overview](http://cordova.apache.org/contribute/). + +The details are explained there, but the important items are: + - Sign and submit an Apache ICLA (Contributor License Agreement). + - Have a Jira issue open that corresponds to your contribution. + - Run the tests so your patch doesn't break existing functionality. + +We look forward to your contributions! diff --git a/plugins/cordova-plugin-camera/LICENSE b/plugins/cordova-plugin-camera/LICENSE new file mode 100644 index 0000000..7a4a3ea --- /dev/null +++ b/plugins/cordova-plugin-camera/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/plugins/cordova-plugin-camera/NOTICE b/plugins/cordova-plugin-camera/NOTICE new file mode 100644 index 0000000..8ec56a5 --- /dev/null +++ b/plugins/cordova-plugin-camera/NOTICE @@ -0,0 +1,5 @@ +Apache Cordova +Copyright 2012 The Apache Software Foundation + +This product includes software developed at +The Apache Software Foundation (http://www.apache.org/). diff --git a/plugins/cordova-plugin-camera/README.md b/plugins/cordova-plugin-camera/README.md new file mode 100644 index 0000000..436eefd --- /dev/null +++ b/plugins/cordova-plugin-camera/README.md @@ -0,0 +1,793 @@ +--- +title: Camera +description: Take pictures with the device camera. +--- + + +|Android 4.4|Android 5.1|Android 6.0|iOS 9.3|iOS 10.0|Windows 10 Store|Travis CI| +|:-:|:-:|:-:|:-:|:-:|:-:|:-:| +|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=android-4.4,PLUGIN=cordova-plugin-camera)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=android-4.4,PLUGIN=cordova-plugin-camera/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=android-5.1,PLUGIN=cordova-plugin-camera)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=android-5.1,PLUGIN=cordova-plugin-camera/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=android-6.0,PLUGIN=cordova-plugin-camera)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=android-6.0,PLUGIN=cordova-plugin-camera/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=ios-9.3,PLUGIN=cordova-plugin-camera)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=ios-9.3,PLUGIN=cordova-plugin-camera/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=ios-10.0,PLUGIN=cordova-plugin-camera)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=ios-10.0,PLUGIN=cordova-plugin-camera/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=windows-10-store,PLUGIN=cordova-plugin-camera)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=windows-10-store,PLUGIN=cordova-plugin-camera/)|[![Build Status](https://travis-ci.org/apache/cordova-plugin-camera.svg?branch=master)](https://travis-ci.org/apache/cordova-plugin-camera) + +# cordova-plugin-camera + +This plugin defines a global `navigator.camera` object, which provides an API for taking pictures and for choosing images from +the system's image library. + +Although the object is attached to the global scoped `navigator`, it is not available until after the `deviceready` event. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(navigator.camera); + } + + +## Installation + +This requires cordova 5.0+ + + cordova plugin add cordova-plugin-camera +Older versions of cordova can still install via the __deprecated__ id + + cordova plugin add org.apache.cordova.camera +It is also possible to install via repo url directly ( unstable ) + + cordova plugin add https://github.com/apache/cordova-plugin-camera.git + + +## How to Contribute + +Contributors are welcome! And we need your contributions to keep the project moving forward. You can [report bugs](https://issues.apache.org/jira/issues/?jql=project%20%3D%20CB%20AND%20status%20in%20(Open%2C%20%22In%20Progress%22%2C%20Reopened)%20AND%20resolution%20%3D%20Unresolved%20AND%20component%20%3D%20%22Plugin%20Camera%22%20ORDER%20BY%20priority%20DESC%2C%20summary%20ASC%2C%20updatedDate%20DESC), improve the documentation, or [contribute code](https://github.com/apache/cordova-plugin-camera/pulls). + +There is a specific [contributor workflow](http://wiki.apache.org/cordova/ContributorWorkflow) we recommend. Start reading there. More information is available on [our wiki](http://wiki.apache.org/cordova). + +:warning: **Found an issue?** File it on [JIRA issue tracker](https://issues.apache.org/jira/issues/?jql=project%20%3D%20CB%20AND%20status%20in%20(Open%2C%20%22In%20Progress%22%2C%20Reopened)%20AND%20resolution%20%3D%20Unresolved%20AND%20component%20%3D%20%22Plugin%20Camera%22%20ORDER%20BY%20priority%20DESC%2C%20summary%20ASC%2C%20updatedDate%20DESC). + +**Have a solution?** Send a [Pull Request](https://github.com/apache/cordova-plugin-camera/pulls). + +In order for your changes to be accepted, you need to sign and submit an Apache [ICLA](http://www.apache.org/licenses/#clas) (Individual Contributor License Agreement). Then your name will appear on the list of CLAs signed by [non-committers](https://people.apache.org/committer-index.html#unlistedclas) or [Cordova committers](http://people.apache.org/committers-by-project.html#cordova). + +**And don't forget to test and document your code.** + + +## This documentation is generated by a tool + +:warning: Run `npm install` in the plugin repo to enable automatic docs generation if you plan to send a PR. +[jsdoc-to-markdown](https://www.npmjs.com/package/jsdoc-to-markdown) is used to generate the docs. +Documentation consists of template and API docs produced from the plugin JS code and should be regenerated before each commit (done automatically via [husky](https://github.com/typicode/husky), running `npm run gen-docs` script as a `precommit` hook - see `package.json` for details). + + + +### iOS Quirks + +Since iOS 10 it's mandatory to add a `NSCameraUsageDescription` and `NSPhotoLibraryUsageDescription` in the info.plist. + +- `NSCameraUsageDescription` describes the reason that the app accesses the user’s camera. +- `NSPhotoLibraryUsageDescription` describes the reason the app accesses the user's photo library. + +When the system prompts the user to allow access, this string is displayed as part of the dialog box. + +To add this entry you can pass the following variables on plugin install. + +- `CAMERA_USAGE_DESCRIPTION` for `NSCameraUsageDescription` +- `PHOTOLIBRARY_USAGE_DESCRIPTION` for `NSPhotoLibraryUsageDescription` + +Example: + + cordova plugin add cordova-plugin-camera --variable CAMERA_USAGE_DESCRIPTION="your usage message" --variable PHOTOLIBRARY_USAGE_DESCRIPTION="your usage message" + +If you don't pass the variable, the plugin will add an empty string as value. + +--- + +# API Reference + + +* [camera](#module_camera) + * [.getPicture(successCallback, errorCallback, options)](#module_camera.getPicture) + * [.cleanup()](#module_camera.cleanup) + * [.onError](#module_camera.onError) : function + * [.onSuccess](#module_camera.onSuccess) : function + * [.CameraOptions](#module_camera.CameraOptions) : Object + + +* [Camera](#module_Camera) + * [.DestinationType](#module_Camera.DestinationType) : enum + * [.EncodingType](#module_Camera.EncodingType) : enum + * [.MediaType](#module_Camera.MediaType) : enum + * [.PictureSourceType](#module_Camera.PictureSourceType) : enum + * [.PopoverArrowDirection](#module_Camera.PopoverArrowDirection) : enum + * [.Direction](#module_Camera.Direction) : enum + +* [CameraPopoverHandle](#module_CameraPopoverHandle) +* [CameraPopoverOptions](#module_CameraPopoverOptions) + +--- + + + +## camera + + +### camera.getPicture(successCallback, errorCallback, options) +Takes a photo using the camera, or retrieves a photo from the device's +image gallery. The image is passed to the success callback as a +Base64-encoded `String`, or as the URI for the image file. + +The `camera.getPicture` function opens the device's default camera +application that allows users to snap pictures by default - this behavior occurs, +when `Camera.sourceType` equals [`Camera.PictureSourceType.CAMERA`](#module_Camera.PictureSourceType). +Once the user snaps the photo, the camera application closes and the application is restored. + +If `Camera.sourceType` is `Camera.PictureSourceType.PHOTOLIBRARY` or +`Camera.PictureSourceType.SAVEDPHOTOALBUM`, then a dialog displays +that allows users to select an existing image. + +The return value is sent to the [`cameraSuccess`](#module_camera.onSuccess) callback function, in +one of the following formats, depending on the specified +`cameraOptions`: + +- A `String` containing the Base64-encoded photo image. +- A `String` representing the image file location on local storage (default). + +You can do whatever you want with the encoded image or URI, for +example: + +- Render the image in an `` tag, as in the example below +- Save the data locally (`LocalStorage`, [Lawnchair](http://brianleroux.github.com/lawnchair/), etc.) +- Post the data to a remote server + +__NOTE__: Photo resolution on newer devices is quite good. Photos +selected from the device's gallery are not downscaled to a lower +quality, even if a `quality` parameter is specified. To avoid common +memory problems, set `Camera.destinationType` to `FILE_URI` rather +than `DATA_URL`. + +__Supported Platforms__ + +- Android +- BlackBerry +- Browser +- Firefox +- FireOS +- iOS +- Windows +- WP8 +- Ubuntu + +More examples [here](#camera-getPicture-examples). Quirks [here](#camera-getPicture-quirks). + +**Kind**: static method of [camera](#module_camera) + +| Param | Type | Description | +| --- | --- | --- | +| successCallback | [onSuccess](#module_camera.onSuccess) | | +| errorCallback | [onError](#module_camera.onError) | | +| options | [CameraOptions](#module_camera.CameraOptions) | CameraOptions | + +**Example** +```js +navigator.camera.getPicture(cameraSuccess, cameraError, cameraOptions); +``` + + +### camera.cleanup() +Removes intermediate image files that are kept in temporary storage +after calling [`camera.getPicture`](#module_camera.getPicture). Applies only when the value of +`Camera.sourceType` equals `Camera.PictureSourceType.CAMERA` and the +`Camera.destinationType` equals `Camera.DestinationType.FILE_URI`. + +__Supported Platforms__ + +- iOS + +**Kind**: static method of [camera](#module_camera) +**Example** +```js +navigator.camera.cleanup(onSuccess, onFail); + +function onSuccess() { + console.log("Camera cleanup success.") +} + +function onFail(message) { + alert('Failed because: ' + message); +} +``` + + +### camera.onError : function +Callback function that provides an error message. + +**Kind**: static typedef of [camera](#module_camera) + +| Param | Type | Description | +| --- | --- | --- | +| message | string | The message is provided by the device's native code. | + + + +### camera.onSuccess : function +Callback function that provides the image data. + +**Kind**: static typedef of [camera](#module_camera) + +| Param | Type | Description | +| --- | --- | --- | +| imageData | string | Base64 encoding of the image data, _or_ the image file URI, depending on [`cameraOptions`](#module_camera.CameraOptions) in effect. | + +**Example** +```js +// Show image +// +function cameraCallback(imageData) { + var image = document.getElementById('myImage'); + image.src = "data:image/jpeg;base64," + imageData; +} +``` + + +### camera.CameraOptions : Object +Optional parameters to customize the camera settings. +* [Quirks](#CameraOptions-quirks) + +**Kind**: static typedef of [camera](#module_camera) +**Properties** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| quality | number | 50 | Quality of the saved image, expressed as a range of 0-100, where 100 is typically full resolution with no loss from file compression. (Note that information about the camera's resolution is unavailable.) | +| destinationType | [DestinationType](#module_Camera.DestinationType) | FILE_URI | Choose the format of the return value. | +| sourceType | [PictureSourceType](#module_Camera.PictureSourceType) | CAMERA | Set the source of the picture. | +| allowEdit | Boolean | true | Allow simple editing of image before selection. | +| encodingType | [EncodingType](#module_Camera.EncodingType) | JPEG | Choose the returned image file's encoding. | +| targetWidth | number | | Width in pixels to scale image. Must be used with `targetHeight`. Aspect ratio remains constant. | +| targetHeight | number | | Height in pixels to scale image. Must be used with `targetWidth`. Aspect ratio remains constant. | +| mediaType | [MediaType](#module_Camera.MediaType) | PICTURE | Set the type of media to select from. Only works when `PictureSourceType` is `PHOTOLIBRARY` or `SAVEDPHOTOALBUM`. | +| correctOrientation | Boolean | | Rotate the image to correct for the orientation of the device during capture. | +| saveToPhotoAlbum | Boolean | | Save the image to the photo album on the device after capture. | +| popoverOptions | [CameraPopoverOptions](#module_CameraPopoverOptions) | | iOS-only options that specify popover location in iPad. | +| cameraDirection | [Direction](#module_Camera.Direction) | BACK | Choose the camera to use (front- or back-facing). | + +--- + + + +## Camera + + +### Camera.DestinationType : enum +Defines the output format of `Camera.getPicture` call. +_Note:_ On iOS passing `DestinationType.NATIVE_URI` along with +`PictureSourceType.PHOTOLIBRARY` or `PictureSourceType.SAVEDPHOTOALBUM` will +disable any image modifications (resize, quality change, cropping, etc.) due +to implementation specific. + +**Kind**: static enum property of [Camera](#module_Camera) +**Properties** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| DATA_URL | number | 0 | Return base64 encoded string. DATA_URL can be very memory intensive and cause app crashes or out of memory errors. Use FILE_URI or NATIVE_URI if possible | +| FILE_URI | number | 1 | Return file uri (content://media/external/images/media/2 for Android) | +| NATIVE_URI | number | 2 | Return native uri (eg. asset-library://... for iOS) | + + + +### Camera.EncodingType : enum +**Kind**: static enum property of [Camera](#module_Camera) +**Properties** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| JPEG | number | 0 | Return JPEG encoded image | +| PNG | number | 1 | Return PNG encoded image | + + + +### Camera.MediaType : enum +**Kind**: static enum property of [Camera](#module_Camera) +**Properties** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| PICTURE | number | 0 | Allow selection of still pictures only. DEFAULT. Will return format specified via DestinationType | +| VIDEO | number | 1 | Allow selection of video only, ONLY RETURNS URL | +| ALLMEDIA | number | 2 | Allow selection from all media types | + + + +### Camera.PictureSourceType : enum +Defines the output format of `Camera.getPicture` call. +_Note:_ On iOS passing `PictureSourceType.PHOTOLIBRARY` or `PictureSourceType.SAVEDPHOTOALBUM` +along with `DestinationType.NATIVE_URI` will disable any image modifications (resize, quality +change, cropping, etc.) due to implementation specific. + +**Kind**: static enum property of [Camera](#module_Camera) +**Properties** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| PHOTOLIBRARY | number | 0 | Choose image from the device's photo library (same as SAVEDPHOTOALBUM for Android) | +| CAMERA | number | 1 | Take picture from camera | +| SAVEDPHOTOALBUM | number | 2 | Choose image only from the device's Camera Roll album (same as PHOTOLIBRARY for Android) | + + + +### Camera.PopoverArrowDirection : enum +Matches iOS UIPopoverArrowDirection constants to specify arrow location on popover. + +**Kind**: static enum property of [Camera](#module_Camera) +**Properties** + +| Name | Type | Default | +| --- | --- | --- | +| ARROW_UP | number | 1 | +| ARROW_DOWN | number | 2 | +| ARROW_LEFT | number | 4 | +| ARROW_RIGHT | number | 8 | +| ARROW_ANY | number | 15 | + + + +### Camera.Direction : enum +**Kind**: static enum property of [Camera](#module_Camera) +**Properties** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| BACK | number | 0 | Use the back-facing camera | +| FRONT | number | 1 | Use the front-facing camera | + +--- + + + +## CameraPopoverOptions +iOS-only parameters that specify the anchor element location and arrow +direction of the popover when selecting images from an iPad's library +or album. +Note that the size of the popover may change to adjust to the +direction of the arrow and orientation of the screen. Make sure to +account for orientation changes when specifying the anchor element +location. + + +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| [x] | Number | 0 | x pixel coordinate of screen element onto which to anchor the popover. | +| [y] | Number | 32 | y pixel coordinate of screen element onto which to anchor the popover. | +| [width] | Number | 320 | width, in pixels, of the screen element onto which to anchor the popover. | +| [height] | Number | 480 | height, in pixels, of the screen element onto which to anchor the popover. | +| [arrowDir] | [PopoverArrowDirection](#module_Camera.PopoverArrowDirection) | ARROW_ANY | Direction the arrow on the popover should point. | + +--- + + + +## CameraPopoverHandle +A handle to an image picker popover. + +__Supported Platforms__ + +- iOS + +**Example** +```js +navigator.camera.getPicture(onSuccess, onFail, +{ + destinationType: Camera.DestinationType.FILE_URI, + sourceType: Camera.PictureSourceType.PHOTOLIBRARY, + popoverOptions: new CameraPopoverOptions(300, 300, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY) +}); + +// Reposition the popover if the orientation changes. +window.onorientationchange = function() { + var cameraPopoverHandle = new CameraPopoverHandle(); + var cameraPopoverOptions = new CameraPopoverOptions(0, 0, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY); + cameraPopoverHandle.setPosition(cameraPopoverOptions); +} +``` +--- + + +## `camera.getPicture` Errata + +#### Example + +Take a photo and retrieve the image's file location: + + navigator.camera.getPicture(onSuccess, onFail, { quality: 50, + destinationType: Camera.DestinationType.FILE_URI }); + + function onSuccess(imageURI) { + var image = document.getElementById('myImage'); + image.src = imageURI; + } + + function onFail(message) { + alert('Failed because: ' + message); + } + +Take a photo and retrieve it as a Base64-encoded image: + + /** + * Warning: Using DATA_URL is not recommended! The DATA_URL destination + * type is very memory intensive, even with a low quality setting. Using it + * can result in out of memory errors and application crashes. Use FILE_URI + * or NATIVE_URI instead. + */ + navigator.camera.getPicture(onSuccess, onFail, { quality: 25, + destinationType: Camera.DestinationType.DATA_URL + }); + + function onSuccess(imageData) { + var image = document.getElementById('myImage'); + image.src = "data:image/jpeg;base64," + imageData; + } + + function onFail(message) { + alert('Failed because: ' + message); + } + +#### Preferences (iOS) + +- __CameraUsesGeolocation__ (boolean, defaults to false). For capturing JPEGs, set to true to get geolocation data in the EXIF header. This will trigger a request for geolocation permissions if set to true. + + + +#### Amazon Fire OS Quirks + +Amazon Fire OS uses intents to launch the camera activity on the device to capture +images, and on phones with low memory, the Cordova activity may be killed. In this +scenario, the image may not appear when the Cordova activity is restored. + +#### Android Quirks + +Android uses intents to launch the camera activity on the device to capture +images, and on phones with low memory, the Cordova activity may be killed. In this +scenario, the result from the plugin call will be delivered via the resume event. +See [the Android Lifecycle guide][android_lifecycle] +for more information. The `pendingResult.result` value will contain the value that +would be passed to the callbacks (either the URI/URL or an error message). Check +the `pendingResult.pluginStatus` to determine whether or not the call was +successful. + +#### Browser Quirks + +Can only return photos as Base64-encoded image. + +#### Firefox OS Quirks + +Camera plugin is currently implemented using [Web Activities][web_activities]. + +#### iOS Quirks + +Including a JavaScript `alert()` in either of the callback functions +can cause problems. Wrap the alert within a `setTimeout()` to allow +the iOS image picker or popover to fully close before the alert +displays: + + setTimeout(function() { + // do your thing here! + }, 0); + +#### Windows Phone 7 Quirks + +Invoking the native camera application while the device is connected +via Zune does not work, and triggers an error callback. + +#### Windows quirks + +On Windows Phone 8.1 using `SAVEDPHOTOALBUM` or `PHOTOLIBRARY` as a source type causes application to suspend until file picker returns the selected image and +then restore with start page as defined in app's `config.xml`. In case when `camera.getPicture` was called from different page, this will lead to reloading +start page from scratch and success and error callbacks will never be called. + +To avoid this we suggest using SPA pattern or call `camera.getPicture` only from your app's start page. + +More information about Windows Phone 8.1 picker APIs is here: [How to continue your Windows Phone app after calling a file picker](https://msdn.microsoft.com/en-us/library/windows/apps/dn720490.aspx) + +#### Tizen Quirks + +Tizen only supports a `destinationType` of +`Camera.DestinationType.FILE_URI` and a `sourceType` of +`Camera.PictureSourceType.PHOTOLIBRARY`. + + +## `CameraOptions` Errata + +#### Amazon Fire OS Quirks + +- Any `cameraDirection` value results in a back-facing photo. + +- Ignores the `allowEdit` parameter. + +- `Camera.PictureSourceType.PHOTOLIBRARY` and `Camera.PictureSourceType.SAVEDPHOTOALBUM` both display the same photo album. + +#### Android Quirks + +- Any `cameraDirection` value results in a back-facing photo. + +- **`allowEdit` is unpredictable on Android and it should not be used!** The Android implementation of this plugin tries to find and use an application on the user's device to do image cropping. The plugin has no control over what application the user selects to perform the image cropping and it is very possible that the user could choose an incompatible option and cause the plugin to fail. This sometimes works because most devices come with an application that handles cropping in a way that is compatible with this plugin (Google Plus Photos), but it is unwise to rely on that being the case. If image editing is essential to your application, consider seeking a third party library or plugin that provides its own image editing utility for a more robust solution. + +- `Camera.PictureSourceType.PHOTOLIBRARY` and `Camera.PictureSourceType.SAVEDPHOTOALBUM` both display the same photo album. + +- Ignores the `encodingType` parameter if the image is unedited (i.e. `quality` is 100, `correctOrientation` is false, and no `targetHeight` or `targetWidth` are specified). The `CAMERA` source will always return the JPEG file given by the native camera and the `PHOTOLIBRARY` and `SAVEDPHOTOALBUM` sources will return the selected file in its existing encoding. + +#### BlackBerry 10 Quirks + +- Ignores the `quality` parameter. + +- Ignores the `allowEdit` parameter. + +- `Camera.MediaType` is not supported. + +- Ignores the `correctOrientation` parameter. + +- Ignores the `cameraDirection` parameter. + +#### Firefox OS Quirks + +- Ignores the `quality` parameter. + +- `Camera.DestinationType` is ignored and equals `1` (image file URI) + +- Ignores the `allowEdit` parameter. + +- Ignores the `PictureSourceType` parameter (user chooses it in a dialog window) + +- Ignores the `encodingType` + +- Ignores the `targetWidth` and `targetHeight` + +- `Camera.MediaType` is not supported. + +- Ignores the `correctOrientation` parameter. + +- Ignores the `cameraDirection` parameter. + +#### iOS Quirks + +- When using `destinationType.FILE_URI`, photos are saved in the application's temporary directory. The contents of the application's temporary directory is deleted when the application ends. + +- When using `destinationType.NATIVE_URI` and `sourceType.CAMERA`, photos are saved in the saved photo album regardless on the value of `saveToPhotoAlbum` parameter. + +- When using `destinationType.NATIVE_URI` and `sourceType.PHOTOLIBRARY` or `sourceType.SAVEDPHOTOALBUM`, all editing options are ignored and link is returned to original picture. + +#### Tizen Quirks + +- options not supported + +- always returns a FILE URI + +#### Windows Phone 7 and 8 Quirks + +- Ignores the `allowEdit` parameter. + +- Ignores the `correctOrientation` parameter. + +- Ignores the `cameraDirection` parameter. + +- Ignores the `saveToPhotoAlbum` parameter. IMPORTANT: All images taken with the WP8/8 Cordova camera API are always copied to the phone's camera roll. Depending on the user's settings, this could also mean the image is auto-uploaded to their OneDrive. This could potentially mean the image is available to a wider audience than your app intended. If this is a blocker for your application, you will need to implement the CameraCaptureTask as [documented on MSDN][msdn_wp8_docs]. You may also comment or up-vote the related issue in the [issue tracker][wp8_bug]. + +- Ignores the `mediaType` property of `cameraOptions` as the Windows Phone SDK does not provide a way to choose videos from PHOTOLIBRARY. + +[android_lifecycle]: http://cordova.apache.org/docs/en/dev/guide/platforms/android/lifecycle.html +[web_activities]: https://hacks.mozilla.org/2013/01/introducing-web-activities/ +[wp8_bug]: https://issues.apache.org/jira/browse/CB-2083 +[msdn_wp8_docs]: http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh394006.aspx + +## Sample: Take Pictures, Select Pictures from the Picture Library, and Get Thumbnails + +The Camera plugin allows you to do things like open the device's Camera app and take a picture, or open the file picker and select one. The code snippets in this section demonstrate different tasks including: + +* Open the Camera app and [take a Picture](#takePicture) +* Take a picture and [return thumbnails](#getThumbnails) (resized picture) +* Take a picture and [generate a FileEntry object](#convert) +* [Select a file](#selectFile) from the picture library +* Select a JPEG image and [return thumbnails](#getFileThumbnails) (resized image) +* Select an image and [generate a FileEntry object](#convert) + +## Take a Picture + +Before you can take a picture, you need to set some Camera plugin options to pass into the Camera plugin's `getPicture` function. Here is a common set of recommendations. In this example, you create the object that you will use for the Camera options, and set the `sourceType` dynamically to support both the Camera app and the file picker. + +```js +function setOptions(srcType) { + var options = { + // Some common settings are 20, 50, and 100 + quality: 50, + destinationType: Camera.DestinationType.FILE_URI, + // In this app, dynamically set the picture source, Camera or photo gallery + sourceType: srcType, + encodingType: Camera.EncodingType.JPEG, + mediaType: Camera.MediaType.PICTURE, + allowEdit: true, + correctOrientation: true //Corrects Android orientation quirks + } + return options; +} +``` + +Typically, you want to use a FILE_URI instead of a DATA_URL to avoid most memory issues. JPEG is the recommended encoding type for Android. + +You take a picture by passing in the options object to `getPicture`, which takes a CameraOptions object as the third argument. When you call `setOptions`, pass `Camera.PictureSourceType.CAMERA` as the picture source. + +```js +function openCamera(selection) { + + var srcType = Camera.PictureSourceType.CAMERA; + var options = setOptions(srcType); + var func = createNewFileEntry; + + navigator.camera.getPicture(function cameraSuccess(imageUri) { + + displayImage(imageUri); + // You may choose to copy the picture, save it somewhere, or upload. + func(imageUri); + + }, function cameraError(error) { + console.debug("Unable to obtain picture: " + error, "app"); + + }, options); +} +``` + +Once you take the picture, you can display it or do something else. In this example, call the app's `displayImage` function from the preceding code. + +```js +function displayImage(imgUri) { + + var elem = document.getElementById('imageFile'); + elem.src = imgUri; +} +``` + +To display the image on some platforms, you might need to include the main part of the URI in the Content-Security-Policy `` element in index.html. For example, on Windows 10, you can include `ms-appdata:` in your `` element. Here is an example. + +```html + +``` + +## Take a Picture and Return Thumbnails (Resize the Picture) + +To get smaller images, you can return a resized image by passing both `targetHeight` and `targetWidth` values with your CameraOptions object. In this example, you resize the returned image to fit in a 100px by 100px box (the aspect ratio is maintained, so 100px is either the height or width, whichever is greater in the source). + +```js +function openCamera(selection) { + + var srcType = Camera.PictureSourceType.CAMERA; + var options = setOptions(srcType); + var func = createNewFileEntry; + + if (selection == "camera-thmb") { + options.targetHeight = 100; + options.targetWidth = 100; + } + + navigator.camera.getPicture(function cameraSuccess(imageUri) { + + // Do something + + }, function cameraError(error) { + console.debug("Unable to obtain picture: " + error, "app"); + + }, options); +} +``` + +## Select a File from the Picture Library + +When selecting a file using the file picker, you also need to set the CameraOptions object. In this example, set the `sourceType` to `Camera.PictureSourceType.SAVEDPHOTOALBUM`. To open the file picker, call `getPicture` just as you did in the previous example, passing in the success and error callbacks along with CameraOptions object. + +```js +function openFilePicker(selection) { + + var srcType = Camera.PictureSourceType.SAVEDPHOTOALBUM; + var options = setOptions(srcType); + var func = createNewFileEntry; + + navigator.camera.getPicture(function cameraSuccess(imageUri) { + + // Do something + + }, function cameraError(error) { + console.debug("Unable to obtain picture: " + error, "app"); + + }, options); +} +``` + +## Select an Image and Return Thumbnails (resized images) + +Resizing a file selected with the file picker works just like resizing using the Camera app; set the `targetHeight` and `targetWidth` options. + +```js +function openFilePicker(selection) { + + var srcType = Camera.PictureSourceType.SAVEDPHOTOALBUM; + var options = setOptions(srcType); + var func = createNewFileEntry; + + if (selection == "picker-thmb") { + // To downscale a selected image, + // Camera.EncodingType (e.g., JPEG) must match the selected image type. + options.targetHeight = 100; + options.targetWidth = 100; + } + + navigator.camera.getPicture(function cameraSuccess(imageUri) { + + // Do something with image + + }, function cameraError(error) { + console.debug("Unable to obtain picture: " + error, "app"); + + }, options); +} +``` + +## Take a picture and get a FileEntry Object + +If you want to do something like copy the image to another location, or upload it somewhere using the FileTransfer plugin, you need to get a FileEntry object for the returned picture. To do that, call `window.resolveLocalFileSystemURL` on the file URI returned by the Camera app. If you need to use a FileEntry object, set the `destinationType` to `Camera.DestinationType.FILE_URI` in your CameraOptions object (this is also the default value). + +>*Note* You need the [File plugin](https://www.npmjs.com/package/cordova-plugin-file) to call `window.resolveLocalFileSystemURL`. + +Here is the call to `window.resolveLocalFileSystemURL`. The image URI is passed to this function from the success callback of `getPicture`. The success handler of `resolveLocalFileSystemURL` receives the FileEntry object. + +```js +function getFileEntry(imgUri) { + window.resolveLocalFileSystemURL(imgUri, function success(fileEntry) { + + // Do something with the FileEntry object, like write to it, upload it, etc. + // writeFile(fileEntry, imgUri); + console.log("got file: " + fileEntry.fullPath); + // displayFileData(fileEntry.nativeURL, "Native URL"); + + }, function () { + // If don't get the FileEntry (which may happen when testing + // on some emulators), copy to a new FileEntry. + createNewFileEntry(imgUri); + }); +} +``` + +In the example shown in the preceding code, you call the app's `createNewFileEntry` function if you don't get a valid FileEntry object. The image URI returned from the Camera app should result in a valid FileEntry, but platform behavior on some emulators may be different for files returned from the file picker. + +>*Note* To see an example of writing to a FileEntry, see the [File plugin README](https://www.npmjs.com/package/cordova-plugin-file). + +The code shown here creates a file in your app's cache (in sandboxed storage) named `tempFile.jpeg`. With the new FileEntry object, you can copy the image to the file or do something else like upload it. + +```js +function createNewFileEntry(imgUri) { + window.resolveLocalFileSystemURL(cordova.file.cacheDirectory, function success(dirEntry) { + + // JPEG file + dirEntry.getFile("tempFile.jpeg", { create: true, exclusive: false }, function (fileEntry) { + + // Do something with it, like write to it, upload it, etc. + // writeFile(fileEntry, imgUri); + console.log("got file: " + fileEntry.fullPath); + // displayFileData(fileEntry.fullPath, "File copied to"); + + }, onErrorCreateFile); + + }, onErrorResolveUrl); +} +``` diff --git a/plugins/cordova-plugin-camera/RELEASENOTES.md b/plugins/cordova-plugin-camera/RELEASENOTES.md new file mode 100644 index 0000000..cbb782c --- /dev/null +++ b/plugins/cordova-plugin-camera/RELEASENOTES.md @@ -0,0 +1,367 @@ + +# Release Notes + +### 2.4.1 (Apr 27, 2017) +* [CB-12622](https://issues.apache.org/jira/browse/CB-12622) Updated build badges in `README` +* [CB-12650](https://issues.apache.org/jira/browse/CB-12650) Fix manual test for uploading image +* [CB-12685](https://issues.apache.org/jira/browse/CB-12685) added `package.json` to tests folder +* [CB-12622](https://issues.apache.org/jira/browse/CB-12622) (android) Appium tests: Bust **Android** 6 and 7 permission dialogs +* [CB-12618](https://issues.apache.org/jira/browse/CB-12618) (android) Appium tests: Handle native cling + +### 2.4.0 (Feb 28, 2017) +* [CB-12501](https://issues.apache.org/jira/browse/CB-12501) **Android**: Appium tests don't use `XPath` selectors anymore +* [CB-12469](https://issues.apache.org/jira/browse/CB-12469) Appium tests can now run on **iOS 10** +* [CB-12005](https://issues.apache.org/jira/browse/CB-12005) Changing the `getOrientation` method to return the defined enumerated `EXIF` instead of orientation in degrees for Consistency +* [CB-12368](https://issues.apache.org/jira/browse/CB-12368) Fix permission check on **Android** +* [CB-12353](https://issues.apache.org/jira/browse/CB-12353) Corrected merges usage in `plugin.xml` +* [CB-12369](https://issues.apache.org/jira/browse/CB-12369) Add plugin typings from `DefinitelyTyped` +* [CB-12363](https://issues.apache.org/jira/browse/CB-12363) Added build badges for **iOS 9.3** and **iOS 10.0** +* [CB-12312](https://issues.apache.org/jira/browse/CB-12312) [Appium] [Android] A few changes to the tests: - updated comments on how to run the tests. extra comments around functionality at certain points in the automation. - stub of a resolution checker on test startup - still need to figure out acceptable values. - moved session shutdown to an afterAll clause. - changed resolution determiner from using webview-based values to using the native windows dimensions - this helps as the webview values may be scaled down intentionally by manufacturers (via changing devicePixelRatio). furthermore, since the screen dimension automation is used purely for native UI automation, better to use the dimensions reported by the native context rather than the web context. - when finding elements by XPath, use multiple calls to avoid a Windows emulator + Android bug. Made this pattern consistent in the entire test. +* [CB-12236](https://issues.apache.org/jira/browse/CB-12236) - Fixed RELEASENOTES for cordova-plugin-camera +* [CB-12230](https://issues.apache.org/jira/browse/CB-12230) Removed Windows 8.1 build badges + +### 2.3.1 (Dec 07, 2016) +* [CB-12224](https://issues.apache.org/jira/browse/CB-12224) Updated version and RELEASENOTES.md for release 2.3.1 +* Fix missing license headers. +* [CB-12086](https://issues.apache.org/jira/browse/CB-12086) Regenerate README.md from template +* Added NSPhotoLibraryUsageDescription parameter to example install command Fixing some usages of NSPhotoLibraryUsageDescriptionentry +* Updating compat dependency to 1.1.0 or better +* [CB-11625](https://issues.apache.org/jira/browse/CB-11625) Forgot to add CordovaUri.java to plugin.xml +* [CB-11625](https://issues.apache.org/jira/browse/CB-11625) Files Provider does not work with Android 4.4.4 or lower, and I have no idea why. Working around with CordovaUri +* [CB-11625](https://issues.apache.org/jira/browse/CB-11625) (Android) : Make this work with previous versions of Cordova via cordova-plugin-compat +* BuildConfig from test project crept in source code thanks to Android Studio, removing +* [CB-11625](https://issues.apache.org/jira/browse/CB-11625) Managed to get Content Providers to work with a weird mix of Content Providers and non-Content Providers +* [CB-11625](https://issues.apache.org/jira/browse/CB-11625) Working on fix to API 24 no longer allowing File URIs to be passed across intents +* [CB-11917](https://issues.apache.org/jira/browse/CB-11917) - Remove pull request template checklist item: "iCLA has been submitted…" +* [CB-11832](https://issues.apache.org/jira/browse/CB-11832) Incremented plugin version. + +### 2.3.0 (Sep 08, 2016) +* [CB-11795](https://issues.apache.org/jira/browse/CB-11795) Add 'protective' entry to cordovaDependencies +* [CB-11661](https://issues.apache.org/jira/browse/CB-11661) Add mandatory **iOS 10** privacy description +* [CB-11714](https://issues.apache.org/jira/browse/CB-11714) **windows** added more explicit content-type when converting to target data on canvas +* [CB-11295](https://issues.apache.org/jira/browse/CB-11295) Add **WP8.1** quirk when choosing image from `photoalbum` +* [CB-10067](https://issues.apache.org/jira/browse/CB-10067) Update `PictureSourceType` JSDoc to reflect `README` update +* [CB-9070](https://issues.apache.org/jira/browse/CB-9070) Update `CameraPopoverHandle` docs to reflect `README` update +* Plugin uses `Android Log class` and not `Cordova LOG class` +* [CB-11631](https://issues.apache.org/jira/browse/CB-11631) Appium tests: A working fix for a flaky `selection canceled` failure +* [CB-11709](https://issues.apache.org/jira/browse/CB-11709) Tests should use `resolveLocalFileSystemURL()` instead of deprecated `resolveFileSystemURI()` +* [CB-11695](https://issues.apache.org/jira/browse/CB-11695) Increased session creation timeout for Appium tests +* [CB-11656](https://issues.apache.org/jira/browse/CB-11656) (**Android**) Appium tests: Fixed side menu opening on some more resolutions +* [CB-11376](https://issues.apache.org/jira/browse/CB-11376) (**ios**): fix `CameraUsesGeolocation` error +* [CB-10067](https://issues.apache.org/jira/browse/CB-10067) (**ios**) clarifications on `PictureSourceType` +* [CB-11410](https://issues.apache.org/jira/browse/CB-11410) (**ios**) fix `cameraPopoverHandle.setPosition` +* [CB-9070](https://issues.apache.org/jira/browse/CB-9070) (**ios**) Fixed `CameraPopoverHandle` documentation +* [CB-11447](https://issues.apache.org/jira/browse/CB-11447) Respect output format when retrieving images from gallery +* [CB-11447](https://issues.apache.org/jira/browse/CB-11447) Resolve **iOS** tests failures due to **iOS** quirks +* [CB-11553](https://issues.apache.org/jira/browse/CB-11553) Pend failing Appium tests on Sauce Labs for the time being (reverted from commit b69571724035f41642f3ee612c5b66e1f0c4386c) +* [CB-11553](https://issues.apache.org/jira/browse/CB-11553) Pend failing Appium tests on Sauce Labs for the time being +* [CB-11498](https://issues.apache.org/jira/browse/CB-11498) [**Android**] Appium tests should not fail when there is no camera +* Add badges for paramedic builds on Jenkins +* [CB-11296](https://issues.apache.org/jira/browse/CB-11296) Appium: Better element clicking and session error handling +* [CB-11232](https://issues.apache.org/jira/browse/CB-11232) Appium tests: fixed element tapping on **iOS 9** +* [CB-11183](https://issues.apache.org/jira/browse/CB-11183) Appium tests: Added image verification +* fixed some bad formatting that hid `HTML` tags and added link to sample +* Set **android** quality default value to 50 on the java code +* Moving message in PR template to a comment +* Add pull request template. This closes #213 +* [CB-11228](https://issues.apache.org/jira/browse/CB-11228) **browser**: Add classes for styling purposes +* [CB-10139](https://issues.apache.org/jira/browse/CB-10139) **browser**: Respect target width and height +* [CB-11227](https://issues.apache.org/jira/browse/CB-11227) **browser**: Fix incorrect `mime type` +* [CB-11162](https://issues.apache.org/jira/browse/CB-11162) Appium tests: retry spec on failure +* [CB-4078](https://issues.apache.org/jira/browse/CB-4078) Fix for `orientation/scaling` on **Android 4.4+** devices +* [CB-11165](https://issues.apache.org/jira/browse/CB-11165) removed peer dependency +* [CB-11147](https://issues.apache.org/jira/browse/CB-11147) Appium tests: generate descriptive spec names +* [CB-10996](https://issues.apache.org/jira/browse/CB-10996) Adding front matter to `README.md` +* [CB-11128](https://issues.apache.org/jira/browse/CB-11128) Appum tests: Fixed some of the flaky failures +* [CB-11003](https://issues.apache.org/jira/browse/CB-11003) Added Sample section to the Camera plugin README + +### 2.2.0 (Apr 15, 2016) +* [CB-10873](https://issues.apache.org/jira/browse/CB-10873) Avoid crash due to usage of uninitialized variable when writing geolocation data to image destination. Properly handle 'CameraUsesGeolocation' option by properly setting geolocation data in EXIF header in all cases +* [CB-11073](https://issues.apache.org/jira/browse/CB-11073) Appium tests stability improvements +* Replace `PermissionHelper.java` with `cordova-plugin-compat` +* Making focus handler work only for **windows 10** phone +* [CB-10865](https://issues.apache.org/jira/browse/CB-10865) Run **ios** native tests on **Travis** +* [CB-10120](https://issues.apache.org/jira/browse/CB-10120) Fixing use of constants and `PermissionHelper` +* [CB-10120](https://issues.apache.org/jira/browse/CB-10120) Fix missing CAMERA permission for **Android M** +* [CB-10756](https://issues.apache.org/jira/browse/CB-10756) Adding sterner warnings about `DATA_URL` +* [CB-10460](https://issues.apache.org/jira/browse/CB-10460) `getRealPath` return null in some cases + +### 2.1.1 (Mar 09, 2016) +* [CB-10825](https://issues.apache.org/jira/browse/CB-10825) **Android** should request READ permission for gallery source +* added apache license header to appium files +* [CB-10720](https://issues.apache.org/jira/browse/CB-10720) Fixed spelling, capitalization, and other small issues. +* [CB-10414](https://issues.apache.org/jira/browse/CB-10414) Adding focus handler to resume video when user comes back on leaving the app while preview was running +* Appium tests: adjust swipe distance on **Android** +* [CB-10750](https://issues.apache.org/jira/browse/CB-10750) Appium tests: fail fast if session is irrecoverable +* Adding missing semi colon +* Adding focus handler to make sure filepicker gets launched when app is active on **Windows** +* [CB-10128](https://issues.apache.org/jira/browse/CB-10128) **iOS** Fixed how checks access authorization to camera & library. This closes #146 +* [CB-10636](https://issues.apache.org/jira/browse/CB-10636) Add JSHint for plugins +* [CB-10639](https://issues.apache.org/jira/browse/CB-10639) Appium tests: Added some timeouts, Taking a screenshot on failure, Retry taking a picture up to 3 times, Try to restart the Appium session if it's lost +* [CB-10552](https://issues.apache.org/jira/browse/CB-10552) Replacing images in README.md. +* Added a lot of more cases to get the real path on **Android** +* [CB-10625](https://issues.apache.org/jira/browse/CB-10625) **Android** getPicture fails when getting a photo from the Photo Library - Google Photos +* [CB-10619](https://issues.apache.org/jira/browse/CB-10619) Appium tests: Properly switch to webview on **Android** +* [CB-10397](https://issues.apache.org/jira/browse/CB-10397) Added Appium tests +* [CB-10576](https://issues.apache.org/jira/browse/CB-10576) MobileSpec can't get results for **Windows**-Store 8.1 Builds +* chore: edit package.json license to match SPDX id +* [CB-10539](https://issues.apache.org/jira/browse/CB-10539) Commenting out the verySmallQvga maxResolution option on **Windows** +* [CB-10541](https://issues.apache.org/jira/browse/CB-10541) Changing default maxResoltion to be highestAvailable for CameraCaptureUI on **Windows** +* [CB-10113](https://issues.apache.org/jira/browse/CB-10113) **Browse** - Layer camera UI on top of all! +* [CB-10502](https://issues.apache.org/jira/browse/CB-10502) **Browser** - Fix camera plugin exception in Chrome when click capture. +* Adding comments +* Camera tapping fix on **Windows** + +### 2.1.0 (Jan 15, 2016) +* added `.ratignore` +* [CB-10319](https://issues.apache.org/jira/browse/CB-10319) **Android** Adding reflective helper methods for permission requests +* [CB-9189](https://issues.apache.org/jira/browse/CB-9189) **Android** Implementing `save/restore` API to handle Activity destruction +* [CB-10241](https://issues.apache.org/jira/browse/CB-10241) App Crash cause by Camera Plugin **iOS 7** +* [CB-8940](https://issues.apache.org/jira/browse/CB-8940) Setting `z-index` values to maximum for UI buttons. + +### 2.0.0 (Nov 18, 2015) +* [CB-10035](https://issues.apache.org/jira/browse/CB-10035) Updated `RELEASENOTES` to be newest to oldest +* [CB-8863](https://issues.apache.org/jira/browse/CB-8863) correct block usage for `async` calls +* [CB-5479](https://issues.apache.org/jira/browse/CB-5479) changed `saveToPhotoAlbum` to save uncompressed images for **Android** +* [CB-9169](https://issues.apache.org/jira/browse/CB-9169) Fixed `filetype` for uncompressed images and added quirk for **Android** +* [CB-9446](https://issues.apache.org/jira/browse/CB-9446) Removing `CordovaResource` library code in favour of the code we're supposed to be deprecating because that at least works. +* [CB-9942](https://issues.apache.org/jira/browse/CB-9942) Normalize line endings in Camera plugin docs +* [CB-9910](https://issues.apache.org/jira/browse/CB-9910) Add permission request for some gallery requests for **Android** +* [CB-7668](https://issues.apache.org/jira/browse/CB-7668) Adding a sterner warning for `allowedit` on **Android** +* Fixing contribute link. +* Using the `CordovaResourceApi` to fine paths of files in the background thread. If the file doesn't exist, return the content `URI`. +* Add engine tag for **Cordova-Android 5.0.x** +* [CB-9583](https://issues.apache.org/jira/browse/CB-9583): Added support for **Marshmallow** permissions (**Android 6.0**) +* Try to use `realpath` filename instead of default `modified.jpg` +* [CB-6190](https://issues.apache.org/jira/browse/CB-6190) **iOS** camera plugin ignores quality parameter +* [CB-9633](https://issues.apache.org/jira/browse/CB-9633) **iOS** Taking a Picture With Option `destinationType:NATIVE_URI` doesn't show image +* [CB-9745](https://issues.apache.org/jira/browse/CB-9745) Camera plugin docs should be generated from the source +* [CB-9622](https://issues.apache.org/jira/browse/CB-9622) **WP8** Camera Option `destinationType:NATIVE_URI` is a `NO-OP` +* [CB-9623](https://issues.apache.org/jira/browse/CB-9623) Fixes various issues when `encodingType` set to `png` +* [CB-9591](https://issues.apache.org/jira/browse/CB-9591) Retaining aspect ratio when resizing +* [CB-9443](https://issues.apache.org/jira/browse/CB-9443) Pick correct `maxResolution` +* [CB-9151](https://issues.apache.org/jira/browse/CB-9151) Trigger `captureAction` only once +* [CB-9413](https://issues.apache.org/jira/browse/CB-9413) Close `RandomAccessStream` once copied +* [CB-5661](https://issues.apache.org/jira/browse/CB-5661) Remove outdated **iOS** quirks about memory +* [CB-9349](https://issues.apache.org/jira/browse/CB-9349) Focus control and nice UI +* [CB-9259](https://issues.apache.org/jira/browse/CB-9259) Forgot to add another check on which `URI` we're using when fixing this thing the first time +* [CB-9247](https://issues.apache.org/jira/browse/CB-9247) Added macro to conditionally add `NSData+Base64.h` +* [CB-9247](https://issues.apache.org/jira/browse/CB-9247) Fixes compilation errors with **cordova-ios 4.x** +* Fix returning native url on **Windows**. + +### 1.2.0 (Jun 17, 2015) +* Closing stale pull request: close #84 +* Closing stale pull request: close #66 +* [CB-9128](https://issues.apache.org/jira/browse/CB-9128) cordova-plugin-camera documentation translation: cordova-plugin-camera +* Update docs. This closes #100 +* attempt to fix npm markdown issue +* [CB-8883](https://issues.apache.org/jira/browse/CB-8883) fix picture rotation issue +* one more alias +* Fixed some nit white-space issues, aliased a little more +* major refactor : readability +* Patch for [CB-8498](https://issues.apache.org/jira/browse/CB-8498), this closes #64 +* [CB-8879](https://issues.apache.org/jira/browse/CB-8879) fix stripe issue with correct aspect ratio +* [CB-8601](https://issues.apache.org/jira/browse/CB-8601) - iOS camera unit tests broken +* [CB-7667](https://issues.apache.org/jira/browse/CB-7667) iOS8: Handle case where camera is not authorized (closes #49) +* add missing license header + +### 1.1.0 (May 06, 2015) +* [CB-8943](https://issues.apache.org/jira/browse/CB-8943) fix `PickAndContinue` issue on *Win10Phone* +* [CB-8253](https://issues.apache.org/jira/browse/CB-8253) Fix potential unreleased resources +* [CB-8909](https://issues.apache.org/jira/browse/CB-8909): Remove unused import from File +* [CB-8404](https://issues.apache.org/jira/browse/CB-8404) typo fix `cameraproxy.js` +* [CB-8404](https://issues.apache.org/jira/browse/CB-8404) Rotate camera feed with device orientation +* [CB-8054](https://issues.apache.org/jira/browse/CB-8054) Support taking pictures from file for *WP8* +* [CB-8405](https://issues.apache.org/jira/browse/CB-8405) Use `z-index` instead of `z-order` + +### 1.0.0 (Apr 15, 2015) +* [CB-8780](https://issues.apache.org/jira/browse/CB-8780) - Display popover using main thread. Fixes popover slowness (closes #81) +* [CB-8746](https://issues.apache.org/jira/browse/CB-8746) bumped version of file dependency +* [CB-8746](https://issues.apache.org/jira/browse/CB-8746) gave plugin major version bump +* [CB-8707](https://issues.apache.org/jira/browse/CB-8707) refactoring windows code to improve readability +* [CB-8706](https://issues.apache.org/jira/browse/CB-8706) use filePicker if saveToPhotoAlbum is true +* [CB-8706](https://issues.apache.org/jira/browse/CB-8706) remove unnecessary capabilities from xml +* [CB-8747](https://issues.apache.org/jira/browse/CB-8747) updated dependency, added peer dependency +* [CB-8683](https://issues.apache.org/jira/browse/CB-8683) updated blackberry specific references of org.apache.cordova.camera to cordova-plugin-camera +* [CB-8782](https://issues.apache.org/jira/browse/CB-8782): Updated the docs to talk about the allowEdit quirks, it's not 100% working, but better than it was +* [CB-8782](https://issues.apache.org/jira/browse/CB-8782): Fixed the flow so that we save the cropped image and use it, not the original non-cropped. Crop only supports G+ Photos Crop, other crops may not work, depending on the OEM +* [CB-8740](https://issues.apache.org/jira/browse/CB-8740): Removing FileHelper call that was failing on Samsung Galaxy S3, now that we have a real path, we only need to update the MediaStore, not pull from it in this case +* [CB-8740](https://issues.apache.org/jira/browse/CB-8740): Partial fix for Save Image to Gallery error found in MobileSpec +* [CB-8683](https://issues.apache.org/jira/browse/CB-8683) changed plugin-id to pacakge-name +* [CB-8653](https://issues.apache.org/jira/browse/CB-8653) properly updated translated docs to use new id +* [CB-8653](https://issues.apache.org/jira/browse/CB-8653) updated translated docs to use new id +* [CB-8351](https://issues.apache.org/jira/browse/CB-8351) Fix custom implementation of integerValueForKey (close #79) +* Fix cordova-paramedic path change, build with TRAVIS_BUILD_DIR, use npm to install paramedic +* docs: added 'Windows' to supported platforms +* [CB-8653](https://issues.apache.org/jira/browse/CB-8653) Updated Readme +* [CB-8659](https://issues.apache.org/jira/browse/CB-8659): ios: 4.0.x Compatibility: Remove use of deprecated headers + +### 0.3.6 (Mar 10, 2015) +* Fix localize key for Videos. This closes #58 +* [CB-8235](https://issues.apache.org/jira/browse/CB-8235) android: Fix crash when selecting images from DropBox with spaces in path (close #65) +* add try ... catch for getting image orientation +* [CB-8599](https://issues.apache.org/jira/browse/CB-8599) fix threading issue with cameraPicker (fixes #72) +* [CB-8559](https://issues.apache.org/jira/browse/CB-8559) Integrate TravisCI +* [CB-8438](https://issues.apache.org/jira/browse/CB-8438) cordova-plugin-camera documentation translation: cordova-plugin-camera +* [CB-8538](https://issues.apache.org/jira/browse/CB-8538) Added package.json file + +### 0.3.5 (Feb 04, 2015) +* [CB-8351](https://issues.apache.org/jira/browse/CB-8351) ios: Stop using now-deprecated [NSData base64EncodedString] +* [CB-8351](https://issues.apache.org/jira/browse/CB-8351) ios: Stop using now-deprecated integerValueForKey: class extension +* [CB-8351](https://issues.apache.org/jira/browse/CB-8351) ios: Use argumentForIndex rather than NSArray extension +* [CB-8032](https://issues.apache.org/jira/browse/CB-8032) ios: Add nativeURL external method support for CDVFileSystem->makeEntryForPath:isDirectory: +* [CB-7938](https://issues.apache.org/jira/browse/CB-7938) ios: Added XCTest unit tests project, with stubs (adapted from SplashScreen unit test setup) +* [CB-7937](https://issues.apache.org/jira/browse/CB-7937) ios: Re-factor iOS Camera plugin so that it is testable + +### 0.3.4 (Dec 02, 2014) +* [CB-7977](https://issues.apache.org/jira/browse/CB-7977) Mention `deviceready` in plugin docs +* [CB-7979](https://issues.apache.org/jira/browse/CB-7979) Each plugin doc should have a ## Installation section +* Fix memory leak of image data in `imagePickerControllerReturnImageResult` +* Pass uri to crop instead of pulling the low resolution image out of the intent return (close #43) +* Add orientation support for PNG to Android (closes #45) +* [CB-7700](https://issues.apache.org/jira/browse/CB-7700) cordova-plugin-camera documentation translation: cordova-plugin-camera + +### 0.3.3 (Oct 03, 2014) +* [CB-7600](https://issues.apache.org/jira/browse/CB-7600) Adds informative message to error callback in manual test. + +### 0.3.2 (Sep 17, 2014) +* [CB-7551](https://issues.apache.org/jira/browse/CB-7551) [Camera][iOS 8] Scaled images show a white line +* [CB-7558](https://issues.apache.org/jira/browse/CB-7558) hasPendingOperation flag in Camera plugin's takePicture should be reversed to fix memory errors +* [CB-7557](https://issues.apache.org/jira/browse/CB-7557) Camera plugin tests is missing a File dependency +* [CB-7423](https://issues.apache.org/jira/browse/CB-7423) do cleanup after copyImage manual test +* [CB-7471](https://issues.apache.org/jira/browse/CB-7471) cordova-plugin-camera documentation translation: cordova-plugin-camera +* [CB-7413](https://issues.apache.org/jira/browse/CB-7413) Resolve 'ms-appdata' URIs with File plugin +* Fixed minor bugs with the browser +* [CB-7433](https://issues.apache.org/jira/browse/CB-7433) Adds missing window reference to prevent manual tests failure on Android and iOS +* [CB-7249](https://issues.apache.org/jira/browse/CB-7249) cordova-plugin-camera documentation translation: cordova-plugin-camera +* [CB-4003](https://issues.apache.org/jira/browse/CB-4003) Add config option to not use location information in Camera plugin (and default to not use it) +* [CB-7461](https://issues.apache.org/jira/browse/CB-7461) Geolocation fails in Camera plugin in iOS 8 +* [CB-7378](https://issues.apache.org/jira/browse/CB-7378) Use single Proxy for both windows8 and windows. +* [CB-7378](https://issues.apache.org/jira/browse/CB-7378) Adds support for windows platform +* [CB-7433](https://issues.apache.org/jira/browse/CB-7433) Fixes manual tests failure on windows +* [CB-6958](https://issues.apache.org/jira/browse/CB-6958) Get the correct default for "quality" in the test +* add documentation for manual tests +* [CB-7249](https://issues.apache.org/jira/browse/CB-7249) cordova-plugin-camera documentation translation: cordova-plugin-camera +* [CB-4003](https://issues.apache.org/jira/browse/CB-4003) Add config option to not use location information in Camera plugin (and default to not use it) +* [CB-7461](https://issues.apache.org/jira/browse/CB-7461) Geolocation fails in Camera plugin in iOS 8 +* [CB-7433](https://issues.apache.org/jira/browse/CB-7433) Fixes manual tests failure on windows +* [CB-7378](https://issues.apache.org/jira/browse/CB-7378) Use single Proxy for both windows8 and windows. +* [CB-7378](https://issues.apache.org/jira/browse/CB-7378) Adds support for windows platform +* [CB-6958](https://issues.apache.org/jira/browse/CB-6958) Get the correct default for "quality" in the test +* add documentation for manual tests +* Updated docs for browser +* Added support for the browser +* [CB-7286](https://issues.apache.org/jira/browse/CB-7286) [BlackBerry10] Use getUserMedia if camera card is unavailable +* [CB-7180](https://issues.apache.org/jira/browse/CB-7180) Update Camera plugin to support generic plugin webView UIView (which can be either a UIWebView or WKWebView) +* Renamed test dir, added nested plugin.xml +* [CB-6958](https://issues.apache.org/jira/browse/CB-6958) added manual tests +* [CB-6958](https://issues.apache.org/jira/browse/CB-6958) Port camera tests to plugin-test-framework + +### 0.3.1 (Aug 06, 2014) +* **FFOS** update CameraProxy.js +* [CB-7187](https://issues.apache.org/jira/browse/CB-7187) ios: Add explicit dependency on CoreLocation.framework +* [BlackBerry10] Doc correction - sourceType is supported +* [CB-7071](https://issues.apache.org/jira/browse/CB-7071) android: Fix callback firing before CROP intent is sent when allowEdit=true +* [CB-6875](https://issues.apache.org/jira/browse/CB-6875) android: Handle exception when SDCard is not mounted +* ios: Delete postImage (dead code) +* Prevent NPE on processResiultFromGallery when intent comes null +* Remove iOS doc reference to non-existing navigator.fileMgr API +* Docs updated with some default values +* Removes File plugin dependency from windows8 code. +* Use WinJS functionality to resize image instead of File plugin functionality +* [CB-6127](https://issues.apache.org/jira/browse/CB-6127) Updated translations for docs + +### 0.3.0 (Jun 05, 2014) +* [CB-5895](https://issues.apache.org/jira/browse/CB-5895) documented saveToPhotoAlbum quirk on WP8 +* Remove deprecated symbols for iOS < 6 +* documentation translation: cordova-plugin-camera +* ubuntu: use application directory for images +* [CB-6795](https://issues.apache.org/jira/browse/CB-6795) Add license +* Little fix in code formatting +* [CB-6613](https://issues.apache.org/jira/browse/CB-6613) Use WinJS functionality to get base64-encoded content of image instead of File plugin functionality +* [CB-6612](https://issues.apache.org/jira/browse/CB-6612) camera.getPicture now always returns encoded JPEG image +* Removed invalid note from [CB-5398](https://issues.apache.org/jira/browse/CB-5398) +* [CB-6576](https://issues.apache.org/jira/browse/CB-6576) - Returns a specific error message when app has no access to library. +* [CB-6491](https://issues.apache.org/jira/browse/CB-6491) add CONTRIBUTING.md +* [CB-6546](https://issues.apache.org/jira/browse/CB-6546) android: Fix a couple bugs with allowEdit pull request +* [CB-6546](https://issues.apache.org/jira/browse/CB-6546) android: Add support for allowEdit Camera option + +### 0.2.9 (Apr 17, 2014) +* [CB-6460](https://issues.apache.org/jira/browse/CB-6460): Update license headers +* [CB-6422](https://issues.apache.org/jira/browse/CB-6422): [windows8] use cordova/exec/proxy +* [WP8] When only targetWidth or targetHeight is provided, use it as the only bound +* [CB-4027](https://issues.apache.org/jira/browse/CB-4027), [CB-5102](https://issues.apache.org/jira/browse/CB-5102), [CB-2737](https://issues.apache.org/jira/browse/CB-2737), [CB-2387](https://issues.apache.org/jira/browse/CB-2387): [WP] Fix camera issues, cropping, memory leaks +* [CB-6212](https://issues.apache.org/jira/browse/CB-6212): [iOS] fix warnings compiled under arm64 64-bit +* [BlackBerry10] Add rim xml namespaces declaration +* Add NOTICE file + +### 0.2.8 (Feb 26, 2014) +* [CB-1826](https://issues.apache.org/jira/browse/CB-1826) Catch OOM on gallery image resize + +### 0.2.7 (Feb 05, 2014) +* [CB-4919](https://issues.apache.org/jira/browse/CB-4919) firefox os quirks added and supported platforms list is updated +* getPicture via web activities +* Documented quirk for [CB-5335](https://issues.apache.org/jira/browse/CB-5335) + [CB-5206](https://issues.apache.org/jira/browse/CB-5206) for WP7+8 +* reference the correct firefoxos implementation +* [BlackBerry10] Add permission to access_shared + +### 0.2.6 (Jan 02, 2014) +* [CB-5658](https://issues.apache.org/jira/browse/CB-5658) Add doc/index.md for Camera plugin +* [CB-2442](https://issues.apache.org/jira/browse/CB-2442) [CB-2419](https://issues.apache.org/jira/browse/CB-2419) Use Windows.Storage.ApplicationData.current.localFolder, instead of writing to app package. +* [BlackBerry10] Adding platform level permissions +* [CB-5599](https://issues.apache.org/jira/browse/CB-5599) Android: Catch and ignore OutOfMemoryError in getRotatedBitmap() + +### 0.2.5 (Dec 4, 2013) +* fix camera for firefox os +* getPicture via web activities +* [ubuntu] specify policy_group +* add ubuntu platform +* 1. User Agent detection now detects AmazonWebView. 2. Change to use amazon-fireos as the platform if user agent string contains 'cordova-amazon-fireos' +* Added amazon-fireos platform. + +### 0.2.4 (Oct 28, 2013) +* [CB-5128](https://issues.apache.org/jira/browse/CB-5128): added repo + issue tag to plugin.xml for camera plugin +* [CB-4958](https://issues.apache.org/jira/browse/CB-4958) - iOS - Camera plugin should not show the status bar +* [CB-4919](https://issues.apache.org/jira/browse/CB-4919) updated plugin.xml for FxOS +* [CB-4915](https://issues.apache.org/jira/browse/CB-4915) Incremented plugin version on dev branch. + +### 0.2.3 (Sept 25, 2013) +* [CB-4889](https://issues.apache.org/jira/browse/CB-4889) bumping&resetting version +* [CB-4889](https://issues.apache.org/jira/browse/CB-4889) forgot index.html +* [CB-4889](https://issues.apache.org/jira/browse/CB-4889) renaming core inside cameraProxy +* [Windows8] commandProxy has moved +* [Windows8] commandProxy has moved +* added Camera API for FirefoxOS +* Rename CHANGELOG.md -> RELEASENOTES.md +* [CB-4823](https://issues.apache.org/jira/browse/CB-4823) Fix XCode 5 camera plugin warnings +* Fix compiler warnings +* [CB-4765](https://issues.apache.org/jira/browse/CB-4765) Move ExifHelper.java into Camera Plugin +* [CB-4764](https://issues.apache.org/jira/browse/CB-4764) Remove reference to DirectoryManager from CameraLauncher +* [CB-4763](https://issues.apache.org/jira/browse/CB-4763) Use a copy of FileHelper.java within camera-plugin. +* [CB-4752](https://issues.apache.org/jira/browse/CB-4752) Incremented plugin version on dev branch. +* [CB-4633](https://issues.apache.org/jira/browse/CB-4633): We really should close cursors. It's just the right thing to do. +* No longer causes a stack trace, but it doesn't cause the error to be called. +* [CB-4889](https://issues.apache.org/jira/browse/CB-4889) renaming org.apache.cordova.core.camera to org.apache.cordova.camera + +### 0.2.1 (Sept 5, 2013) +* [CB-4656](https://issues.apache.org/jira/browse/CB-4656) Don't add line-breaks to base64-encoded images (Fixes type=DataURI) +* [CB-4432](https://issues.apache.org/jira/browse/CB-4432) copyright notice change diff --git a/plugins/cordova-plugin-camera/appium-tests/android/android.spec.js b/plugins/cordova-plugin-camera/appium-tests/android/android.spec.js new file mode 100644 index 0000000..69f7e35 --- /dev/null +++ b/plugins/cordova-plugin-camera/appium-tests/android/android.spec.js @@ -0,0 +1,672 @@ +/*jshint node: true, jasmine: true */ + +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ + +// these tests are meant to be executed by Cordova ParaMedic Appium runner +// you can find it here: https://github.com/apache/cordova-paramedic/ +// it is not necessary to do a full CI setup to run these tests +// Run: +// node cordova-paramedic/main.js --platform android --plugin cordova-plugin-camera --skipMainTests --target +// Please note only Android 5.1 and 4.4 are supported at this point. + +'use strict'; + +var wdHelper = global.WD_HELPER; +var screenshotHelper = global.SCREENSHOT_HELPER; +var wd = wdHelper.getWD(); +var cameraConstants = require('../../www/CameraConstants'); +var cameraHelper = require('../helpers/cameraHelper'); + +var MINUTE = 60 * 1000; +var BACK_BUTTON = 4; +var DEFAULT_SCREEN_WIDTH = 360; +var DEFAULT_SCREEN_HEIGHT = 567; +var DEFAULT_WEBVIEW_CONTEXT = 'WEBVIEW'; +var PROMISE_PREFIX = 'appium_camera_promise_'; +var CONTEXT_NATIVE_APP = 'NATIVE_APP'; + +describe('Camera tests Android.', function () { + var driver; + // the name of webview context, it will be changed to match needed context if there are named ones: + var webviewContext = DEFAULT_WEBVIEW_CONTEXT; + // this indicates that the device library has the test picture: + var isTestPictureSaved = false; + // we need to know the screen width and height to properly click on an image in the gallery: + var screenWidth = DEFAULT_SCREEN_WIDTH; + var screenHeight = DEFAULT_SCREEN_HEIGHT; + // promise count to use in promise ID + var promiseCount = 0; + // determine if Appium session is created successfully + var appiumSessionStarted = false; + // determine if camera is present on the device/emulator + var cameraAvailable = false; + // determine if emulator is within a range of acceptable resolutions able to run these tests + var isResolutionBad = true; + // a path to the image we add to the gallery before test run + var fillerImagePath; + + function getNextPromiseId() { + promiseCount += 1; + return getCurrentPromiseId(); + } + + function getCurrentPromiseId() { + return PROMISE_PREFIX + promiseCount; + } + + function gracefullyFail(error) { + fail(error); + return driver + .quit() + .then(function () { + return getDriver(); + }); + } + + // combinines specified options in all possible variations + // you can add more options to test more scenarios + function generateOptions() { + var sourceTypes = [ + cameraConstants.PictureSourceType.CAMERA, + cameraConstants.PictureSourceType.PHOTOLIBRARY + ]; + var destinationTypes = cameraConstants.DestinationType; + var encodingTypes = cameraConstants.EncodingType; + var allowEditOptions = [ true, false ]; + var correctOrientationOptions = [ true, false ]; + + return cameraHelper.generateSpecs(sourceTypes, destinationTypes, encodingTypes, allowEditOptions, correctOrientationOptions); + } + + // invokes Camera.getPicture() with the specified options + // and goes through all UI interactions unless 'skipUiInteractions' is true + function getPicture(options, skipUiInteractions) { + var promiseId = getNextPromiseId(); + if (!options) { + options = {}; + } + + return driver + .context(webviewContext) + .execute(cameraHelper.getPicture, [options, promiseId]) + .context(CONTEXT_NATIVE_APP) + .then(function () { + if (skipUiInteractions) { + return; + } + // selecting a picture from gallery + if (options.hasOwnProperty('sourceType') && + (options.sourceType === cameraConstants.PictureSourceType.PHOTOLIBRARY || + options.sourceType === cameraConstants.PictureSourceType.SAVEDPHOTOALBUM)) { + var tapTile = new wd.TouchAction(); + var swipeRight = new wd.TouchAction(); + tapTile + .tap({ + x: Math.round(screenWidth / 4), + y: Math.round(screenHeight / 4) + }); + swipeRight + .press({x: 10, y: Math.round(screenHeight / 4)}) + .wait(300) + .moveTo({x: Math.round(screenWidth - (screenWidth / 8)), y: 0}) + .wait(1500) + .release() + .wait(1000); + if (options.allowEdit) { + return driver + // always wait before performing touchAction + .sleep(7000) + .performTouchAction(tapTile); + } + return driver + .waitForElementByAndroidUIAutomator('new UiSelector().text("Gallery");', 20000) + .fail(function () { + // If the Gallery button is not present, swipe right to reveal the Gallery button! + return driver + .performTouchAction(swipeRight) + .waitForElementByAndroidUIAutomator('new UiSelector().text("Gallery");', 20000) + }) + .click() + // always wait before performing touchAction + .sleep(7000) + .performTouchAction(tapTile); + } + // taking a picture from camera + return driver + .waitForElementByAndroidUIAutomator('new UiSelector().resourceIdMatches(".*shutter.*")', MINUTE / 2) + .click() + .waitForElementByAndroidUIAutomator('new UiSelector().resourceIdMatches(".*done.*")', MINUTE / 2) + .click(); + }) + .then(function () { + if (skipUiInteractions) { + return; + } + if (options.allowEdit) { + return driver + .waitForElementByAndroidUIAutomator('new UiSelector().text("Save")', MINUTE) + .click(); + } + }) + .fail(function (failure) { + throw failure; + }); + } + + // checks if the picture was successfully taken + // if shouldLoad is falsy, ensures that the error callback was called + function checkPicture(shouldLoad, options) { + if (!options) { + options = {}; + } + return driver + .context(webviewContext) + .setAsyncScriptTimeout(MINUTE / 2) + .executeAsync(cameraHelper.checkPicture, [getCurrentPromiseId(), options]) + .then(function (result) { + if (shouldLoad) { + if (result !== 'OK') { + fail(result); + } + } else if (result.indexOf('ERROR') === -1) { + throw 'Unexpected success callback with result: ' + result; + } + }); + } + + // deletes the latest image from the gallery + function deleteImage() { + var holdTile = new wd.TouchAction(); + holdTile + .press({x: Math.round(screenWidth / 4), y: Math.round(screenHeight / 5)}) + .wait(1000) + .release(); + return driver + // always wait before performing touchAction + .sleep(7000) + .performTouchAction(holdTile) + .elementByAndroidUIAutomator('new UiSelector().text("Delete")') + .then(function (element) { + return element + .click() + .elementByAndroidUIAutomator('new UiSelector().text("OK")') + .click(); + }, function () { + // couldn't find Delete menu item. Possibly there is no image. + return driver; + }); + } + + function getDriver() { + driver = wdHelper.getDriver('Android'); + return driver.getWebviewContext() + .then(function(context) { + webviewContext = context; + return driver.context(webviewContext); + }) + .waitForDeviceReady() + .injectLibraries() + .then(function () { + var options = { + quality: 50, + allowEdit: false, + sourceType: cameraConstants.PictureSourceType.SAVEDPHOTOALBUM, + saveToPhotoAlbum: false, + targetWidth: 210, + targetHeight: 210 + }; + return driver + .then(function () { return getPicture(options, true); }) + .context(CONTEXT_NATIVE_APP) + // case insensitive select, will be handy with Android 7 support + .elementByXPath('//android.widget.Button[translate(@text, "alow", "ALOW")="ALLOW"]') + .click() + .fail(function noAlert() { }) + .deviceKeyEvent(BACK_BUTTON) + .sleep(2000) + .elementById('action_bar_title') + .then(function () { + // success means we're still in native app + return driver + .deviceKeyEvent(BACK_BUTTON); + }, function () { + // error means we're already in webview + return driver; + }); + }) + .then(function () { + // doing it inside a function because otherwise + // it would not hook up to the webviewContext var change + // in the first methods of this chain + return driver.context(webviewContext); + }) + .deleteFillerImage(fillerImagePath) + .then(function () { + fillerImagePath = null; + }) + .addFillerImage() + .then(function (result) { + if (result && result.indexOf('ERROR:') === 0) { + throw new Error(result); + } else { + fillerImagePath = result; + } + }); + } + + function recreateSession() { + return driver + .quit() + .finally(function () { + return getDriver(); + }); + } + + function tryRunSpec(spec) { + return driver + .then(spec) + .fail(function () { + return recreateSession() + .then(spec) + .fail(function() { + return recreateSession() + .then(spec); + }); + }) + .fail(gracefullyFail); + } + + // produces a generic spec function which + // takes a picture with specified options + // and then verifies it + function generateSpec(options) { + return function () { + return driver + .then(function () { + return getPicture(options); + }) + .then(function () { + return checkPicture(true, options); + }); + }; + } + + function checkSession(done, skipResolutionCheck) { + if (!appiumSessionStarted) { + fail('Failed to start a session ' + (lastFailureReason ? lastFailureReason : '')); + done(); + } + if (!skipResolutionCheck && isResolutionBad) { + fail('The resolution of this target device is not within the appropriate range of width: blah-blah and height: bleh-bleh. The target\'s current resolution is: ' + isResolutionBad); + } + } + + function checkCamera(pending) { + if (!cameraAvailable) { + pending('This test requires a functioning camera on the Android device/emulator, and this test suite\'s functional camera test failed on your target environment.'); + } + } + + afterAll(function (done) { + checkSession(done); + driver + .quit() + .done(done); + }, MINUTE); + + it('camera.ui.util configuring driver and starting a session', function (done) { + getDriver() + .then(function () { + appiumSessionStarted = true; + }, fail) + .done(done); + }, 10 * MINUTE); + + it('camera.ui.util determine screen dimensions', function (done) { + checkSession(done, /*skipResolutionCheck?*/ true); // skip the resolution check here since we are about to find out in this spec! + driver + .context(CONTEXT_NATIVE_APP) + .getWindowSize() + .then(function (size) { + screenWidth = Number(size.width); + screenHeight = Number(size.height); + isResolutionBad = false; + /* + TODO: what are acceptable resolution values? + need to check what the emulators used in CI return. + and also what local device definitions work and dont + */ + }) + .done(done); + }, MINUTE); + + it('camera.ui.util determine camera availability', function (done) { + checkSession(done); + var opts = { + sourceType: cameraConstants.PictureSourceType.CAMERA, + saveToPhotoAlbum: false + }; + + return driver + .then(function () { + return getPicture(opts); + }) + .then(function () { + cameraAvailable = true; + }, function () { + return recreateSession(); + }) + .done(done); + }, 5 * MINUTE); + + describe('Specs.', function () { + // getPicture() with saveToPhotoLibrary = true + it('camera.ui.spec.1 Saving a picture to the photo library', function (done) { + checkSession(done); + checkCamera(pending); + var spec = generateSpec({ + quality: 50, + allowEdit: false, + sourceType: cameraConstants.PictureSourceType.CAMERA, + saveToPhotoAlbum: true + }); + + tryRunSpec(spec) + .then(function () { + isTestPictureSaved = true; + }) + .done(done); + }, 10 * MINUTE); + + // getPicture() with mediaType: VIDEO, sourceType: PHOTOLIBRARY + it('camera.ui.spec.2 Selecting only videos', function (done) { + checkSession(done); + var spec = function () { + var options = { sourceType: cameraConstants.PictureSourceType.PHOTOLIBRARY, + mediaType: cameraConstants.MediaType.VIDEO }; + return driver + .then(function () { + return getPicture(options, true); + }) + .context(CONTEXT_NATIVE_APP) + .then(function () { + // try to find "Gallery" menu item + // if there's none, the gallery should be already opened + return driver + .waitForElementByAndroidUIAutomator('new UiSelector().text("Gallery")', 20000) + .then(function (element) { + return element.click(); + }, function () { + return driver; + }); + }) + .then(function () { + // if the gallery is opened on the videos page, + // there should be a "Choose video" caption + return driver + .elementByAndroidUIAutomator('new UiSelector().text("Choose video")') + .fail(function () { + throw 'Couldn\'t find a "Choose video" element.'; + }); + }) + .deviceKeyEvent(BACK_BUTTON) + .elementByAndroidUIAutomator('new UiSelector().text("Gallery")') + .deviceKeyEvent(BACK_BUTTON) + .finally(function () { + return driver + .elementById('action_bar_title') + .then(function () { + // success means we're still in native app + return driver + .deviceKeyEvent(BACK_BUTTON) + // give native app some time to close + .sleep(2000) + // try again! because every ~30th build + // on Sauce Labs this backbutton doesn't work + .elementById('action_bar_title') + .then(function () { + // success means we're still in native app + return driver + .deviceKeyEvent(BACK_BUTTON); + }, function () { + // error means we're already in webview + return driver; + }); + }, function () { + // error means we're already in webview + return driver; + }); + }); + }; + tryRunSpec(spec).done(done); + }, 10 * MINUTE); + + // getPicture(), then dismiss + // wait for the error callback to be called + it('camera.ui.spec.3 Dismissing the camera', function (done) { + checkSession(done); + checkCamera(pending); + var spec = function () { + var options = { + quality: 50, + allowEdit: true, + sourceType: cameraConstants.PictureSourceType.CAMERA, + destinationType: cameraConstants.DestinationType.FILE_URI + }; + return driver + .then(function () { + return getPicture(options, true); + }) + .context(CONTEXT_NATIVE_APP) + .waitForElementByAndroidUIAutomator('new UiSelector().resourceIdMatches(".*cancel.*")', MINUTE / 2) + .click() + .then(function () { + return checkPicture(false); + }); + }; + + tryRunSpec(spec).done(done); + }, 10 * MINUTE); + + // getPicture(), then take picture but dismiss the edit + // wait for the error callback to be called + it('camera.ui.spec.4 Dismissing the edit', function (done) { + checkSession(done); + checkCamera(pending); + var spec = function () { + var options = { + quality: 50, + allowEdit: true, + sourceType: cameraConstants.PictureSourceType.CAMERA, + destinationType: cameraConstants.DestinationType.FILE_URI + }; + return driver + .then(function () { + return getPicture(options, true); + }) + .waitForElementByAndroidUIAutomator('new UiSelector().resourceIdMatches(".*shutter.*")', MINUTE / 2) + .click() + .waitForElementByAndroidUIAutomator('new UiSelector().resourceIdMatches(".*done.*")', MINUTE / 2) + .click() + .waitForElementByAndroidUIAutomator('new UiSelector().resourceIdMatches(".*discard.*")', MINUTE / 2) + .click() + .then(function () { + return checkPicture(false); + }); + }; + + tryRunSpec(spec).done(done); + }, 10 * MINUTE); + + it('camera.ui.spec.5 Verifying target image size, sourceType=CAMERA', function (done) { + checkSession(done); + checkCamera(pending); + var spec = generateSpec({ + quality: 50, + allowEdit: false, + sourceType: cameraConstants.PictureSourceType.CAMERA, + saveToPhotoAlbum: false, + targetWidth: 210, + targetHeight: 210 + }); + + tryRunSpec(spec).done(done); + }, 10 * MINUTE); + + it('camera.ui.spec.6 Verifying target image size, sourceType=PHOTOLIBRARY', function (done) { + checkSession(done); + var spec = generateSpec({ + quality: 50, + allowEdit: false, + sourceType: cameraConstants.PictureSourceType.PHOTOLIBRARY, + saveToPhotoAlbum: false, + targetWidth: 210, + targetHeight: 210 + }); + + tryRunSpec(spec).done(done); + }, 10 * MINUTE); + + it('camera.ui.spec.7 Verifying target image size, sourceType=CAMERA, DestinationType=NATIVE_URI', function (done) { + checkSession(done); + checkCamera(pending); + var spec = generateSpec({ + quality: 50, + allowEdit: false, + sourceType: cameraConstants.PictureSourceType.CAMERA, + destinationType: cameraConstants.DestinationType.NATIVE_URI, + saveToPhotoAlbum: false, + targetWidth: 210, + targetHeight: 210 + }); + + tryRunSpec(spec).done(done); + }, 10 * MINUTE); + + it('camera.ui.spec.8 Verifying target image size, sourceType=PHOTOLIBRARY, DestinationType=NATIVE_URI', function (done) { + checkSession(done); + var spec = generateSpec({ + quality: 50, + allowEdit: false, + sourceType: cameraConstants.PictureSourceType.PHOTOLIBRARY, + destinationType: cameraConstants.DestinationType.NATIVE_URI, + saveToPhotoAlbum: false, + targetWidth: 210, + targetHeight: 210 + }); + + tryRunSpec(spec).done(done); + }, 10 * MINUTE); + + it('camera.ui.spec.9 Verifying target image size, sourceType=CAMERA, DestinationType=NATIVE_URI, quality=100', function (done) { + checkSession(done); + checkCamera(pending); + var spec = generateSpec({ + quality: 100, + allowEdit: true, + sourceType: cameraConstants.PictureSourceType.CAMERA, + destinationType: cameraConstants.DestinationType.NATIVE_URI, + saveToPhotoAlbum: false, + targetWidth: 305, + targetHeight: 305 + }); + + tryRunSpec(spec).done(done); + }, 10 * MINUTE); + + it('camera.ui.spec.10 Verifying target image size, sourceType=PHOTOLIBRARY, DestinationType=NATIVE_URI, quality=100', function (done) { + checkSession(done); + var spec = generateSpec({ + quality: 100, + allowEdit: true, + sourceType: cameraConstants.PictureSourceType.PHOTOLIBRARY, + destinationType: cameraConstants.DestinationType.NATIVE_URI, + saveToPhotoAlbum: false, + targetWidth: 305, + targetHeight: 305 + }); + + tryRunSpec(spec).done(done); + }, 10 * MINUTE); + + // combine various options for getPicture() + generateOptions().forEach(function (spec) { + it('camera.ui.spec.11.' + spec.id + ' Combining options. ' + spec.description, function (done) { + checkSession(done); + if (spec.options.sourceType == cameraConstants.PictureSourceType.CAMERA) { + checkCamera(pending); + } + var s = generateSpec(spec.options); + tryRunSpec(s).done(done); + }, 10 * MINUTE); + }); + + it('camera.ui.util Delete filler picture from device library', function (done) { + driver + .context(webviewContext) + .deleteFillerImage(fillerImagePath) + .done(done); + }, MINUTE); + + it('camera.ui.util Delete taken picture from device library', function (done) { + checkSession(done); + if (!isTestPictureSaved) { + // couldn't save test picture earlier, so nothing to delete here + done(); + return; + } + // delete exactly one latest picture + // this should be the picture we've taken in the first spec + driver + .context(CONTEXT_NATIVE_APP) + .deviceKeyEvent(BACK_BUTTON) + .sleep(1000) + .deviceKeyEvent(BACK_BUTTON) + .sleep(1000) + .deviceKeyEvent(BACK_BUTTON) + .elementById('Apps') + .click() + .then(function () { + return driver + .elementByXPath('//android.widget.Button[@text="OK"]') + .click() + .fail(function () { + // no cling is all right + // it is not a brand new emulator, then + }); + }) + .elementByAndroidUIAutomator('new UiSelector().text("Gallery")') + .click() + .elementByAndroidUIAutomator('new UiSelector().textContains("Pictures")') + .click() + .then(deleteImage) + .deviceKeyEvent(BACK_BUTTON) + .sleep(1000) + .deviceKeyEvent(BACK_BUTTON) + .sleep(1000) + .deviceKeyEvent(BACK_BUTTON) + .fail(fail) + .finally(done); + }, 3 * MINUTE); + }); + +}); diff --git a/plugins/cordova-plugin-camera/appium-tests/helpers/cameraHelper.js b/plugins/cordova-plugin-camera/appium-tests/helpers/cameraHelper.js new file mode 100644 index 0000000..caf0f9e --- /dev/null +++ b/plugins/cordova-plugin-camera/appium-tests/helpers/cameraHelper.js @@ -0,0 +1,308 @@ +/*jshint node: true */ +/* global Q, resolveLocalFileSystemURL, Camera, cordova */ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ + +'use strict'; + +var cameraConstants = require('../../www/CameraConstants'); + +function findKeyByValue(set, value) { + for (var k in set) { + if (set.hasOwnProperty(k)) { + if (set[k] == value) { + return k; + } + } + } + return undefined; +} + +function getDescription(spec) { + var desc = ''; + + desc += 'sourceType: ' + findKeyByValue(cameraConstants.PictureSourceType, spec.options.sourceType); + desc += ', destinationType: ' + findKeyByValue(cameraConstants.DestinationType, spec.options.destinationType); + desc += ', encodingType: ' + findKeyByValue(cameraConstants.EncodingType, spec.options.encodingType); + desc += ', allowEdit: ' + spec.options.allowEdit.toString(); + desc += ', correctOrientation: ' + spec.options.correctOrientation.toString(); + + return desc; +} + +module.exports.generateSpecs = function (sourceTypes, destinationTypes, encodingTypes, allowEditOptions, correctOrientationOptions) { + var destinationType, + sourceType, + encodingType, + allowEdit, + correctOrientation, + specs = [], + id = 1; + for (destinationType in destinationTypes) { + if (destinationTypes.hasOwnProperty(destinationType)) { + for (sourceType in sourceTypes) { + if (sourceTypes.hasOwnProperty(sourceType)) { + for (encodingType in encodingTypes) { + if (encodingTypes.hasOwnProperty(encodingType)) { + for (allowEdit in allowEditOptions) { + if (allowEditOptions.hasOwnProperty(allowEdit)) { + for (correctOrientation in correctOrientationOptions) { + // if taking picture from photolibrary, don't vary 'correctOrientation' option + if ((sourceTypes[sourceType] === cameraConstants.PictureSourceType.PHOTOLIBRARY || + sourceTypes[sourceType] === cameraConstants.PictureSourceType.SAVEDPHOTOALBUM) && + correctOrientation === true) { continue; } + var spec = { + 'id': id++, + 'options': { + 'destinationType': destinationTypes[destinationType], + 'sourceType': sourceTypes[sourceType], + 'encodingType': encodingTypes[encodingType], + 'allowEdit': allowEditOptions[allowEdit], + 'saveToPhotoAlbum': false, + 'correctOrientation': correctOrientationOptions[correctOrientation] + } + }; + spec.description = getDescription(spec); + specs.push(spec); + } + } + } + } + } + } + } + } + } + return specs; +}; + +// calls getPicture() and saves the result in promise +// note that this function is executed in the context of tested app +// and not in the context of tests +module.exports.getPicture = function (opts, pid) { + if (navigator._appiumPromises[pid - 1]) { + navigator._appiumPromises[pid - 1] = null; + } + navigator._appiumPromises[pid] = Q.defer(); + navigator.camera.getPicture(function (result) { + navigator._appiumPromises[pid].resolve(result); + }, function (err) { + navigator._appiumPromises[pid].reject(err); + }, opts); +}; + +// verifies taken picture when the promise is resolved, +// calls a callback with 'OK' if everything is good, +// calls a callback with 'ERROR: ' if something is wrong +// note that this function is executed in the context of tested app +// and not in the context of tests +module.exports.checkPicture = function (pid, options, cb) { + var isIos = cordova.platformId === "ios"; + var isAndroid = cordova.platformId === "android"; + // skip image type check if it's unmodified on Android: + // https://github.com/apache/cordova-plugin-camera/#android-quirks-1 + var skipFileTypeCheckAndroid = isAndroid && options.quality === 100 && + !options.targetWidth && !options.targetHeight && + !options.correctOrientation; + + // Skip image type check if destination is NATIVE_URI and source - device's photoalbum + // https://github.com/apache/cordova-plugin-camera/#ios-quirks-1 + var skipFileTypeCheckiOS = isIos && options.destinationType === Camera.DestinationType.NATIVE_URI && + (options.sourceType === Camera.PictureSourceType.PHOTOLIBRARY || + options.sourceType === Camera.PictureSourceType.SAVEDPHOTOALBUM); + + var skipFileTypeCheck = skipFileTypeCheckAndroid || skipFileTypeCheckiOS; + + var desiredType = 'JPEG'; + var mimeType = 'image/jpeg'; + if (options.encodingType === Camera.EncodingType.PNG) { + desiredType = 'PNG'; + mimeType = 'image/png'; + } + + function errorCallback(msg) { + if (msg.hasOwnProperty('message')) { + msg = msg.message; + } + cb('ERROR: ' + msg); + } + + // verifies the image we get from plugin + function verifyResult(result) { + if (result.length === 0) { + errorCallback('The result is empty.'); + return; + } else if (isIos && options.destinationType === Camera.DestinationType.NATIVE_URI && result.indexOf('assets-library:') !== 0) { + errorCallback('Expected "' + result.substring(0, 150) + '"to start with "assets-library:"'); + return; + } else if (isIos && options.destinationType === Camera.DestinationType.FILE_URI && result.indexOf('file:') !== 0) { + errorCallback('Expected "' + result.substring(0, 150) + '"to start with "file:"'); + return; + } + + try { + window.atob(result); + // if we got here it is a base64 string (DATA_URL) + result = "data:" + mimeType + ";base64," + result; + } catch (e) { + // not DATA_URL + if (options.destinationType === Camera.DestinationType.DATA_URL) { + errorCallback('Expected ' + result.substring(0, 150) + 'not to be DATA_URL'); + return; + } + } + + try { + if (result.indexOf('file:') === 0 || + result.indexOf('content:') === 0 || + result.indexOf('assets-library:') === 0) { + + if (!window.resolveLocalFileSystemURL) { + errorCallback('Cannot read file. Please install cordova-plugin-file to fix this.'); + return; + } + resolveLocalFileSystemURL(result, function (entry) { + if (skipFileTypeCheck) { + displayFile(entry); + } else { + verifyFile(entry); + } + }, function (err) { + errorCallback(err); + }); + } else { + displayImage(result); + } + } catch (e) { + errorCallback(e); + } + } + + // verifies that the file type matches the requested type + function verifyFile(entry) { + try { + var reader = new FileReader(); + reader.onloadend = function(e) { + var arr = (new Uint8Array(e.target.result)).subarray(0, 4); + var header = ''; + for(var i = 0; i < arr.length; i++) { + header += arr[i].toString(16); + } + var actualType = 'unknown'; + + switch (header) { + case "89504e47": + actualType = 'PNG'; + break; + case 'ffd8ffe0': + case 'ffd8ffe1': + case 'ffd8ffe2': + actualType = 'JPEG'; + break; + } + + if (actualType === desiredType) { + displayFile(entry); + } else { + errorCallback('File type mismatch. Expected ' + desiredType + ', got ' + actualType); + } + }; + reader.onerror = function (e) { + errorCallback(e); + }; + entry.file(function (file) { + reader.readAsArrayBuffer(file); + }, function (e) { + errorCallback(e); + }); + } catch (e) { + errorCallback(e); + } + } + + // reads the file, then displays the image + function displayFile(entry) { + function onFileReceived(file) { + var reader = new FileReader(); + reader.onerror = function (e) { + errorCallback(e); + }; + reader.onloadend = function (evt) { + displayImage(evt.target.result); + }; + reader.readAsDataURL(file); + } + + entry.file(onFileReceived, function (e) { + errorCallback(e); + }); + } + + function displayImage(image) { + try { + var imgEl = document.getElementById('camera_test_image'); + if (!imgEl) { + imgEl = document.createElement('img'); + imgEl.id = 'camera_test_image'; + document.body.appendChild(imgEl); + } + var timedOut = false; + var loadTimeout = setTimeout(function () { + timedOut = true; + imgEl.src = ''; + errorCallback('The image did not load: ' + image.substring(0, 150)); + }, 10000); + var done = function (status) { + if (!timedOut) { + clearTimeout(loadTimeout); + imgEl.src = ''; + cb(status); + } + }; + imgEl.onload = function () { + try { + // aspect ratio is preserved so only one dimension should match + if ((typeof options.targetWidth === 'number' && imgEl.naturalWidth !== options.targetWidth) && + (typeof options.targetHeight === 'number' && imgEl.naturalHeight !== options.targetHeight)) + { + done('ERROR: Wrong image size: ' + imgEl.naturalWidth + 'x' + imgEl.naturalHeight + + '. Requested size: ' + options.targetWidth + 'x' + options.targetHeight); + } else { + done('OK'); + } + } catch (e) { + errorCallback(e); + } + }; + imgEl.src = image; + } catch (e) { + errorCallback(e); + } + } + + navigator._appiumPromises[pid].promise + .then(function (result) { + verifyResult(result); + }) + .fail(function (e) { + errorCallback(e); + }); +}; diff --git a/plugins/cordova-plugin-camera/appium-tests/ios/ios.spec.js b/plugins/cordova-plugin-camera/appium-tests/ios/ios.spec.js new file mode 100644 index 0000000..bf3b33e --- /dev/null +++ b/plugins/cordova-plugin-camera/appium-tests/ios/ios.spec.js @@ -0,0 +1,489 @@ +/*jshint node: true, jasmine: true */ + +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ + +// these tests are meant to be executed by Cordova Paramedic test runner +// you can find it here: https://github.com/apache/cordova-paramedic/ +// it is not necessary to do a full CI setup to run these tests +// just run "node cordova-paramedic/main.js --platform ios --plugin cordova-plugin-camera" + +'use strict'; + +var wdHelper = global.WD_HELPER; +var screenshotHelper = global.SCREENSHOT_HELPER; +var isDevice = global.DEVICE; +var cameraConstants = require('../../www/CameraConstants'); +var cameraHelper = require('../helpers/cameraHelper'); + +var MINUTE = 60 * 1000; +var DEFAULT_WEBVIEW_CONTEXT = 'WEBVIEW_1'; +var PROMISE_PREFIX = 'appium_camera_promise_'; +var CONTEXT_NATIVE_APP = 'NATIVE_APP'; + +describe('Camera tests iOS.', function () { + var driver; + var webviewContext = DEFAULT_WEBVIEW_CONTEXT; + // promise count to use in promise ID + var promiseCount = 0; + // going to set this to false if session is created successfully + var failedToStart = true; + // points out which UI automation to use + var isXCUI = false; + // spec counter to restart the session + var specsRun = 0; + + function getNextPromiseId() { + promiseCount += 1; + return getCurrentPromiseId(); + } + + function getCurrentPromiseId() { + return PROMISE_PREFIX + promiseCount; + } + + function gracefullyFail(error) { + fail(error); + return driver + .quit() + .then(function () { + return getDriver(); + }); + } + + // generates test specs by combining all the specified options + // you can add more options to test more scenarios + function generateOptions() { + var sourceTypes = cameraConstants.PictureSourceType; + var destinationTypes = cameraConstants.DestinationType; + var encodingTypes = cameraConstants.EncodingType; + var allowEditOptions = [ true, false ]; + var correctOrientationOptions = [ true, false ]; + + return cameraHelper.generateSpecs(sourceTypes, destinationTypes, encodingTypes, allowEditOptions, correctOrientationOptions); + } + + function usePicture() { + return driver + .elementByXPath('//*[@label="Use"]') + .click() + .fail(function () { + if (isXCUI) { + return driver + .waitForElementByAccessibilityId('Choose', MINUTE / 3) + .click(); + } + // For some reason "Choose" element is not clickable by standard Appium methods on iOS <= 9 + return wdHelper.tapElementByXPath('//UIAButton[@label="Choose"]', driver); + }); + } + + function clickPhoto() { + if (isXCUI) { + // iOS >=10 + return driver + .context(CONTEXT_NATIVE_APP) + .elementsByXPath('//XCUIElementTypeCell') + .then(function(photos) { + if (photos.length == 0) { + return driver + .sleep(0) // driver.source is not a function o.O + .source() + .then(function (src) { + console.log(src); + gracefullyFail('Couldn\'t find an image to click'); + }); + } + // intentionally clicking the second photo here + // the first one is not clickable for some reason + return photos[1].click(); + }); + } + // iOS <10 + return driver + .elementByXPath('//UIACollectionCell') + .click(); + } + + function getPicture(options, cancelCamera, skipUiInteractions) { + var promiseId = getNextPromiseId(); + if (!options) { + options = {}; + } + + return driver + .context(webviewContext) + .execute(cameraHelper.getPicture, [options, promiseId]) + .context(CONTEXT_NATIVE_APP) + .then(function () { + if (skipUiInteractions) { + return; + } + if (options.hasOwnProperty('sourceType') && options.sourceType === cameraConstants.PictureSourceType.PHOTOLIBRARY) { + return driver + .waitForElementByAccessibilityId('Camera Roll', MINUTE / 2) + .click() + .then(function () { + return clickPhoto(); + }) + .then(function () { + if (!options.allowEdit) { + return driver; + } + return usePicture(); + }); + } + if (options.hasOwnProperty('sourceType') && options.sourceType === cameraConstants.PictureSourceType.SAVEDPHOTOALBUM) { + return clickPhoto() + .then(function () { + if (!options.allowEdit) { + return driver; + } + return usePicture(); + }); + } + if (cancelCamera) { + return driver + .waitForElementByAccessibilityId('Cancel', MINUTE / 2) + .click(); + } + return driver + .waitForElementByAccessibilityId('Take Picture', MINUTE / 2) + .click() + .waitForElementByAccessibilityId('Use Photo', MINUTE / 2) + .click(); + }) + .fail(fail); + } + + // checks if the picture was successfully taken + // if shouldLoad is falsy, ensures that the error callback was called + function checkPicture(shouldLoad, options) { + if (!options) { + options = {}; + } + return driver + .context(webviewContext) + .setAsyncScriptTimeout(MINUTE / 2) + .executeAsync(cameraHelper.checkPicture, [getCurrentPromiseId(), options]) + .then(function (result) { + if (shouldLoad) { + if (result !== 'OK') { + fail(result); + } + } else if (result.indexOf('ERROR') === -1) { + throw 'Unexpected success callback with result: ' + result; + } + }); + } + + // takes a picture with the specified options + // and then verifies it + function runSpec(options, done, pending) { + if (options.sourceType === cameraConstants.PictureSourceType.CAMERA && !isDevice) { + pending('Camera is not available on iOS simulator'); + } + checkSession(done); + specsRun += 1; + return driver + .then(function () { + return getPicture(options); + }) + .then(function () { + return checkPicture(true, options); + }) + .fail(gracefullyFail); + } + + function getDriver() { + failedToStart = true; + driver = wdHelper.getDriver('iOS'); + return wdHelper.getWebviewContext(driver) + .then(function(context) { + webviewContext = context; + return driver.context(webviewContext); + }) + .then(function () { + return wdHelper.waitForDeviceReady(driver); + }) + .then(function () { + return wdHelper.injectLibraries(driver); + }) + .sessionCapabilities() + .then(function (caps) { + var platformVersion = parseFloat(caps.platformVersion); + isXCUI = platformVersion >= 10.0; + }) + .then(function () { + var options = { + quality: 50, + allowEdit: false, + sourceType: cameraConstants.PictureSourceType.SAVEDPHOTOALBUM, + saveToPhotoAlbum: false, + targetWidth: 210, + targetHeight: 210 + }; + return driver + .then(function () { return getPicture(options, false, true); }) + .context(CONTEXT_NATIVE_APP) + .acceptAlert() + .then(function alertDismissed() { + // TODO: once we move to only XCUITest-based (which is force on you in either iOS 10+ or Xcode 8+) + // UI tests, we will have to: + // a) remove use of autoAcceptAlerts appium capability since it no longer functions in XCUITest + // b) can remove this entire then() clause, as we do not need to explicitly handle the acceptAlert + // failure callback, since we will be guaranteed to hit the permission dialog on startup. + }, function noAlert() { + // in case the contacts permission alert never showed up: no problem, don't freak out. + // This can happen if: + // a) The application-under-test already had photos permissions granted to it + // b) Appium's autoAcceptAlerts capability is provided (and functioning) + }) + .elementByAccessibilityId('Cancel', 10000) + .click(); + }) + .then(function () { + failedToStart = false; + }); + } + + function checkSession(done) { + if (failedToStart) { + fail('Failed to start a session'); + done(); + } + } + + it('camera.ui.util configure driver and start a session', function (done) { + getDriver() + .fail(fail) + .done(done); + }, 15 * MINUTE); + + describe('Specs.', function () { + afterEach(function (done) { + if (specsRun >= 15) { + specsRun = 0; + // we need to restart the session regularly because for some reason + // when running against iOS 10 simulator on SauceLabs, + // Appium cannot handle more than ~20 specs at one session + // the error would be as follows: + // "Could not proxy command to remote server. Original error: Error: connect ECONNREFUSED 127.0.0.1:8100" + checkSession(done); + return driver + .quit() + .then(function () { + return getDriver(); + }) + .done(done); + } else { + done(); + } + }, 15 * MINUTE); + + // getPicture() with mediaType: VIDEO, sourceType: PHOTOLIBRARY + it('camera.ui.spec.1 Selecting only videos', function (done) { + checkSession(done); + specsRun += 1; + var options = { sourceType: cameraConstants.PictureSourceType.PHOTOLIBRARY, + mediaType: cameraConstants.MediaType.VIDEO }; + driver + // skip ui unteractions + .then(function () { return getPicture(options, false, true); }) + .waitForElementByXPath('//*[contains(@label,"Videos")]', MINUTE / 2) + .elementByAccessibilityId('Cancel') + .click() + .fail(gracefullyFail) + .done(done); + }, 7 * MINUTE); + + // getPicture(), then dismiss + // wait for the error callback to be called + it('camera.ui.spec.2 Dismissing the camera', function (done) { + checkSession(done); + if (!isDevice) { + pending('Camera is not available on iOS simulator'); + } + specsRun += 1; + var options = { sourceType: cameraConstants.PictureSourceType.CAMERA, + saveToPhotoAlbum: false }; + driver + .then(function () { + return getPicture(options, true); + }) + .then(function () { + return checkPicture(false); + }) + .fail(gracefullyFail) + .done(done); + }, 7 * MINUTE); + + it('camera.ui.spec.3 Verifying target image size, sourceType=CAMERA', function (done) { + var options = { + quality: 50, + allowEdit: false, + sourceType: cameraConstants.PictureSourceType.CAMERA, + saveToPhotoAlbum: false, + targetWidth: 210, + targetHeight: 210 + }; + + runSpec(options, done, pending).done(done); + }, 7 * MINUTE); + + it('camera.ui.spec.4 Verifying target image size, sourceType=SAVEDPHOTOALBUM', function (done) { + var options = { + quality: 50, + allowEdit: false, + sourceType: cameraConstants.PictureSourceType.SAVEDPHOTOALBUM, + saveToPhotoAlbum: false, + targetWidth: 210, + targetHeight: 210 + }; + + runSpec(options, done, pending).done(done); + }, 7 * MINUTE); + + it('camera.ui.spec.5 Verifying target image size, sourceType=PHOTOLIBRARY', function (done) { + var options = { + quality: 50, + allowEdit: false, + sourceType: cameraConstants.PictureSourceType.PHOTOLIBRARY, + saveToPhotoAlbum: false, + targetWidth: 210, + targetHeight: 210 + }; + + runSpec(options, done, pending).done(done); + }, 7 * MINUTE); + + it('camera.ui.spec.6 Verifying target image size, sourceType=CAMERA, destinationType=FILE_URL', function (done) { + // remove this line if you don't mind the tests leaving a photo saved on device + pending('Cannot prevent iOS from saving the picture to photo library'); + + var options = { + quality: 50, + allowEdit: false, + sourceType: cameraConstants.PictureSourceType.CAMERA, + destinationType: cameraConstants.DestinationType.FILE_URL, + saveToPhotoAlbum: false, + targetWidth: 210, + targetHeight: 210 + }; + + runSpec(options, done, pending).done(done); + }, 7 * MINUTE); + + it('camera.ui.spec.7 Verifying target image size, sourceType=SAVEDPHOTOALBUM, destinationType=FILE_URL', function (done) { + var options = { + quality: 50, + allowEdit: false, + sourceType: cameraConstants.PictureSourceType.SAVEDPHOTOALBUM, + destinationType: cameraConstants.DestinationType.FILE_URL, + saveToPhotoAlbum: false, + targetWidth: 210, + targetHeight: 210 + }; + + runSpec(options, done, pending).done(done); + }, 7 * MINUTE); + + it('camera.ui.spec.8 Verifying target image size, sourceType=PHOTOLIBRARY, destinationType=FILE_URL', function (done) { + var options = { + quality: 50, + allowEdit: false, + sourceType: cameraConstants.PictureSourceType.PHOTOLIBRARY, + destinationType: cameraConstants.DestinationType.FILE_URL, + saveToPhotoAlbum: false, + targetWidth: 210, + targetHeight: 210 + }; + + runSpec(options, done, pending).done(done); + }, 7 * MINUTE); + + it('camera.ui.spec.9 Verifying target image size, sourceType=CAMERA, destinationType=FILE_URL, quality=100', function (done) { + // remove this line if you don't mind the tests leaving a photo saved on device + pending('Cannot prevent iOS from saving the picture to photo library'); + + var options = { + quality: 100, + allowEdit: false, + sourceType: cameraConstants.PictureSourceType.CAMERA, + destinationType: cameraConstants.DestinationType.FILE_URL, + saveToPhotoAlbum: false, + targetWidth: 305, + targetHeight: 305 + }; + runSpec(options, done, pending).done(done); + }, 7 * MINUTE); + + it('camera.ui.spec.10 Verifying target image size, sourceType=SAVEDPHOTOALBUM, destinationType=FILE_URL, quality=100', function (done) { + var options = { + quality: 100, + allowEdit: false, + sourceType: cameraConstants.PictureSourceType.SAVEDPHOTOALBUM, + destinationType: cameraConstants.DestinationType.FILE_URL, + saveToPhotoAlbum: false, + targetWidth: 305, + targetHeight: 305 + }; + + runSpec(options, done, pending).done(done); + }, 7 * MINUTE); + + it('camera.ui.spec.11 Verifying target image size, sourceType=PHOTOLIBRARY, destinationType=FILE_URL, quality=100', function (done) { + var options = { + quality: 100, + allowEdit: false, + sourceType: cameraConstants.PictureSourceType.PHOTOLIBRARY, + destinationType: cameraConstants.DestinationType.FILE_URL, + saveToPhotoAlbum: false, + targetWidth: 305, + targetHeight: 305 + }; + + runSpec(options, done, pending).done(done); + }, 7 * MINUTE); + + // combine various options for getPicture() + generateOptions().forEach(function (spec) { + it('camera.ui.spec.12.' + spec.id + ' Combining options. ' + spec.description, function (done) { + // remove this check if you don't mind the tests leaving a photo saved on device + if (spec.options.sourceType === cameraConstants.PictureSourceType.CAMERA && + spec.options.destinationType === cameraConstants.DestinationType.NATIVE_URI) { + pending('Skipping: cannot prevent iOS from saving the picture to photo library and cannot delete it. ' + + 'For more info, see iOS quirks here: https://github.com/apache/cordova-plugin-camera#ios-quirks-1'); + } + + runSpec(spec.options, done, pending).done(done); + }, 7 * MINUTE); + }); + + }); + + it('camera.ui.util Destroy the session', function (done) { + checkSession(done); + driver + .quit() + .done(done); + }, 5 * MINUTE); +}); diff --git a/plugins/cordova-plugin-camera/doc/de/README.md b/plugins/cordova-plugin-camera/doc/de/README.md new file mode 100644 index 0000000..97e6526 --- /dev/null +++ b/plugins/cordova-plugin-camera/doc/de/README.md @@ -0,0 +1,421 @@ + + +# cordova-plugin-camera + +[![Build Status](https://travis-ci.org/apache/cordova-plugin-camera.svg)](https://travis-ci.org/apache/cordova-plugin-camera) + +Dieses Plugin definiert eine globale `navigator.camera`-Objekt, das eine API für Aufnahmen und für die Auswahl der Bilder aus dem System-Image-Library bietet. + +Obwohl das Objekt mit der globalen Gültigkeitsbereich `navigator` verbunden ist, steht es nicht bis nach dem `Deviceready`-Ereignis. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(navigator.camera); + } + + +## Installation + + cordova plugin add cordova-plugin-camera + + +## API + + * Kamera + * navigator.camera.getPicture(success, fail, options) + * CameraOptions + * CameraPopoverHandle + * CameraPopoverOptions + * navigator.camera.cleanup + +## navigator.camera.getPicture + +Nimmt ein Foto mit der Kamera, oder ein Foto aus dem Gerät Bildergalerie abgerufen. Das Bild wird an den Erfolg-Rückruf als base64-codierte `String` oder als URI für die Image-Datei übergeben. Die Methode selbst gibt ein `CameraPopoverHandle`-Objekt, das verwendet werden kann, um die Datei-Auswahl-Popover neu zu positionieren. + + navigator.camera.getPicture(cameraSuccess, cameraError, cameraOptions); + + +#### Beschreibung + +Die `camera.getPicture`-Funktion öffnet das Gerät Standard-Kamera-Anwendung, die Benutzern ermöglicht, Bilder ausrichten. Dieses Verhalten tritt in der Standardeinstellung, wenn `Camera.sourceType` `Camera.PictureSourceType.CAMERA` entspricht. Sobald der Benutzer die Fotoschnäpper, die Kameraanwendung geschlossen wird und die Anwendung wird wiederhergestellt. + +Wenn `Camera.sourceType` `Camera.PictureSourceType.PHOTOLIBRARY` oder `Camera.PictureSourceType.SAVEDPHOTOALBUM` ist, dann wird ein Dialogfeld angezeigt, das Benutzern ermöglicht, ein vorhandenes Bild auszuwählen. Die `camera.getPicture`-Funktion gibt ein `CameraPopoverHandle`-Objekt, das verwendet werden kann, um die Bild-Auswahl-Dialog, z. B. beim ändert sich der Orientierung des Geräts neu positionieren. + +Der Rückgabewert wird an die `cameraSuccess`-Callback-Funktion in einem der folgenden Formate, je nach dem angegebenen `cameraOptions` gesendet: + + * A `String` mit dem base64-codierte Foto-Bild. + + * A `String` , die die Bild-Datei-Stelle auf lokalem Speicher (Standard). + +Sie können tun, was Sie wollen, mit dem codierten Bildes oder URI, zum Beispiel: + + * Rendern Sie das Bild in ein `` Tag, wie im folgenden Beispiel + + * Die Daten lokal zu speichern ( `LocalStorage` , [Lawnchair](http://brianleroux.github.com/lawnchair/), etc..) + + * Post die Daten an einen entfernten server + +**Hinweis**: Fotoauflösung auf neueren Geräten ist ganz gut. Fotos aus dem Gerät Galerie ausgewählt sind nicht zu einer niedrigeren Qualität herunterskaliert, selbst wenn ein `Qualität`-Parameter angegeben wird. Um Speicherprobleme zu vermeiden, legen Sie `Camera.destinationType` auf `FILE_URI` statt `DATA_URL`. + +#### Unterstützte Plattformen + +![](doc/img/android-success.png) ![](doc/img/blackberry-success.png) ![](doc/img/browser-success.png) ![](doc/img/firefox-success.png) ![](doc/img/fireos-success.png) ![](doc/img/ios-success.png) ![](doc/img/windows-success.png) ![](doc/img/wp8-success.png) ![](doc/img/ubuntu-success.png) + +#### Beispiel + +Nehmen Sie ein Foto und rufen Sie sie als base64-codierte Bild: + + navigator.camera.getPicture(onSuccess, onFail, { quality: 50, + destinationType: Camera.DestinationType.DATA_URL + }); + + function onSuccess(imageData) { + var image = document.getElementById('myImage'); + image.src = "data:image/jpeg;base64," + imageData; + } + + function onFail(message) { + alert('Failed because: ' + message); + } + + +Nehmen Sie ein Foto und rufen Sie das Bild-Datei-Speicherort: + + navigator.camera.getPicture(onSuccess, onFail, { quality: 50, + destinationType: Camera.DestinationType.FILE_URI }); + + function onSuccess(imageURI) { + var image = document.getElementById('myImage'); + image.src = imageURI; + } + + function onFail(message) { + alert('Failed because: ' + message); + } + + +#### "Einstellungen" (iOS) + + * **CameraUsesGeolocation** (Boolean, Standardwert ist False). Zur Erfassung von JPEGs, auf true festgelegt, um Geolocation-Daten im EXIF-Header zu erhalten. Dies löst einen Antrag auf Geolocation-Berechtigungen, wenn auf True festgelegt. + + + + +#### Amazon Fire OS Macken + +Amazon Fire OS verwendet Absichten zum Starten von der Kamera-Aktivität auf dem Gerät, um Bilder zu erfassen und auf Handys mit wenig Speicher, Cordova Tätigkeit getötet werden kann. In diesem Szenario kann das Bild nicht angezeigt, wenn die Aktivität von Cordova wiederhergestellt wird. + +#### Android Eigenarten + +Android verwendet Absichten zum Starten von der Kamera-Aktivität auf dem Gerät, um Bilder zu erfassen und auf Handys mit wenig Speicher, Cordova Tätigkeit getötet werden kann. In diesem Szenario kann das Bild nicht angezeigt, wenn die Aktivität von Cordova wiederhergestellt wird. + +#### Browser-Eigenheiten + +Fotos können nur als base64-codierte Bild zurückgeben werden. + +#### Firefox OS Macken + +Kamera-Plugin ist derzeit implementiert mithilfe von [Web-Aktivitäten](https://hacks.mozilla.org/2013/01/introducing-web-activities/). + +#### iOS Macken + +Einschließlich einer JavaScript-`alert()` entweder Rückruffunktionen kann Probleme verursachen. Wickeln Sie die Warnung innerhalb eine `setTimeout()` erlauben die iOS-Bild-Picker oder Popover vollständig zu schließen, bevor die Warnung angezeigt: + + setTimeout(function() { + // do your thing here! + }, 0); + + +#### Windows Phone 7 Macken + +Die native Kameraanwendung aufrufen, während das Gerät via Zune angeschlossen ist funktioniert nicht und löst eine Fehler-Callback. + +#### Tizen Macken + +Tizen unterstützt nur ein `DestinationType` von `Camera.DestinationType.FILE_URI` und ein `SourceType` von `Camera.PictureSourceType.PHOTOLIBRARY`. + +## CameraOptions + +Optionale Parameter die Kameraeinstellungen anpassen. + + { quality : 75, + destinationType : Camera.DestinationType.DATA_URL, + sourceType : Camera.PictureSourceType.CAMERA, + allowEdit : true, + encodingType: Camera.EncodingType.JPEG, + targetWidth: 100, + targetHeight: 100, + popoverOptions: CameraPopoverOptions, + saveToPhotoAlbum: false }; + + + * **Qualität**: Qualität des gespeicherten Bildes, ausgedrückt als ein Bereich von 0-100, wo 100 in der Regel voller Auflösung ohne Verlust aus der Dateikomprimierung ist. Der Standardwert ist 50. *(Anzahl)* (Beachten Sie, dass Informationen über die Kamera Auflösung nicht verfügbar ist.) + + * **DestinationType**: Wählen Sie das Format des Rückgabewerts. Der Standardwert ist FILE_URI. Im Sinne `navigator.camera.DestinationType` *(Anzahl)* + + Camera.DestinationType = { + DATA_URL : 0, // Return image as base64-encoded string + FILE_URI : 1, // Return image file URI + NATIVE_URI : 2 // Return image native URI (e.g., assets-library:// on iOS or content:// on Android) + }; + + + * **SourceType**: Legen Sie die Quelle des Bildes. Der Standardwert ist die Kamera. Im Sinne `navigator.camera.PictureSourceType` *(Anzahl)* + + Camera.PictureSourceType = { + PHOTOLIBRARY : 0, + CAMERA : 1, + SAVEDPHOTOALBUM : 2 + }; + + + * **AllowEdit**: einfache Bearbeitung des Bildes vor Auswahl zu ermöglichen. *(Boolesch)* + + * **EncodingType**: die zurückgegebene Image-Datei ist Codierung auswählen. Standardwert ist JPEG. Im Sinne `navigator.camera.EncodingType` *(Anzahl)* + + Camera.EncodingType = { + JPEG : 0, // Return JPEG encoded image + PNG : 1 // Return PNG encoded image + }; + + + * **TargetWidth**: Breite in Pixel zum Bild skalieren. Muss mit **TargetHeight**verwendet werden. Seitenverhältnis bleibt konstant. *(Anzahl)* + + * **TargetHeight**: Höhe in Pixel zum Bild skalieren. Muss mit **TargetWidth**verwendet werden. Seitenverhältnis bleibt konstant. *(Anzahl)* + + * **MediaType**: Legen Sie den Typ der Medien zur Auswahl. Funktioniert nur, wenn `PictureSourceType` ist `PHOTOLIBRARY` oder `SAVEDPHOTOALBUM` . Im Sinne `nagivator.camera.MediaType` *(Anzahl)* + + Camera.MediaType = { + PICTURE: 0, // allow selection of still pictures only. STANDARD. Will return format specified via DestinationType + VIDEO: 1, // allow selection of video only, WILL ALWAYS RETURN FILE_URI + ALLMEDIA : 2 // allow selection from all media types + }; + + + * **CorrectOrientation**: Drehen Sie das Bild um die Ausrichtung des Geräts während der Aufnahme zu korrigieren. *(Boolesch)* + + * **SaveToPhotoAlbum**: das Bild auf das Fotoalbum auf dem Gerät zu speichern, nach Einnahme. *(Boolesch)* + + * **PopoverOptions**: iOS-nur Optionen, die Popover Lage in iPad angeben. In definierten`CameraPopoverOptions`. + + * **CameraDirection**: Wählen Sie die Kamera (vorn oder hinten-gerichtete) verwenden. Der Standardwert ist zurück. Im Sinne `navigator.camera.Direction` *(Anzahl)* + + Camera.Direction = { + BACK : 0, // Use the back-facing camera + FRONT : 1 // Use the front-facing camera + }; + + +#### Amazon Fire OS Macken + + * `cameraDirection`Ergebnisse in einem hinten gerichteter Foto Wert. + + * Ignoriert die `allowEdit` Parameter. + + * `Camera.PictureSourceType.PHOTOLIBRARY`und `Camera.PictureSourceType.SAVEDPHOTOALBUM` beide das gleiche Fotoalbum anzuzeigen. + +#### Android Eigenarten + + * `cameraDirection`Ergebnisse in einem hinten gerichteter Foto Wert. + + * Android verwendet auch die Ernte-Aktivität für AllowEdit, obwohl Ernte sollte arbeiten und das zugeschnittene Bild zurück zu Cordova, das einzige, dass Werke konsequent die gebündelt mit der Google-Plus-Fotos-Anwendung ist tatsächlich zu übergeben. Andere Kulturen funktioniert möglicherweise nicht. + + * `Camera.PictureSourceType.PHOTOLIBRARY`und `Camera.PictureSourceType.SAVEDPHOTOALBUM` beide das gleiche Fotoalbum anzuzeigen. + +#### BlackBerry 10 Macken + + * Ignoriert die `quality` Parameter. + + * Ignoriert die `allowEdit` Parameter. + + * `Camera.MediaType`wird nicht unterstützt. + + * Ignoriert die `correctOrientation` Parameter. + + * Ignoriert die `cameraDirection` Parameter. + +#### Firefox OS Macken + + * Ignoriert die `quality` Parameter. + + * `Camera.DestinationType`wird ignoriert, und gleich `1` (Bilddatei-URI) + + * Ignoriert die `allowEdit` Parameter. + + * Ignoriert die `PictureSourceType` Parameter (Benutzer wählt es in einem Dialogfenster) + + * Ignoriert die`encodingType` + + * Ignoriert die `targetWidth` und`targetHeight` + + * `Camera.MediaType`wird nicht unterstützt. + + * Ignoriert die `correctOrientation` Parameter. + + * Ignoriert die `cameraDirection` Parameter. + +#### iOS Macken + + * Legen Sie `quality` unter 50 Speicherfehler auf einigen Geräten zu vermeiden. + + * Bei der Verwendung `destinationType.FILE_URI` , Fotos werden im temporären Verzeichnis der Anwendung gespeichert. Den Inhalt des temporären Verzeichnis der Anwendung wird gelöscht, wenn die Anwendung beendet. + +#### Tizen Macken + + * nicht unterstützte Optionen + + * gibt immer einen Datei-URI + +#### Windows Phone 7 und 8 Eigenarten + + * Ignoriert die `allowEdit` Parameter. + + * Ignoriert die `correctOrientation` Parameter. + + * Ignoriert die `cameraDirection` Parameter. + + * Ignoriert die `saveToPhotoAlbum` Parameter. WICHTIG: Alle Aufnahmen die wp7/8 Cordova-Kamera-API werden immer in Kamerarolle des Telefons kopiert. Abhängig von den Einstellungen des Benutzers könnte dies auch bedeuten, dass das Bild in ihre OneDrive automatisch hochgeladen ist. Dies könnte möglicherweise bedeuten, dass das Bild für ein breiteres Publikum als Ihre Anwendung vorgesehen ist. Wenn diese einen Blocker für Ihre Anwendung, Sie müssen die CameraCaptureTask zu implementieren, wie im Msdn dokumentiert: Sie können kommentieren oder Up-Abstimmung das Beiträge zu diesem Thema im [Bugtracker](https://issues.apache.org/jira/browse/CB-2083) + + * Ignoriert die `mediaType` -Eigenschaft des `cameraOptions` wie das Windows Phone SDK keine Möglichkeit, Fotothek Videos wählen. + +## CameraError + +onError-Callback-Funktion, die eine Fehlermeldung bereitstellt. + + function(message) { + // Show a helpful message + } + + +#### Beschreibung + + * **Meldung**: die Nachricht wird durch das Gerät systemeigenen Code bereitgestellt. *(String)* + +## cameraSuccess + +onSuccess Callback-Funktion, die die Bilddaten bereitstellt. + + function(imageData) { + // Do something with the image + } + + +#### Beschreibung + + * **CMYK**: Base64-Codierung der Bilddaten, *oder* die Image-Datei-URI, je nach `cameraOptions` in Kraft. *(String)* + +#### Beispiel + + // Show image + // + function cameraCallback(imageData) { + var image = document.getElementById('myImage'); + image.src = "data:image/jpeg;base64," + imageData; + } + + +## CameraPopoverHandle + +Ein Handle für das Dialogfeld "Popover" erstellt von `navigator.camera.getPicture`. + +#### Beschreibung + + * **setPosition**: Set the position of the popover. Takes the `CameraPopoverOptions` that specify the new position. + +#### Unterstützte Plattformen + +![](doc/img/android-fail.png) ![](doc/img/blackberry-fail.png) ![](doc/img/browser-fail.png) ![](doc/img/firefox-fail.png) ![](doc/img/fireos-fail.png) ![](doc/img/ios-success.png) ![](doc/img/windows-fail.png) ![](doc/img/wp8-fail.png) ![](doc/img/ubuntu-fail.png) + +#### Beispiel + + var cameraPopoverHandle = navigator.camera.getPicture(onSuccess, onFail, + { destinationType: Camera.DestinationType.FILE_URI, + sourceType: Camera.PictureSourceType.PHOTOLIBRARY, + popoverOptions: new CameraPopoverOptions(300, 300, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY) + }); + + // Reposition the popover if the orientation changes. + window.onorientationchange = function() { + var cameraPopoverOptions = new CameraPopoverOptions(0, 0, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY); + cameraPopoverHandle.setPosition(cameraPopoverOptions); + } + + +## CameraPopoverOptions + +nur iOS-Parametern, die Anker-Element Lage und Pfeil Richtung der Popover angeben, bei der Auswahl von Bildern aus einem iPad Bibliothek oder Album. + + { x : 0, + y : 32, + width : 320, + height : 480, + arrowDir : Camera.PopoverArrowDirection.ARROW_ANY + }; + + +#### Beschreibung + + * **X**: x Pixelkoordinate des Bildschirmelement auf dem der Popover zu verankern. *(Anzahl)* + + * **y**: y Pixelkoordinate des Bildschirmelement auf dem der Popover zu verankern. *(Anzahl)* + + * **width**: Breite in Pixeln, das Bildschirmelement auf dem der Popover zu verankern. *(Anzahl)* + + * **height**: Höhe in Pixeln, das Bildschirmelement auf dem der Popover zu verankern. *(Anzahl)* + + * **arrowDir**: Richtung der Pfeil auf der Popover zeigen sollte. Im Sinne `Camera.PopoverArrowDirection` *(Anzahl)* + + Camera.PopoverArrowDirection = { + ARROW_UP : 1, // matches iOS UIPopoverArrowDirection constants + ARROW_DOWN : 2, + ARROW_LEFT : 4, + ARROW_RIGHT : 8, + ARROW_ANY : 15 + }; + + +Beachten Sie, dass die Größe der Popover ändern kann, um die Richtung des Pfeils und Ausrichtung des Bildschirms anzupassen. Achten Sie darauf, um Orientierung zu berücksichtigen, wenn Sie den Anker-Element-Speicherort angeben. + +## navigator.camera.cleanup + +Entfernt Mittelstufe Fotos von der Kamera aus der vorübergehenden Verwahrung genommen. + + navigator.camera.cleanup( cameraSuccess, cameraError ); + + +#### Beschreibung + +Fortgeschrittene Image-Dateien, die in vorübergehender Verwahrung gehalten werden, nach dem Aufruf von `camera.getPicture` entfernt. Gilt nur wenn der Wert von `Camera.sourceType` gleich `Camera.PictureSourceType.CAMERA` und `Camera.destinationType` gleich `Camera.DestinationType.FILE_URI`. + +#### Unterstützte Plattformen + +![](doc/img/android-fail.png) ![](doc/img/blackberry-fail.png) ![](doc/img/browser-fail.png) ![](doc/img/firefox-fail.png) ![](doc/img/fireos-fail.png) ![](doc/img/ios-success.png) ![](doc/img/windows-fail.png) ![](doc/img/wp8-fail.png) ![](doc/img/ubuntu-fail.png) + +#### Beispiel + + navigator.camera.cleanup(onSuccess, onFail); + + function onSuccess() { + console.log("Camera cleanup success.") + } + + function onFail(message) { + alert('Failed because: ' + message); + } \ No newline at end of file diff --git a/plugins/cordova-plugin-camera/doc/de/index.md b/plugins/cordova-plugin-camera/doc/de/index.md new file mode 100644 index 0000000..1c7486c --- /dev/null +++ b/plugins/cordova-plugin-camera/doc/de/index.md @@ -0,0 +1,434 @@ + + +# cordova-plugin-camera + +Dieses Plugin definiert eine globale `navigator.camera`-Objekt, das eine API für Aufnahmen und für die Auswahl der Bilder aus dem System-Image-Library bietet. + +Obwohl das Objekt mit der globalen Gültigkeitsbereich `navigator` verbunden ist, steht es nicht bis nach dem `Deviceready`-Ereignis. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(navigator.camera); + } + + +## Installation + + cordova plugin add cordova-plugin-camera + + +## navigator.camera.getPicture + +Nimmt ein Foto mit der Kamera, oder ein Foto aus dem Gerät Bildergalerie abgerufen. Das Bild wird an den Erfolg-Rückruf als base64-codierte `String` oder als URI für die Image-Datei übergeben. Die Methode selbst gibt ein `CameraPopoverHandle`-Objekt, das verwendet werden kann, um die Datei-Auswahl-Popover neu zu positionieren. + + navigator.camera.getPicture( cameraSuccess, cameraError, cameraOptions ); + + +### Beschreibung + +Die `camera.getPicture`-Funktion öffnet das Gerät Standard-Kamera-Anwendung, die Benutzern ermöglicht, Bilder ausrichten. Dieses Verhalten tritt in der Standardeinstellung, wenn `Camera.sourceType` `Camera.PictureSourceType.CAMERA` entspricht. Sobald der Benutzer die Fotoschnäpper, die Kameraanwendung geschlossen wird und die Anwendung wird wiederhergestellt. + +Wenn `Camera.sourceType` `Camera.PictureSourceType.PHOTOLIBRARY` oder `Camera.PictureSourceType.SAVEDPHOTOALBUM` ist, dann wird ein Dialogfeld angezeigt, das Benutzern ermöglicht, ein vorhandenes Bild auszuwählen. Die `camera.getPicture`-Funktion gibt ein `CameraPopoverHandle`-Objekt, das verwendet werden kann, um die Bild-Auswahl-Dialog, z. B. beim ändert sich der Orientierung des Geräts neu positionieren. + +Der Rückgabewert wird an die `cameraSuccess`-Callback-Funktion in einem der folgenden Formate, je nach dem angegebenen `cameraOptions` gesendet: + +* A `String` mit dem base64-codierte Foto-Bild. + +* A `String` , die die Bild-Datei-Stelle auf lokalem Speicher (Standard). + +Sie können tun, was Sie wollen, mit dem codierten Bildes oder URI, zum Beispiel: + +* Rendern Sie das Bild in ein `` Tag, wie im folgenden Beispiel + +* Die Daten lokal zu speichern ( `LocalStorage` , [Lawnchair][1], etc..) + +* Post die Daten an einen entfernten server + + [1]: http://brianleroux.github.com/lawnchair/ + +**Hinweis**: Fotoauflösung auf neueren Geräten ist ganz gut. Fotos aus dem Gerät Galerie ausgewählt sind nicht zu einer niedrigeren Qualität herunterskaliert, selbst wenn ein `Qualität`-Parameter angegeben wird. Um Speicherprobleme zu vermeiden, legen Sie `Camera.destinationType` auf `FILE_URI` statt `DATA_URL`. + +### Unterstützte Plattformen + +* Amazon Fire OS +* Android +* BlackBerry 10 +* Browser +* Firefox OS +* iOS +* Tizen +* Windows Phone 7 und 8 +* Windows 8 + +### "Einstellungen" (iOS) + +* **CameraUsesGeolocation** (Boolean, Standardwert ist False). Zur Erfassung von JPEGs, auf true festgelegt, um Geolocation-Daten im EXIF-Header zu erhalten. Dies löst einen Antrag auf Geolocation-Berechtigungen, wenn auf True festgelegt. + + + + +### Amazon Fire OS Macken + +Amazon Fire OS verwendet Absichten zum Starten von der Kamera-Aktivität auf dem Gerät, um Bilder zu erfassen und auf Handys mit wenig Speicher, Cordova Tätigkeit getötet werden kann. In diesem Szenario kann das Bild nicht angezeigt, wenn die Aktivität von Cordova wiederhergestellt wird. + +### Android Eigenarten + +Android verwendet Absichten zum Starten von der Kamera-Aktivität auf dem Gerät, um Bilder zu erfassen und auf Handys mit wenig Speicher, Cordova Tätigkeit getötet werden kann. In diesem Szenario kann das Bild nicht angezeigt, wenn die Aktivität von Cordova wiederhergestellt wird. + +### Browser-Eigenheiten + +Fotos können nur als base64-codierte Bild zurückgeben werden. + +### Firefox OS Macken + +Kamera-Plugin ist derzeit implementiert mithilfe von [Web-Aktivitäten][2]. + + [2]: https://hacks.mozilla.org/2013/01/introducing-web-activities/ + +### iOS Macken + +Einschließlich einer JavaScript-`alert()` entweder Rückruffunktionen kann Probleme verursachen. Wickeln Sie die Warnung innerhalb eine `setTimeout()` erlauben die iOS-Bild-Picker oder Popover vollständig zu schließen, bevor die Warnung angezeigt: + + setTimeout(function() { + // do your thing here! + }, 0); + + +### Windows Phone 7 Macken + +Die native Kameraanwendung aufrufen, während das Gerät via Zune angeschlossen ist funktioniert nicht und löst eine Fehler-Callback. + +### Tizen Macken + +Tizen unterstützt nur ein `DestinationType` von `Camera.DestinationType.FILE_URI` und ein `SourceType` von `Camera.PictureSourceType.PHOTOLIBRARY`. + +### Beispiel + +Nehmen Sie ein Foto und rufen Sie sie als base64-codierte Bild: + + navigator.camera.getPicture(onSuccess, onFail, { quality: 50, + destinationType: Camera.DestinationType.DATA_URL + }); + + function onSuccess(imageData) { + var image = document.getElementById('myImage'); + image.src = "data:image/jpeg;base64," + imageData; + } + + function onFail(message) { + alert('Failed because: ' + message); + } + + +Nehmen Sie ein Foto und rufen Sie das Bild-Datei-Speicherort: + + navigator.camera.getPicture(onSuccess, onFail, { quality: 50, + destinationType: Camera.DestinationType.FILE_URI }); + + function onSuccess(imageURI) { + var image = document.getElementById('myImage'); + image.src = imageURI; + } + + function onFail(message) { + alert('Failed because: ' + message); + } + + +## CameraOptions + +Optionale Parameter die Kameraeinstellungen anpassen. + + { quality : 75, + destinationType : Camera.DestinationType.DATA_URL, + sourceType : Camera.PictureSourceType.CAMERA, + allowEdit : true, + encodingType: Camera.EncodingType.JPEG, + targetWidth: 100, + targetHeight: 100, + popoverOptions: CameraPopoverOptions, + saveToPhotoAlbum: false }; + + +### Optionen + +* **Qualität**: Qualität des gespeicherten Bildes, ausgedrückt als ein Bereich von 0-100, wo 100 in der Regel voller Auflösung ohne Verlust aus der Dateikomprimierung ist. Der Standardwert ist 50. *(Anzahl)* (Beachten Sie, dass Informationen über die Kamera Auflösung nicht verfügbar ist.) + +* **DestinationType**: Wählen Sie das Format des Rückgabewerts. Der Standardwert ist FILE_URI. Im Sinne `navigator.camera.DestinationType` *(Anzahl)* + + Camera.DestinationType = { + DATA_URL : 0, // Return image as base64-encoded string + FILE_URI : 1, // Return image file URI + NATIVE_URI : 2 // Return image native URI (e.g., assets-library:// on iOS or content:// on Android) + }; + + +* **SourceType**: Legen Sie die Quelle des Bildes. Der Standardwert ist die Kamera. Im Sinne `navigator.camera.PictureSourceType` *(Anzahl)* + + Camera.PictureSourceType = { + PHOTOLIBRARY : 0, + CAMERA : 1, + SAVEDPHOTOALBUM : 2 + }; + + +* **AllowEdit**: einfache Bearbeitung des Bildes vor Auswahl zu ermöglichen. *(Boolesch)* + +* **EncodingType**: die zurückgegebene Image-Datei ist Codierung auswählen. Standardwert ist JPEG. Im Sinne `navigator.camera.EncodingType` *(Anzahl)* + + Camera.EncodingType = { + JPEG : 0, // Return JPEG encoded image + PNG : 1 // Return PNG encoded image + }; + + +* **TargetWidth**: Breite in Pixel zum Bild skalieren. Muss mit **TargetHeight**verwendet werden. Seitenverhältnis bleibt konstant. *(Anzahl)* + +* **TargetHeight**: Höhe in Pixel zum Bild skalieren. Muss mit **TargetWidth**verwendet werden. Seitenverhältnis bleibt konstant. *(Anzahl)* + +* **MediaType**: Legen Sie den Typ der Medien zur Auswahl. Funktioniert nur, wenn `PictureSourceType` ist `PHOTOLIBRARY` oder `SAVEDPHOTOALBUM` . Im Sinne `nagivator.camera.MediaType` *(Anzahl)* + + Camera.MediaType = { + PICTURE: 0, // allow selection of still pictures only. STANDARD. Will return format specified via DestinationType + VIDEO: 1, // allow selection of video only, WILL ALWAYS RETURN FILE_URI + ALLMEDIA : 2 // allow selection from all media types + }; + + +* **CorrectOrientation**: Drehen Sie das Bild um die Ausrichtung des Geräts während der Aufnahme zu korrigieren. *(Boolesch)* + +* **SaveToPhotoAlbum**: das Bild auf das Fotoalbum auf dem Gerät zu speichern, nach Einnahme. *(Boolesch)* + +* **PopoverOptions**: iOS-nur Optionen, die Popover Lage in iPad angeben. In definierten`CameraPopoverOptions`. + +* **CameraDirection**: Wählen Sie die Kamera (vorn oder hinten-gerichtete) verwenden. Der Standardwert ist zurück. Im Sinne `navigator.camera.Direction` *(Anzahl)* + + Camera.Direction = { + BACK : 0, // Use the back-facing camera + FRONT : 1 // Use the front-facing camera + }; + + +### Amazon Fire OS Macken + +* `cameraDirection`Ergebnisse in einem hinten gerichteter Foto Wert. + +* Ignoriert die `allowEdit` Parameter. + +* `Camera.PictureSourceType.PHOTOLIBRARY`und `Camera.PictureSourceType.SAVEDPHOTOALBUM` beide das gleiche Fotoalbum anzuzeigen. + +### Android Eigenarten + +* `cameraDirection`Ergebnisse in einem hinten gerichteter Foto Wert. + +* Ignoriert die `allowEdit` Parameter. + +* `Camera.PictureSourceType.PHOTOLIBRARY`und `Camera.PictureSourceType.SAVEDPHOTOALBUM` beide das gleiche Fotoalbum anzuzeigen. + +### BlackBerry 10 Macken + +* Ignoriert die `quality` Parameter. + +* Ignoriert die `allowEdit` Parameter. + +* `Camera.MediaType`wird nicht unterstützt. + +* Ignoriert die `correctOrientation` Parameter. + +* Ignoriert die `cameraDirection` Parameter. + +### Firefox OS Macken + +* Ignoriert die `quality` Parameter. + +* `Camera.DestinationType`wird ignoriert, und gleich `1` (Bilddatei-URI) + +* Ignoriert die `allowEdit` Parameter. + +* Ignoriert die `PictureSourceType` Parameter (Benutzer wählt es in einem Dialogfenster) + +* Ignoriert die`encodingType` + +* Ignoriert die `targetWidth` und`targetHeight` + +* `Camera.MediaType`wird nicht unterstützt. + +* Ignoriert die `correctOrientation` Parameter. + +* Ignoriert die `cameraDirection` Parameter. + +### iOS Macken + +* Legen Sie `quality` unter 50 Speicherfehler auf einigen Geräten zu vermeiden. + +* Bei der Verwendung `destinationType.FILE_URI` , Fotos werden im temporären Verzeichnis der Anwendung gespeichert. Den Inhalt des temporären Verzeichnis der Anwendung wird gelöscht, wenn die Anwendung beendet. + +### Tizen Macken + +* nicht unterstützte Optionen + +* gibt immer einen Datei-URI + +### Windows Phone 7 und 8 Eigenarten + +* Ignoriert die `allowEdit` Parameter. + +* Ignoriert die `correctOrientation` Parameter. + +* Ignoriert die `cameraDirection` Parameter. + +* Ignoriert die `saveToPhotoAlbum` Parameter. WICHTIG: Alle Aufnahmen die wp7/8 Cordova-Kamera-API werden immer in Kamerarolle des Telefons kopiert. Abhängig von den Einstellungen des Benutzers könnte dies auch bedeuten, dass das Bild in ihre OneDrive automatisch hochgeladen ist. Dies könnte möglicherweise bedeuten, dass das Bild für ein breiteres Publikum als Ihre Anwendung vorgesehen ist. Wenn diese einen Blocker für Ihre Anwendung, Sie müssen die CameraCaptureTask zu implementieren, wie im Msdn dokumentiert: Sie können kommentieren oder Up-Abstimmung das Beiträge zu diesem Thema im [Bugtracker][3] + +* Ignoriert die `mediaType` -Eigenschaft des `cameraOptions` wie das Windows Phone SDK keine Möglichkeit, Fotothek Videos wählen. + + [3]: https://issues.apache.org/jira/browse/CB-2083 + +## CameraError + +onError-Callback-Funktion, die eine Fehlermeldung bereitstellt. + + function(message) { + // Show a helpful message + } + + +### Parameter + +* **Meldung**: die Nachricht wird durch das Gerät systemeigenen Code bereitgestellt. *(String)* + +## cameraSuccess + +onSuccess Callback-Funktion, die die Bilddaten bereitstellt. + + function(imageData) { + // Do something with the image + } + + +### Parameter + +* **CMYK**: Base64-Codierung der Bilddaten, *oder* die Image-Datei-URI, je nach `cameraOptions` in Kraft. *(String)* + +### Beispiel + + // Show image + // + function cameraCallback(imageData) { + var image = document.getElementById('myImage'); + image.src = "data:image/jpeg;base64," + imageData; + } + + +## CameraPopoverHandle + +Ein Handle für das Dialogfeld "Popover" erstellt von `navigator.camera.getPicture`. + +### Methoden + +* **SetPosition**: Legen Sie die Position der Popover. + +### Unterstützte Plattformen + +* iOS + +### setPosition + +Legen Sie die Position von der Popover. + +**Parameter**: + +* `cameraPopoverOptions`: die `CameraPopoverOptions` angeben, dass die neue Position + +### Beispiel + + var cameraPopoverHandle = navigator.camera.getPicture(onSuccess, onFail, + { destinationType: Camera.DestinationType.FILE_URI, + sourceType: Camera.PictureSourceType.PHOTOLIBRARY, + popoverOptions: new CameraPopoverOptions(300, 300, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY) + }); + + // Reposition the popover if the orientation changes. + window.onorientationchange = function() { + var cameraPopoverOptions = new CameraPopoverOptions(0, 0, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY); + cameraPopoverHandle.setPosition(cameraPopoverOptions); + } + + +## CameraPopoverOptions + +nur iOS-Parametern, die Anker-Element Lage und Pfeil Richtung der Popover angeben, bei der Auswahl von Bildern aus einem iPad Bibliothek oder Album. + + { x : 0, + y : 32, + width : 320, + height : 480, + arrowDir : Camera.PopoverArrowDirection.ARROW_ANY + }; + + +### CameraPopoverOptions + +* **X**: x Pixelkoordinate des Bildschirmelement auf dem der Popover zu verankern. *(Anzahl)* + +* **y**: y Pixelkoordinate des Bildschirmelement auf dem der Popover zu verankern. *(Anzahl)* + +* **width**: Breite in Pixeln, das Bildschirmelement auf dem der Popover zu verankern. *(Anzahl)* + +* **height**: Höhe in Pixeln, das Bildschirmelement auf dem der Popover zu verankern. *(Anzahl)* + +* **arrowDir**: Richtung der Pfeil auf der Popover zeigen sollte. Im Sinne `Camera.PopoverArrowDirection` *(Anzahl)* + + Camera.PopoverArrowDirection = { + ARROW_UP : 1, // matches iOS UIPopoverArrowDirection constants + ARROW_DOWN : 2, + ARROW_LEFT : 4, + ARROW_RIGHT : 8, + ARROW_ANY : 15 + }; + + +Beachten Sie, dass die Größe der Popover ändern kann, um die Richtung des Pfeils und Ausrichtung des Bildschirms anzupassen. Achten Sie darauf, um Orientierung zu berücksichtigen, wenn Sie den Anker-Element-Speicherort angeben. + +## navigator.camera.cleanup + +Entfernt Mittelstufe Fotos von der Kamera aus der vorübergehenden Verwahrung genommen. + + navigator.camera.cleanup( cameraSuccess, cameraError ); + + +### Beschreibung + +Fortgeschrittene Image-Dateien, die in vorübergehender Verwahrung gehalten werden, nach dem Aufruf von `camera.getPicture` entfernt. Gilt nur wenn der Wert von `Camera.sourceType` gleich `Camera.PictureSourceType.CAMERA` und `Camera.destinationType` gleich `Camera.DestinationType.FILE_URI`. + +### Unterstützte Plattformen + +* iOS + +### Beispiel + + navigator.camera.cleanup(onSuccess, onFail); + + function onSuccess() { + console.log("Camera cleanup success.") + } + + function onFail(message) { + alert('Failed because: ' + message); + } diff --git a/plugins/cordova-plugin-camera/doc/es/README.md b/plugins/cordova-plugin-camera/doc/es/README.md new file mode 100644 index 0000000..76af164 --- /dev/null +++ b/plugins/cordova-plugin-camera/doc/es/README.md @@ -0,0 +1,411 @@ + + +# cordova-plugin-camera + +[![Build Status](https://travis-ci.org/apache/cordova-plugin-camera.svg)](https://travis-ci.org/apache/cordova-plugin-camera) + +Este plugin define un global `navigator.camera` objeto que proporciona una API para tomar fotografías y por elegir imágenes de biblioteca de imágenes del sistema. + +Aunque el objeto está unido al ámbito global `navigator` , no estará disponible hasta después de la `deviceready` evento. + + document.addEventListener ("deviceready", onDeviceReady, false); + function onDeviceReady() {console.log(navigator.camera)}; + + +## Instalación + + cordova plugin add cordova-plugin-camera + + +## API + + * Cámara + * navigator.camera.getPicture(success, fail, options) + * CameraOptions + * CameraPopoverHandle + * CameraPopoverOptions + * Navigator.Camera.Cleanup + +## navigator.camera.getPicture + +Toma una foto con la cámara, o recupera una foto de Galería de imágenes del dispositivo. La imagen se pasa a la devolución de llamada de éxito como un codificado en base64 `String` , o como el URI para el archivo de imagen. El método se devuelve un `CameraPopoverHandle` objeto que puede utilizarse para volver a colocar el popover de selección de archivo. + + navigator.camera.getPicture(cameraSuccess, cameraError, cameraOptions); + + +#### Descripción + +El `camera.getPicture` función abre la aplicación de cámara predeterminada del dispositivo que permite a los usuarios ajustar imágenes. Este comportamiento se produce de forma predeterminada, cuando `Camera.sourceType` es igual a `Camera.PictureSourceType.CAMERA` . Una vez que el usuario ajusta la foto, una aplicación de cámara se cierra y se restablecerá la aplicación. + +Si `Camera.sourceType` es `Camera.PictureSourceType.PHOTOLIBRARY` o `Camera.PictureSourceType.SAVEDPHOTOALBUM` , entonces una muestra de diálogo que permite a los usuarios seleccionar una imagen existente. El `camera.getPicture` función devuelve un `CameraPopoverHandle` objeto, que puede utilizarse para volver a colocar el diálogo de selección de imagen, por ejemplo, cuando cambia la orientación del dispositivo. + +El valor devuelto es enviado a la `cameraSuccess` función de callback, en uno de los formatos siguientes, dependiendo del objeto `cameraOptions` : + + * Una `String` que contiene la imagen codificada en base64. + + * Una `String` que representa la ubicación del archivo de imagen en almacenamiento local (por defecto). + +Puedes hacer lo que quieras con la imagen codificada o URI, por ejemplo: + + * Representar la imagen en una etiqueta de ``, como en el ejemplo siguiente + + * Guardar los datos localmente (`LocalStorage`, [Lawnchair](http://brianleroux.github.com/lawnchair/), etc.) + + * Enviar los datos a un servidor remoto + +**Nota**: resolución de la foto en los nuevos dispositivos es bastante bueno. Fotos seleccionadas de la Galería del dispositivo no son degradadas a una calidad más baja, incluso si un `quality` se especifica el parámetro. Para evitar problemas con la memoria común, establezca `Camera.destinationType` a `FILE_URI` en lugar de`DATA_URL`. + +#### Plataformas soportadas + +![](doc/img/android-success.png) ![](doc/img/blackberry-success.png) ![](doc/img/browser-success.png) ![](doc/img/firefox-success.png) ![](doc/img/fireos-success.png) ![](doc/img/ios-success.png) ![](doc/img/windows-success.png) ![](doc/img/wp8-success.png) ![](doc/img/ubuntu-success.png) + +#### Ejemplo + +Tomar una foto y recuperarlo como una imagen codificada en base64: + + navigator.camera.getPicture(onSuccess, onFail, { quality: 50, + destinationType: Camera.DestinationType.DATA_URL + }); + + function onSuccess(imageData) { + var image = document.getElementById('myImage'); + image.src = "data:image/jpeg;base64," + imageData; + } + + function onFail(message) { + alert('Failed because: ' + message); + } + + +Tomar una foto y recuperar la ubicación del archivo de la imagen: + + navigator.camera.getPicture(onSuccess, onFail, { quality: 50, + destinationType: Camera.DestinationType.FILE_URI }); + + function onSuccess(imageURI) { + var image = document.getElementById('myImage'); + image.src = imageURI; + } + + function onFail(message) { + alert('Failed because: ' + message); + } + + +#### Preferencias (iOS) + + * **CameraUsesGeolocation** (booleano, el valor predeterminado de false). Para la captura de imágenes JPEG, establecido en true para obtener datos de geolocalización en la cabecera EXIF. Esto activará la solicitud de permisos de geolocalización si establecido en true. + + + + +#### Amazon fuego OS rarezas + +Amazon fuego OS utiliza los intentos para poner en marcha la actividad de la cámara del dispositivo para capturar imágenes y en teléfonos con poca memoria, puede matar la actividad Cordova. En este escenario, la imagen no aparezca cuando se restaura la actividad cordova. + +#### Rarezas Android + +Android utiliza los intentos para iniciar la actividad de la cámara del dispositivo para capturar imágenes, y en los teléfonos con poca memoria, puede matar la actividad Cordova. En este escenario, la imagen no aparezca cuando se restaura la actividad Cordova. + +#### Navegador rarezas + +Sólo puede devolver fotos como imagen codificada en base64. + +#### Firefox OS rarezas + +Cámara plugin actualmente se implementa mediante [Actividades Web](https://hacks.mozilla.org/2013/01/introducing-web-activities/). + +#### iOS rarezas + +Incluyendo un JavaScript `alert()` en cualquiera de la devolución de llamada funciones pueden causar problemas. Envuelva la alerta dentro de un `setTimeout()` para permitir que el selector de imagen iOS o popover cerrar completamente antes de la alerta se muestra: + + setTimeout(function() { + // do your thing here! + }, 0); + + +#### Windows Phone 7 rarezas + +Invocando la aplicación de cámara nativa mientras el dispositivo está conectado vía Zune no funciona y desencadena un callback de error. + +#### Rarezas Tizen + +Tizen sólo es compatible con un `destinationType` de `Camera.DestinationType.FILE_URI` y un `sourceType` de`Camera.PictureSourceType.PHOTOLIBRARY`. + +## CameraOptions + +Parámetros opcionales para personalizar la configuración de la cámara. + + {calidad: destinationType 75,: Camera.DestinationType.DATA_URL, sourceType: Camera.PictureSourceType.CAMERA, allowEdit: true, encodingType: Camera.EncodingType.JPEG, targetWidth: 100, targetHeight: 100, popoverOptions: CameraPopoverOptions, saveToPhotoAlbum: falsa}; + + + * **calidad**: calidad de la imagen guardada, expresada en un rango de 0-100, donde 100 es típicamente resolución sin pérdida de compresión del archivo. El valor predeterminado es 50. *(Número)* (Tenga en cuenta que no está disponible información sobre resolución de la cámara). + + * **destinationType**: elegir el formato del valor devuelto. El valor predeterminado es FILE_URI. Definido en `navigator.camera.DestinationType` *(número)* + + Camera.DestinationType = { + DATA_URL : 0, // Return image as base64-encoded string + FILE_URI : 1, // Return image file URI + NATIVE_URI : 2 // Return image native URI (e.g., assets-library:// on iOS or content:// on Android) + }; + + + * **sourceType**: establecer el origen de la imagen. El valor predeterminado es cámara. Definido en `navigator.camera.PictureSourceType` *(número)* + + Camera.PictureSourceType = { + PHOTOLIBRARY : 0, + CAMERA : 1, + SAVEDPHOTOALBUM : 2 + }; + + + * **allowEdit**: permite edición sencilla de imagen antes de la selección. *(Booleano)* + + * **encodingType**: elegir la codificación del archivo de imagen devuelta. Por defecto es JPEG. Definido en `navigator.camera.EncodingType` *(número)* + + Camera.EncodingType = { + JPEG : 0, // Return JPEG encoded image + PNG : 1 // Return PNG encoded image + }; + + + * **targetWidth**: ancho en píxeles a escala de la imagen. Debe usarse con **targetHeight**. Proporción se mantiene constante. *(Número)* + + * **targetHeight**: altura en píxeles a escala de la imagen. Debe usarse con **targetWidth**. Proporción se mantiene constante. *(Número)* + + * **mediaType**: definir el tipo de medios para seleccionar. Sólo funciona cuando `PictureSourceType` es `PHOTOLIBRARY` o `SAVEDPHOTOALBUM` . Definido en `nagivator.camera.MediaType` *(número)* + + Camera.MediaType = { + PICTURE: 0, // allow selection of still pictures only. DE FORMA PREDETERMINADA. Will return format specified via DestinationType + VIDEO: 1, // allow selection of video only, WILL ALWAYS RETURN FILE_URI + ALLMEDIA : 2 // allow selection from all media types + }; + + + * **correctOrientation**: rotar la imagen para corregir la orientación del dispositivo durante la captura. *(Booleano)* + + * **saveToPhotoAlbum**: guardar la imagen en el álbum de fotos en el dispositivo después de su captura. *(Booleano)* + + * **popoverOptions**: opciones sólo iOS que especifican popover ubicación en iPad. Definido en`CameraPopoverOptions`. + + * **cameraDirection**: elegir la cámara para usar (o parte posterior-frontal). El valor predeterminado es atrás. Definido en `navigator.camera.Direction` *(número)* + + Camera.Direction = { + BACK : 0, // Use the back-facing camera + FRONT : 1 // Use the front-facing camera + }; + + +#### Amazon fuego OS rarezas + + * Cualquier valor de `cameraDirection` da como resultado una foto orientada hacia atrás. + + * Ignora el `allowEdit` parámetro. + + * `Camera.PictureSourceType.PHOTOLIBRARY` y `Camera.PictureSourceType.SAVEDPHOTOALBUM` Mostrar el mismo álbum de fotos. + +#### Rarezas Android + + * Cualquier valor de `cameraDirection` da como resultado una foto orientada hacia atrás. + + * Android también utiliza la actividad de cultivo de allowEdit, aunque cultivo debe trabajar y realmente pasar la imagen recortada a Córdoba, el único que funciona constantemente es el integrado con la aplicación de Google Plus fotos. Otros cultivos pueden no funcionar. + + * `Camera.PictureSourceType.PHOTOLIBRARY` y `Camera.PictureSourceType.SAVEDPHOTOALBUM` Mostrar el mismo álbum de fotos. + +#### BlackBerry 10 rarezas + + * Ignora el `quality` parámetro. + + * Ignora el `allowEdit` parámetro. + + * `Camera.MediaType`No se admite. + + * Ignora el `correctOrientation` parámetro. + + * Ignora el `cameraDirection` parámetro. + +#### Firefox OS rarezas + + * Ignora el `quality` parámetro. + + * `Camera.DestinationType`se ignora y es igual a `1` (URI del archivo de imagen) + + * Ignora el `allowEdit` parámetro. + + * Ignora el `PictureSourceType` parámetro (el usuario lo elige en una ventana de diálogo) + + * Ignora el`encodingType` + + * Ignora el `targetWidth` y`targetHeight` + + * `Camera.MediaType`No se admite. + + * Ignora el `correctOrientation` parámetro. + + * Ignora el `cameraDirection` parámetro. + +#### iOS rarezas + + * Establecer `quality` por debajo de 50 para evitar errores de memoria en algunos dispositivos. + + * Cuando se utiliza `destinationType.FILE_URI` , fotos se guardan en el directorio temporal de la aplicación. El contenido del directorio temporal de la aplicación se eliminará cuando finalice la aplicación. + +#### Rarezas Tizen + + * opciones no compatibles + + * siempre devuelve un identificador URI de archivo + +#### Windows Phone 7 y 8 rarezas + + * Ignora el `allowEdit` parámetro. + + * Ignora el `correctOrientation` parámetro. + + * Ignora el `cameraDirection` parámetro. + + * Ignora el `saveToPhotoAlbum` parámetro. IMPORTANTE: Todas las imágenes tomadas con la cámara wp7/8 cordova API siempre se copian en rollo de cámara del teléfono. Dependiendo de la configuración del usuario, esto podría significar también que la imagen es auto-subido a su OneDrive. Esto potencialmente podría significar que la imagen está disponible a una audiencia más amplia que su aplicación previsto. Si un bloqueador para su aplicación, usted necesitará aplicar el CameraCaptureTask como se documenta en msdn: también puede comentar o votar hasta el tema relacionado en el [issue tracker de](https://issues.apache.org/jira/browse/CB-2083) + + * Ignora el `mediaType` propiedad de `cameraOptions` como el SDK de Windows Phone no proporciona una manera para elegir vídeos fototeca. + +## CameraError + +onError función callback que proporciona un mensaje de error. + + function(message) { + // Show a helpful message + } + + +#### Descripción + + * **mensaje**: el mensaje es proporcionado por código nativo del dispositivo. *(String)* + +## cameraSuccess + +onSuccess función callback que proporciona los datos de imagen. + + function(imageData) { + // Do something with the image + } + + +#### Descripción + + * **imageData**: codificación en Base64 de los datos de imagen, *o* el archivo de imagen URI, dependiendo de `cameraOptions` en vigor. *(String)* + +#### Ejemplo + + // Show image + // + function cameraCallback(imageData) { + var image = document.getElementById('myImage'); + image.src = "data:image/jpeg;base64," + imageData; + } + + +## CameraPopoverHandle + +Un identificador para el cuadro de diálogo popover creado por`navigator.camera.getPicture`. + +#### Descripción + + * **setPosition**: Set the position of the popover. Takes the `CameraPopoverOptions` that specify the new position. + +#### Plataformas soportadas + +![](doc/img/android-fail.png) ![](doc/img/blackberry-fail.png) ![](doc/img/browser-fail.png) ![](doc/img/firefox-fail.png) ![](doc/img/fireos-fail.png) ![](doc/img/ios-success.png) ![](doc/img/windows-fail.png) ![](doc/img/wp8-fail.png) ![](doc/img/ubuntu-fail.png) + +#### Ejemplo + + var cameraPopoverHandle = navigator.camera.getPicture(onSuccess, onFail, + { destinationType: Camera.DestinationType.FILE_URI, + sourceType: Camera.PictureSourceType.PHOTOLIBRARY, + popoverOptions: new CameraPopoverOptions(300, 300, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY) + }); + + // Reposition the popover if the orientation changes. + window.onorientationchange = function() { + var cameraPopoverOptions = new CameraPopoverOptions(0, 0, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY); + cameraPopoverHandle.setPosition(cameraPopoverOptions); + } + + +## CameraPopoverOptions + +Sólo iOS parámetros que especifican la dirección ancla elemento ubicación y la flecha de la popover al seleccionar imágenes de biblioteca o álbum de un iPad. + + { x : 0, + y : 32, + width : 320, + height : 480, + arrowDir : Camera.PopoverArrowDirection.ARROW_ANY + }; + + +#### Descripción + + * **x**: coordenadas de píxeles del elemento de la pantalla en la que anclar el popover x. *(Número)* + + * **y**: coordenada píxeles del elemento de la pantalla en la que anclar el popover. *(Número)* + + * **anchura**: anchura, en píxeles, del elemento sobre el que anclar el popover pantalla. *(Número)* + + * **altura**: alto, en píxeles, del elemento sobre el que anclar el popover pantalla. *(Número)* + + * **arrowDir**: dirección de la flecha en el popover debe apuntar. Definido en `Camera.PopoverArrowDirection` *(número)* + + Camera.PopoverArrowDirection = { + ARROW_UP : 1, // matches iOS UIPopoverArrowDirection constants + ARROW_DOWN : 2, + ARROW_LEFT : 4, + ARROW_RIGHT : 8, + ARROW_ANY : 15 + }; + + +Tenga en cuenta que puede cambiar el tamaño de la popover para ajustar la dirección de la flecha y orientación de la pantalla. Asegúrese de que para tener en cuenta los cambios de orientación cuando se especifica la ubicación del elemento de anclaje. + +## Navigator.Camera.Cleanup + +Elimina intermedio fotos tomadas por la cámara de almacenamiento temporal. + + Navigator.Camera.cleanup (cameraSuccess, cameraError); + + +#### Descripción + +Elimina intermedio archivos de imagen que se mantienen en depósito temporal después de llamar `camera.getPicture` . Se aplica sólo cuando el valor de `Camera.sourceType` es igual a `Camera.PictureSourceType.CAMERA` y el `Camera.destinationType` es igual a`Camera.DestinationType.FILE_URI`. + +#### Plataformas soportadas + +![](doc/img/android-fail.png) ![](doc/img/blackberry-fail.png) ![](doc/img/browser-fail.png) ![](doc/img/firefox-fail.png) ![](doc/img/fireos-fail.png) ![](doc/img/ios-success.png) ![](doc/img/windows-fail.png) ![](doc/img/wp8-fail.png) ![](doc/img/ubuntu-fail.png) + +#### Ejemplo + + navigator.camera.cleanup(onSuccess, onFail); + + function onSuccess() { + console.log("Camera cleanup success.") + } + + function onFail(message) { + alert('Failed because: ' + message); + } \ No newline at end of file diff --git a/plugins/cordova-plugin-camera/doc/es/index.md b/plugins/cordova-plugin-camera/doc/es/index.md new file mode 100644 index 0000000..dfd0970 --- /dev/null +++ b/plugins/cordova-plugin-camera/doc/es/index.md @@ -0,0 +1,391 @@ + + +# cordova-plugin-camera + +Este plugin define un global `navigator.camera` objeto que proporciona una API para tomar fotografías y por elegir imágenes de biblioteca de imágenes del sistema. + +Aunque el objeto está unido al ámbito global `navigator` , no estará disponible hasta después de la `deviceready` evento. + + document.addEventListener ("deviceready", onDeviceReady, false); + function onDeviceReady() {console.log(navigator.camera)}; + + +## Instalación + + Cordova plugin agregar cordova-plugin-camera + + +## navigator.camera.getPicture + +Toma una foto con la cámara, o recupera una foto de Galería de imágenes del dispositivo. La imagen se pasa a la devolución de llamada de éxito como un codificado en base64 `String` , o como el URI para el archivo de imagen. El método se devuelve un `CameraPopoverHandle` objeto que puede utilizarse para volver a colocar el popover de selección de archivo. + + navigator.camera.getPicture (cameraSuccess, cameraError, cameraOptions); + + +### Descripción + +El `camera.getPicture` función abre la aplicación de cámara predeterminada del dispositivo que permite a los usuarios ajustar imágenes. Este comportamiento se produce de forma predeterminada, cuando `Camera.sourceType` es igual a `Camera.PictureSourceType.CAMERA` . Una vez que el usuario ajusta la foto, una aplicación de cámara se cierra y se restablecerá la aplicación. + +Si `Camera.sourceType` es `Camera.PictureSourceType.PHOTOLIBRARY` o `Camera.PictureSourceType.SAVEDPHOTOALBUM` , entonces una muestra de diálogo que permite a los usuarios seleccionar una imagen existente. El `camera.getPicture` función devuelve un `CameraPopoverHandle` objeto, que puede utilizarse para volver a colocar el diálogo de selección de imagen, por ejemplo, cuando cambia la orientación del dispositivo. + +El valor devuelto es enviado a la `cameraSuccess` función de callback, en uno de los formatos siguientes, dependiendo del objeto `cameraOptions` : + +* Una `String` que contiene la imagen codificada en base64. + +* Una `String` que representa la ubicación del archivo de imagen en almacenamiento local (por defecto). + +Puedes hacer lo que quieras con la imagen codificada o URI, por ejemplo: + +* Representar la imagen en una etiqueta de ``, como en el ejemplo siguiente + +* Guardar los datos localmente (`LocalStorage`, [Lawnchair][1], etc.) + +* Enviar los datos a un servidor remoto + + [1]: http://brianleroux.github.com/lawnchair/ + +**Nota**: resolución de la foto en los nuevos dispositivos es bastante bueno. Fotos seleccionadas de la Galería del dispositivo no son degradadas a una calidad más baja, incluso si un `quality` se especifica el parámetro. Para evitar problemas con la memoria común, establezca `Camera.destinationType` a `FILE_URI` en lugar de`DATA_URL`. + +### Plataformas soportadas + +* Amazon fire OS +* Android +* BlackBerry 10 +* Explorador +* Firefox OS +* iOS +* Tizen +* Windows Phone 7 y 8 +* Windows 8 + +### Preferencias (iOS) + +* **CameraUsesGeolocation** (booleano, el valor predeterminado de false). Para la captura de imágenes JPEG, establecido en true para obtener datos de geolocalización en la cabecera EXIF. Esto activará la solicitud de permisos de geolocalización si establecido en true. + + + + +### Amazon fuego OS rarezas + +Amazon fuego OS utiliza los intentos para poner en marcha la actividad de la cámara del dispositivo para capturar imágenes y en teléfonos con poca memoria, puede matar la actividad Cordova. En este escenario, la imagen no aparezca cuando se restaura la actividad cordova. + +### Rarezas Android + +Android utiliza los intentos para iniciar la actividad de la cámara del dispositivo para capturar imágenes, y en los teléfonos con poca memoria, puede matar la actividad Cordova. En este escenario, la imagen no aparezca cuando se restaura la actividad Cordova. + +### Navegador rarezas + +Sólo puede devolver fotos como imagen codificada en base64. + +### Firefox OS rarezas + +Cámara plugin actualmente se implementa mediante [Actividades Web][2]. + + [2]: https://hacks.mozilla.org/2013/01/introducing-web-activities/ + +### iOS rarezas + +Incluyendo un JavaScript `alert()` en cualquiera de la devolución de llamada funciones pueden causar problemas. Envuelva la alerta dentro de un `setTimeout()` para permitir que el selector de imagen iOS o popover cerrar completamente antes de la alerta se muestra: + + setTimeout(function() {/ / Haz lo tuyo aquí!}, 0); + + +### Windows Phone 7 rarezas + +Invocando la aplicación de cámara nativa mientras el dispositivo está conectado vía Zune no funciona y desencadena un callback de error. + +### Rarezas Tizen + +Tizen sólo es compatible con un `destinationType` de `Camera.DestinationType.FILE_URI` y un `sourceType` de`Camera.PictureSourceType.PHOTOLIBRARY`. + +### Ejemplo + +Tomar una foto y recuperarlo como una imagen codificada en base64: + + navigator.camera.getPicture (onSuccess, onFail, { quality: 50, + destinationType: Camera.DestinationType.DATA_URL + }); + + function onSuccess(imageData) {var imagen = document.getElementById('myImage'); + Image.src = "datos: image / jpeg; base64," + imageData;} + + function onFail(message) {alert (' falló porque: ' + mensaje);} + + +Tomar una foto y recuperar la ubicación del archivo de la imagen: + + navigator.camera.getPicture (onSuccess, onFail, { quality: 50, + destinationType: Camera.DestinationType.FILE_URI }); + + function onSuccess(imageURI) {var imagen = document.getElementById('myImage'); + Image.src = imageURI; + } function onFail(message) {alert (' falló porque: ' + mensaje);} + + +## CameraOptions + +Parámetros opcionales para personalizar la configuración de la cámara. + + {calidad: destinationType 75,: Camera.DestinationType.DATA_URL, sourceType: Camera.PictureSourceType.CAMERA, allowEdit: true, encodingType: Camera.EncodingType.JPEG, targetWidth: 100, targetHeight: 100, popoverOptions: CameraPopoverOptions, saveToPhotoAlbum: falsa}; + + +### Opciones + +* **calidad**: calidad de la imagen guardada, expresada en un rango de 0-100, donde 100 es típicamente resolución sin pérdida de compresión del archivo. El valor predeterminado es 50. *(Número)* (Tenga en cuenta que no está disponible información sobre resolución de la cámara). + +* **destinationType**: elegir el formato del valor devuelto. El valor predeterminado es FILE_URI. Definido en `navigator.camera.DestinationType` *(número)* + + Camera.DestinationType = { + DATA_URL : 0, // Return image as base64-encoded string + FILE_URI : 1, // Return image file URI + NATIVE_URI : 2 // Return image native URI (e.g., assets-library:// on iOS or content:// on Android) + }; + + +* **sourceType**: establecer el origen de la imagen. El valor predeterminado es cámara. Definido en `navigator.camera.PictureSourceType` *(número)* + + Camera.PictureSourceType = { + PHOTOLIBRARY : 0, + CAMERA : 1, + SAVEDPHOTOALBUM : 2 + }; + + +* **allowEdit**: permite edición sencilla de imagen antes de la selección. *(Booleano)* + +* **encodingType**: elegir la codificación del archivo de imagen devuelta. Por defecto es JPEG. Definido en `navigator.camera.EncodingType` *(número)* + + Camera.EncodingType = { + JPEG : 0, // Return JPEG encoded image + PNG : 1 // Return PNG encoded image + }; + + +* **targetWidth**: ancho en píxeles a escala de la imagen. Debe usarse con **targetHeight**. Proporción se mantiene constante. *(Número)* + +* **targetHeight**: altura en píxeles a escala de la imagen. Debe usarse con **targetWidth**. Proporción se mantiene constante. *(Número)* + +* **mediaType**: definir el tipo de medios para seleccionar. Sólo funciona cuando `PictureSourceType` es `PHOTOLIBRARY` o `SAVEDPHOTOALBUM` . Definido en `nagivator.camera.MediaType` *(número)* + + Camera.MediaType = { + PICTURE: 0, // allow selection of still pictures only. DE FORMA PREDETERMINADA. Will return format specified via DestinationType + VIDEO: 1, // allow selection of video only, WILL ALWAYS RETURN FILE_URI + ALLMEDIA : 2 // allow selection from all media types + }; + + +* **correctOrientation**: rotar la imagen para corregir la orientación del dispositivo durante la captura. *(Booleano)* + +* **saveToPhotoAlbum**: guardar la imagen en el álbum de fotos en el dispositivo después de su captura. *(Booleano)* + +* **popoverOptions**: opciones sólo iOS que especifican popover ubicación en iPad. Definido en`CameraPopoverOptions`. + +* **cameraDirection**: elegir la cámara para usar (o parte posterior-frontal). El valor predeterminado es atrás. Definido en `navigator.camera.Direction` *(número)* + + Camera.Direction = { + BACK : 0, // Use the back-facing camera + FRONT : 1 // Use the front-facing camera + }; + + +### Amazon fuego OS rarezas + +* Cualquier valor de `cameraDirection` da como resultado una foto orientada hacia atrás. + +* Ignora el `allowEdit` parámetro. + +* `Camera.PictureSourceType.PHOTOLIBRARY` y `Camera.PictureSourceType.SAVEDPHOTOALBUM` Mostrar el mismo álbum de fotos. + +### Rarezas Android + +* Cualquier valor de `cameraDirection` da como resultado una foto orientada hacia atrás. + +* Ignora el `allowEdit` parámetro. + +* `Camera.PictureSourceType.PHOTOLIBRARY` y `Camera.PictureSourceType.SAVEDPHOTOALBUM` Mostrar el mismo álbum de fotos. + +### BlackBerry 10 rarezas + +* Ignora el `quality` parámetro. + +* Ignora el `allowEdit` parámetro. + +* `Camera.MediaType`No se admite. + +* Ignora el `correctOrientation` parámetro. + +* Ignora el `cameraDirection` parámetro. + +### Firefox OS rarezas + +* Ignora el `quality` parámetro. + +* `Camera.DestinationType`se ignora y es igual a `1` (URI del archivo de imagen) + +* Ignora el `allowEdit` parámetro. + +* Ignora el `PictureSourceType` parámetro (el usuario lo elige en una ventana de diálogo) + +* Ignora el`encodingType` + +* Ignora el `targetWidth` y`targetHeight` + +* `Camera.MediaType`No se admite. + +* Ignora el `correctOrientation` parámetro. + +* Ignora el `cameraDirection` parámetro. + +### iOS rarezas + +* Establecer `quality` por debajo de 50 para evitar errores de memoria en algunos dispositivos. + +* Cuando se utiliza `destinationType.FILE_URI` , fotos se guardan en el directorio temporal de la aplicación. El contenido del directorio temporal de la aplicación se eliminará cuando finalice la aplicación. + +### Rarezas Tizen + +* opciones no compatibles + +* siempre devuelve un identificador URI de archivo + +### Windows Phone 7 y 8 rarezas + +* Ignora el `allowEdit` parámetro. + +* Ignora el `correctOrientation` parámetro. + +* Ignora el `cameraDirection` parámetro. + +* Ignora el `saveToPhotoAlbum` parámetro. IMPORTANTE: Todas las imágenes tomadas con la cámara wp7/8 cordova API siempre se copian en rollo de cámara del teléfono. Dependiendo de la configuración del usuario, esto podría significar también que la imagen es auto-subido a su OneDrive. Esto potencialmente podría significar que la imagen está disponible a una audiencia más amplia que su aplicación previsto. Si un bloqueador para su aplicación, usted necesitará aplicar el CameraCaptureTask como se documenta en msdn: también puede comentar o votar hasta el tema relacionado en el [issue tracker de][3] + +* Ignora el `mediaType` propiedad de `cameraOptions` como el SDK de Windows Phone no proporciona una manera para elegir vídeos fototeca. + + [3]: https://issues.apache.org/jira/browse/CB-2083 + +## CameraError + +onError función callback que proporciona un mensaje de error. + + function(Message) {/ / Mostrar un mensaje útil} + + +### Parámetros + +* **mensaje**: el mensaje es proporcionado por código nativo del dispositivo. *(String)* + +## cameraSuccess + +onSuccess función callback que proporciona los datos de imagen. + + function(ImageData) {/ / hacer algo con la imagen} + + +### Parámetros + +* **imageData**: codificación en Base64 de los datos de imagen, *o* el archivo de imagen URI, dependiendo de `cameraOptions` en vigor. *(String)* + +### Ejemplo + + Mostrar imagen / / function cameraCallback(imageData) {var imagen = document.getElementById('myImage'); + Image.src = "datos: image / jpeg; base64," + imageData;} + + +## CameraPopoverHandle + +Un identificador para el cuadro de diálogo popover creado por`navigator.camera.getPicture`. + +### Métodos + +* **setPosition**: establecer la posición de la popover. + +### Plataformas soportadas + +* iOS + +### setPosition + +Establecer la posición de la popover. + +**Parámetros**: + +* `cameraPopoverOptions`: el `CameraPopoverOptions` que especifican la nueva posición + +### Ejemplo + + var cameraPopoverHandle = navigator.camera.getPicture (onSuccess, onFail, {destinationType: Camera.DestinationType.FILE_URI, sourceType: Camera.PictureSourceType.PHOTOLIBRARY, popoverOptions: CameraPopoverOptions nuevo (300, 300, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY)}); + + Vuelva a colocar el popover si cambia la orientación. + Window.onorientationchange = function() {var cameraPopoverOptions = new CameraPopoverOptions (0, 0, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY); + cameraPopoverHandle.setPosition(cameraPopoverOptions); + } + + +## CameraPopoverOptions + +Sólo iOS parámetros que especifican la dirección ancla elemento ubicación y la flecha de la popover al seleccionar imágenes de biblioteca o álbum de un iPad. + + {x: 0, y: 32, ancho: 320, altura: 480, arrowDir: Camera.PopoverArrowDirection.ARROW_ANY}; + + +### CameraPopoverOptions + +* **x**: coordenadas de píxeles del elemento de la pantalla en la que anclar el popover x. *(Número)* + +* **y**: coordenada píxeles del elemento de la pantalla en la que anclar el popover. *(Número)* + +* **anchura**: anchura, en píxeles, del elemento sobre el que anclar el popover pantalla. *(Número)* + +* **altura**: alto, en píxeles, del elemento sobre el que anclar el popover pantalla. *(Número)* + +* **arrowDir**: dirección de la flecha en el popover debe apuntar. Definido en `Camera.PopoverArrowDirection` *(número)* + + Camera.PopoverArrowDirection = { + ARROW_UP : 1, // matches iOS UIPopoverArrowDirection constants + ARROW_DOWN : 2, + ARROW_LEFT : 4, + ARROW_RIGHT : 8, + ARROW_ANY : 15 + }; + + +Tenga en cuenta que puede cambiar el tamaño de la popover para ajustar la dirección de la flecha y orientación de la pantalla. Asegúrese de que para tener en cuenta los cambios de orientación cuando se especifica la ubicación del elemento de anclaje. + +## Navigator.Camera.Cleanup + +Elimina intermedio fotos tomadas por la cámara de almacenamiento temporal. + + Navigator.Camera.cleanup (cameraSuccess, cameraError); + + +### Descripción + +Elimina intermedio archivos de imagen que se mantienen en depósito temporal después de llamar `camera.getPicture` . Se aplica sólo cuando el valor de `Camera.sourceType` es igual a `Camera.PictureSourceType.CAMERA` y el `Camera.destinationType` es igual a`Camera.DestinationType.FILE_URI`. + +### Plataformas soportadas + +* iOS + +### Ejemplo + + Navigator.Camera.cleanup (onSuccess, onFail); + + function onSuccess() {console.log ("cámara limpieza éxito.")} + + function onFail(message) {alert (' falló porque: ' + mensaje);} diff --git a/plugins/cordova-plugin-camera/doc/fr/README.md b/plugins/cordova-plugin-camera/doc/fr/README.md new file mode 100644 index 0000000..091dd23 --- /dev/null +++ b/plugins/cordova-plugin-camera/doc/fr/README.md @@ -0,0 +1,378 @@ + + +# cordova-plugin-camera + +[![Build Status](https://travis-ci.org/apache/cordova-plugin-camera.svg)](https://travis-ci.org/apache/cordova-plugin-camera) + +Ce plugin définit un global `navigator.camera` objet qui fournit une API pour la prise de photos et de choisir des images de la bibliothèque d'images du système. + +Bien que l'objet est attaché à la portée globale `navigator` , il n'est pas disponible jusqu'après la `deviceready` événement. + + document.addEventListener (« deviceready », onDeviceReady, false) ; + function onDeviceReady() {console.log(navigator.camera);} + + +## Installation + + cordova plugin add cordova-plugin-camera + + +## API + + * Appareil photo + * navigator.camera.getPicture(success, fail, options) + * CameraOptions + * CameraPopoverHandle + * CameraPopoverOptions + * Navigator.Camera.Cleanup + +## navigator.camera.getPicture + +Prend une photo à l'aide de la caméra, ou récupère une photo de la Galerie d'images de l'appareil. L'image est passé au rappel succès comme un codage base64 `String` , ou comme l'URI du fichier de l'image. La méthode elle-même retourne un `CameraPopoverHandle` objet qui permet de repositionner le kangourou de sélection de fichier. + + navigator.camera.getPicture(cameraSuccess, cameraError, cameraOptions); + + +#### Description + +Le `camera.getPicture` fonction ouvre l'application de caméra par défaut de l'appareil qui permet aux utilisateurs de prendre des photos. Ce comportement se produit par défaut, lorsque `Camera.sourceType` est égal à `Camera.PictureSourceType.CAMERA` . Une fois que l'utilisateur s'enclenche la photo, l'application appareil photo se ferme et l'application est restaurée. + +Si `Camera.sourceType` est `Camera.PictureSourceType.PHOTOLIBRARY` ou `Camera.PictureSourceType.SAVEDPHOTOALBUM` , puis un dialogue affiche qui permet aux utilisateurs de sélectionner une image existante. Le `camera.getPicture` retourne un `CameraPopoverHandle` objet, ce qui permet de repositionner le dialogue de sélection d'image, par exemple, lorsque l'orientation de l'appareil change. + +La valeur de retour est envoyée à la `cameraSuccess` la fonction de rappel, dans l'un des formats suivants, selon les `cameraOptions` : + + * A `String` contenant l'image photo codée en base64. + + * A `String` qui représente l'emplacement du fichier image sur le stockage local (par défaut). + +Vous pouvez faire ce que vous voulez avec l'image codée ou URI, par exemple : + + * Afficher l'image dans un `` tag, comme dans l'exemple ci-dessous + + * Enregistrer les données localement ( `LocalStorage` , [poids](http://brianleroux.github.com/lawnchair/), etc..) + + * Publier les données sur un serveur distant + +**NOTE**: la résolution de Photo sur les nouveaux appareils est assez bonne. Photos sélectionnées de la Galerie de l'appareil ne sont pas réduites à une baisse de la qualité, même si un `quality` paramètre est spécifié. Pour éviter les problèmes de mémoire commun, définissez `Camera.destinationType` à `FILE_URI` au lieu de`DATA_URL`. + +#### Plates-formes supportées + +![](doc/img/android-success.png) ![](doc/img/blackberry-success.png) ![](doc/img/browser-success.png) ![](doc/img/firefox-success.png) ![](doc/img/fireos-success.png) ![](doc/img/ios-success.png) ![](doc/img/windows-success.png) ![](doc/img/wp8-success.png) ![](doc/img/ubuntu-success.png) + +#### Exemple + +Prendre une photo, puis extrayez-la comme une image codée en base64 : + + navigator.camera.getPicture (onSuccess, onFail, { quality: 50, + destinationType: Camera.DestinationType.DATA_URL + }) ; + + function onSuccess(imageData) {var image = document.getElementById('myImage') ; + image.src = "données : image / jpeg ; base64," + imageData;} + + function onFail(message) {alert (' a échoué car: "+ message);} + + +Prendre une photo et récupérer l'emplacement du fichier de l'image : + + navigator.camera.getPicture (onSuccess, onFail, { quality: 50, + destinationType: Camera.DestinationType.FILE_URI }) ; + + function onSuccess(imageURI) {var image = document.getElementById('myImage') ; + image.SRC = imageURI ; + } function onFail(message) {alert (' a échoué car: "+ message);} + + +#### Préférences (iOS) + + * **CameraUsesGeolocation** (boolean, par défaut, false). Pour capturer des images JPEG, true pour obtenir des données de géolocalisation dans l'en-tête EXIF. Cela va déclencher une demande d'autorisations de géolocalisation si défini à true. + + + + +#### Amazon Fire OS Quirks + +Amazon Fire OS utilise des intentions pour lancer l'activité de l'appareil photo sur l'appareil pour capturer des images et sur les téléphones avec peu de mémoire, l'activité de Cordova peut être tuée. Dans ce scénario, l'image peut ne pas apparaître lorsque l'activité de cordova est restaurée. + +#### Quirks Android + +Android utilise des intentions pour lancer l'activité de l'appareil photo sur l'appareil pour capturer des images et sur les téléphones avec peu de mémoire, l'activité de Cordova peut être tuée. Dans ce scénario, l'image peut ne pas apparaître lorsque l'activité de Cordova est restaurée. + +#### Bizarreries navigateur + +Peut retourner uniquement les photos comme image codée en base64. + +#### Firefox OS Quirks + +Appareil photo plugin est actuellement mis en œuvre à l'aide [d'Activités sur le Web](https://hacks.mozilla.org/2013/01/introducing-web-activities/). + +#### Notes au sujet d'iOS + +Y compris un JavaScript `alert()` dans les deux le rappel fonctions peuvent causer des problèmes. Envelopper l'alerte dans un `setTimeout()` pour permettre le sélecteur d'image iOS ou kangourou pour fermer entièrement avant que l'alerte s'affiche : + + setTimeout(function() {/ / faire votre truc ici!}, 0) ; + + +#### Windows Phone 7 Quirks + +Invoquant l'application native caméra alors que l'appareil est connecté via Zune ne fonctionne pas et déclenche un rappel de l'erreur. + +#### Bizarreries de paciarelli + +Paciarelli prend uniquement en charge un `destinationType` de `Camera.DestinationType.FILE_URI` et un `sourceType` de`Camera.PictureSourceType.PHOTOLIBRARY`. + +## CameraOptions + +Paramètres optionnels pour personnaliser les réglages de l'appareil. + + {qualité : destinationType 75,: Camera.DestinationType.DATA_URL, TypeSource : Camera.PictureSourceType.CAMERA, allowEdit : encodingType vrai,: Camera.EncodingType.JPEG, targetWidth : 100, targetHeight : 100, popoverOptions : CameraPopoverOptions, saveToPhotoAlbum : false} ; + + + * **qualité**: qualité de l'image enregistrée, exprimée en une gamme de 0 à 100, 100 étant généralement pleine résolution sans perte de compression de fichiers. La valeur par défaut est 50. *(Nombre)* (Notez que les informations sur la résolution de la caméra sont indisponibles). + + * **destinationType**: choisissez le format de la valeur de retour. La valeur par défaut est FILE_URI. Définies dans `navigator.camera.DestinationType` *(nombre)* + + Camera.DestinationType = { + DATA_URL : 0, // Return image as base64-encoded string + FILE_URI : 1, // Return image file URI + NATIVE_URI : 2 // Return image native URI (e.g., assets-library:// on iOS or content:// on Android) + }; + + + * **sourceType**: définissez la source de l'image. La valeur par défaut est la caméra. Définies dans `navigator.camera.PictureSourceType` *(nombre)* + + Camera.PictureSourceType = { + PHOTOLIBRARY : 0, + CAMERA : 1, + SAVEDPHOTOALBUM : 2 + }; + + + * **allowEdit**: permettre un montage simple d'image avant la sélection. *(Booléen)* + + * **encodingType**: choisir le fichier image retournée de codage. Valeur par défaut est JPEG. Définies dans `navigator.camera.EncodingType` *(nombre)* + + Camera.EncodingType = { + JPEG : 0, // Return JPEG encoded image + PNG : 1 // Return PNG encoded image + }; + + + * **targetWidth**: largeur en pixels de l'image de l'échelle. Doit être utilisé avec **targetHeight**. Aspect ratio reste constant. *(Nombre)* + + * **targetHeight**: hauteur en pixels de l'image de l'échelle. Doit être utilisé avec **targetWidth**. Aspect ratio reste constant. *(Nombre)* + + * **mediaType**: définir le type de média pour choisir de. Ne fonctionne que quand `PictureSourceType` est `PHOTOLIBRARY` ou `SAVEDPHOTOALBUM` . Définies dans `nagivator.camera.MediaType` *(nombre)* + + Camera.MediaType = { + PICTURE: 0, // allow selection of still pictures only. PAR DÉFAUT. Will return format specified via DestinationType + VIDEO: 1, // allow selection of video only, WILL ALWAYS RETURN FILE_URI + ALLMEDIA : 2 // allow selection from all media types + }; + + + * **correctOrientation**: faire pivoter l'image afin de corriger l'orientation de l'appareil lors de la capture. *(Booléen)* + + * **saveToPhotoAlbum**: enregistrer l'image sur l'album photo sur l'appareil après la capture. *(Booléen)* + + * **popoverOptions**: iOS uniquement des options qui spécifient l'emplacement de kangourou dans iPad. Défini dans`CameraPopoverOptions`. + + * **cameraDirection**: choisissez la caméra à utiliser (ou dos-face). La valeur par défaut est de retour. Définies dans `navigator.camera.Direction` *(nombre)* + + Camera.Direction = { + BACK : 0, // Use the back-facing camera + FRONT : 1 // Use the front-facing camera + }; + + +#### Amazon Fire OS Quirks + + * Tout `cameraDirection` résultats dans le back-face photo de valeur. + + * Ignore la `allowEdit` paramètre. + + * `Camera.PictureSourceType.PHOTOLIBRARY`et `Camera.PictureSourceType.SAVEDPHOTOALBUM` les deux affichent le même album photo. + +#### Quirks Android + + * Tout `cameraDirection` résultats dans le back-face photo de valeur. + + * Android utilise également l'activité de récolte pour allowEdit, même si la récolte doit travailler et transmet en réalité l'image recadrée à Cordoue, le seul que les œuvres sont toujours celui livré avec l'application Google Plus Photos. Autres cultures peuvent ne pas fonctionner. + + * `Camera.PictureSourceType.PHOTOLIBRARY`et `Camera.PictureSourceType.SAVEDPHOTOALBUM` les deux affichent le même album photo. + +#### BlackBerry 10 Quirks + + * Ignore la `quality` paramètre. + + * Ignore la `allowEdit` paramètre. + + * `Camera.MediaType`n'est pas pris en charge. + + * Ignore la `correctOrientation` paramètre. + + * Ignore la `cameraDirection` paramètre. + +#### Firefox OS Quirks + + * Ignore la `quality` paramètre. + + * `Camera.DestinationType`est ignorée et est égal à `1` (URI du fichier image) + + * Ignore la `allowEdit` paramètre. + + * Ignore la `PictureSourceType` paramètre (utilisateur il choisit dans une fenêtre de dialogue) + + * Ignore le`encodingType` + + * Ignore la `targetWidth` et`targetHeight` + + * `Camera.MediaType`n'est pas pris en charge. + + * Ignore la `correctOrientation` paramètre. + + * Ignore la `cameraDirection` paramètre. + +#### Notes au sujet d'iOS + + * La valeur `quality` inférieur à 50 pour éviter les erreurs de mémoire sur certains appareils. + + * Lorsque vous utilisez `destinationType.FILE_URI` , les photos sont sauvegardées dans le répertoire temporaire de l'application. Le contenu du répertoire temporaire de l'application est supprimé lorsque l'application se termine. + +#### Bizarreries de paciarelli + + * options non prises en charge + + * retourne toujours un URI de fichier + +#### Notes au sujet de Windows Phone 7 et 8 + + * Ignore la `allowEdit` paramètre. + + * Ignore la `correctOrientation` paramètre. + + * Ignore la `cameraDirection` paramètre. + + * Ignore la `saveToPhotoAlbum` paramètre. IMPORTANT : Toutes les images prises avec la caméra de cordova wp7/8 API sont toujours copiés au rôle d'appareil photo du téléphone. Selon les paramètres de l'utilisateur, cela pourrait également signifier que l'image est auto-téléchargées à leur OneDrive. Potentiellement, cela pourrait signifier que l'image est disponible à un public plus large que votre application destinée. Si ce un bloqueur pour votre application, vous devrez implémenter le CameraCaptureTask tel que documenté sur msdn : vous pouvez aussi commenter ou haut-vote la question connexe dans le [gestionnaire d'incidents](https://issues.apache.org/jira/browse/CB-2083) + + * Ignore la `mediaType` propriété de `cameraOptions` comme le kit de développement Windows Phone ne fournit pas un moyen de choisir les vidéos de PHOTOLIBRARY. + +## CameraError + +fonction de rappel onError qui fournit un message d'erreur. + + function(message) {/ / afficher un message utile} + + +#### Description + + * **message**: le message est fourni par du code natif de l'appareil. *(String)* + +## cameraSuccess + +fonction de rappel onSuccess qui fournit les données d'image. + + function(ImageData) {/ / faire quelque chose avec l'image} + + +#### Description + + * **imageData**: codage Base64 de l'image, *ou* le fichier image URI, selon `cameraOptions` en vigueur. *(String)* + +#### Exemple + + Afficher image / / function cameraCallback(imageData) {var image = document.getElementById('myImage') ; + image.src = "données : image / jpeg ; base64," + imageData;} + + +## CameraPopoverHandle + +Un handle vers la boîte de dialogue de kangourou créé par`navigator.camera.getPicture`. + +#### Description + + * **setPosition**: Set the position of the popover. Takes the `CameraPopoverOptions` that specify the new position. + +#### Plates-formes supportées + +![](doc/img/android-fail.png) ![](doc/img/blackberry-fail.png) ![](doc/img/browser-fail.png) ![](doc/img/firefox-fail.png) ![](doc/img/fireos-fail.png) ![](doc/img/ios-success.png) ![](doc/img/windows-fail.png) ![](doc/img/wp8-fail.png) ![](doc/img/ubuntu-fail.png) + +#### Exemple + + var cameraPopoverHandle = navigator.camera.getPicture (onSuccess, onFail, {destinationType : Camera.DestinationType.FILE_URI, TypeSource : Camera.PictureSourceType.PHOTOLIBRARY, popoverOptions : nouvelle CameraPopoverOptions (300, 300, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY)}) ; + + Repositionner le kangourou si l'orientation change. + Window.onorientationchange = function() {var cameraPopoverOptions = new CameraPopoverOptions (0, 0, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY) ; + cameraPopoverHandle.setPosition(cameraPopoverOptions) ; + } + + +## CameraPopoverOptions + +iOS uniquement les paramètres qui spécifient la direction ancre élément emplacement et de la flèche de la kangourou lors de la sélection des images de la bibliothèque de l'iPad ou l'album. + + {x: 0, y: 32, largeur : 320, hauteur : 480, arrowDir : Camera.PopoverArrowDirection.ARROW_ANY} ; + + +#### Description + + * **x**: coordonnée de pixel de l'élément de l'écran sur lequel ancrer le kangourou x. *(Nombre)* + + * **y**: coordonnée de y pixels de l'élément de l'écran sur lequel ancrer le kangourou. *(Nombre)* + + * **largeur**: largeur, en pixels, de l'élément de l'écran sur lequel ancrer le kangourou. *(Nombre)* + + * **hauteur**: hauteur, en pixels, de l'élément de l'écran sur lequel ancrer le kangourou. *(Nombre)* + + * **arrowDir**: Direction de la flèche sur le kangourou doit pointer. Définies dans `Camera.PopoverArrowDirection` *(nombre)* + + Camera.PopoverArrowDirection = { + ARROW_UP : 1, // matches iOS UIPopoverArrowDirection constants + ARROW_DOWN : 2, + ARROW_LEFT : 4, + ARROW_RIGHT : 8, + ARROW_ANY : 15 + }; + + +Notez que la taille de la kangourou peut changer pour s'adapter à la direction de la flèche et l'orientation de l'écran. Assurez-vous que tenir compte des changements d'orientation lors de la spécification de l'emplacement d'élément d'ancrage. + +## Navigator.Camera.Cleanup + +Supprime les intermédiaires photos prises par la caméra de stockage temporaire. + + Navigator.Camera.Cleanup (cameraSuccess, cameraError) ; + + +#### Description + +Supprime les intermédiaires les fichiers image qui sont gardées en dépôt temporaire après avoir appelé `camera.getPicture` . S'applique uniquement lorsque la valeur de `Camera.sourceType` est égale à `Camera.PictureSourceType.CAMERA` et le `Camera.destinationType` est égal à`Camera.DestinationType.FILE_URI`. + +#### Plates-formes supportées + +![](doc/img/android-fail.png) ![](doc/img/blackberry-fail.png) ![](doc/img/browser-fail.png) ![](doc/img/firefox-fail.png) ![](doc/img/fireos-fail.png) ![](doc/img/ios-success.png) ![](doc/img/windows-fail.png) ![](doc/img/wp8-fail.png) ![](doc/img/ubuntu-fail.png) + +#### Exemple + + Navigator.Camera.Cleanup (onSuccess, onFail) ; + + fonction onSuccess() {console.log ("succès de caméra nettoyage.")} + + function onFail(message) {alert (' a échoué car: "+ message);} \ No newline at end of file diff --git a/plugins/cordova-plugin-camera/doc/fr/index.md b/plugins/cordova-plugin-camera/doc/fr/index.md new file mode 100644 index 0000000..ec005f0 --- /dev/null +++ b/plugins/cordova-plugin-camera/doc/fr/index.md @@ -0,0 +1,391 @@ + + +# cordova-plugin-camera + +Ce plugin définit un global `navigator.camera` objet qui fournit une API pour la prise de photos et de choisir des images de la bibliothèque d'images du système. + +Bien que l'objet est attaché à la portée globale `navigator` , il n'est pas disponible jusqu'après la `deviceready` événement. + + document.addEventListener (« deviceready », onDeviceReady, false) ; + function onDeviceReady() {console.log(navigator.camera);} + + +## Installation + + Cordova plugin ajouter cordova-plugin-camera + + +## navigator.camera.getPicture + +Prend une photo à l'aide de la caméra, ou récupère une photo de la Galerie d'images de l'appareil. L'image est passé au rappel succès comme un codage base64 `String` , ou comme l'URI du fichier de l'image. La méthode elle-même retourne un `CameraPopoverHandle` objet qui permet de repositionner le kangourou de sélection de fichier. + + navigator.camera.getPicture (cameraSuccess, cameraError, cameraOptions) ; + + +### Description + +Le `camera.getPicture` fonction ouvre l'application de caméra par défaut de l'appareil qui permet aux utilisateurs de prendre des photos. Ce comportement se produit par défaut, lorsque `Camera.sourceType` est égal à `Camera.PictureSourceType.CAMERA` . Une fois que l'utilisateur s'enclenche la photo, l'application appareil photo se ferme et l'application est restaurée. + +Si `Camera.sourceType` est `Camera.PictureSourceType.PHOTOLIBRARY` ou `Camera.PictureSourceType.SAVEDPHOTOALBUM` , puis un dialogue affiche qui permet aux utilisateurs de sélectionner une image existante. Le `camera.getPicture` retourne un `CameraPopoverHandle` objet, ce qui permet de repositionner le dialogue de sélection d'image, par exemple, lorsque l'orientation de l'appareil change. + +La valeur de retour est envoyée à la `cameraSuccess` la fonction de rappel, dans l'un des formats suivants, selon les `cameraOptions` : + +* A `String` contenant l'image photo codée en base64. + +* A `String` qui représente l'emplacement du fichier image sur le stockage local (par défaut). + +Vous pouvez faire ce que vous voulez avec l'image codée ou URI, par exemple : + +* Afficher l'image dans un `` tag, comme dans l'exemple ci-dessous + +* Enregistrer les données localement ( `LocalStorage` , [poids][1], etc..) + +* Publier les données sur un serveur distant + + [1]: http://brianleroux.github.com/lawnchair/ + +**NOTE**: la résolution de Photo sur les nouveaux appareils est assez bonne. Photos sélectionnées de la Galerie de l'appareil ne sont pas réduites à une baisse de la qualité, même si un `quality` paramètre est spécifié. Pour éviter les problèmes de mémoire commun, définissez `Camera.destinationType` à `FILE_URI` au lieu de`DATA_URL`. + +### Plates-formes prises en charge + +* Amazon Fire OS +* Android +* BlackBerry 10 +* Navigateur +* Firefox OS +* iOS +* Paciarelli +* Windows Phone 7 et 8 +* Windows 8 + +### Préférences (iOS) + +* **CameraUsesGeolocation** (boolean, par défaut, false). Pour capturer des images JPEG, true pour obtenir des données de géolocalisation dans l'en-tête EXIF. Cela va déclencher une demande d'autorisations de géolocalisation si défini à true. + + + + +### Amazon Fire OS Quirks + +Amazon Fire OS utilise des intentions pour lancer l'activité de l'appareil photo sur l'appareil pour capturer des images et sur les téléphones avec peu de mémoire, l'activité de Cordova peut être tuée. Dans ce scénario, l'image peut ne pas apparaître lorsque l'activité de cordova est restaurée. + +### Quirks Android + +Android utilise des intentions pour lancer l'activité de l'appareil photo sur l'appareil pour capturer des images et sur les téléphones avec peu de mémoire, l'activité de Cordova peut être tuée. Dans ce scénario, l'image peut ne pas apparaître lorsque l'activité de Cordova est restaurée. + +### Bizarreries navigateur + +Peut retourner uniquement les photos comme image codée en base64. + +### Firefox OS Quirks + +Appareil photo plugin est actuellement mis en œuvre à l'aide [d'Activités sur le Web][2]. + + [2]: https://hacks.mozilla.org/2013/01/introducing-web-activities/ + +### iOS Quirks + +Y compris un JavaScript `alert()` dans les deux le rappel fonctions peuvent causer des problèmes. Envelopper l'alerte dans un `setTimeout()` pour permettre le sélecteur d'image iOS ou kangourou pour fermer entièrement avant que l'alerte s'affiche : + + setTimeout(function() {/ / faire votre truc ici!}, 0) ; + + +### Windows Phone 7 Quirks + +Invoquant l'application native caméra alors que l'appareil est connecté via Zune ne fonctionne pas et déclenche un rappel de l'erreur. + +### Bizarreries de paciarelli + +Paciarelli prend uniquement en charge un `destinationType` de `Camera.DestinationType.FILE_URI` et un `sourceType` de`Camera.PictureSourceType.PHOTOLIBRARY`. + +### Exemple + +Prendre une photo, puis extrayez-la comme une image codée en base64 : + + navigator.camera.getPicture (onSuccess, onFail, { quality: 50, + destinationType: Camera.DestinationType.DATA_URL + }) ; + + function onSuccess(imageData) {var image = document.getElementById('myImage') ; + image.src = "données : image / jpeg ; base64," + imageData;} + + function onFail(message) {alert (' a échoué car: "+ message);} + + +Prendre une photo et récupérer l'emplacement du fichier de l'image : + + navigator.camera.getPicture (onSuccess, onFail, { quality: 50, + destinationType: Camera.DestinationType.FILE_URI }) ; + + function onSuccess(imageURI) {var image = document.getElementById('myImage') ; + image.SRC = imageURI ; + } function onFail(message) {alert (' a échoué car: "+ message);} + + +## CameraOptions + +Paramètres optionnels pour personnaliser les réglages de l'appareil. + + {qualité : destinationType 75,: Camera.DestinationType.DATA_URL, TypeSource : Camera.PictureSourceType.CAMERA, allowEdit : encodingType vrai,: Camera.EncodingType.JPEG, targetWidth : 100, targetHeight : 100, popoverOptions : CameraPopoverOptions, saveToPhotoAlbum : false} ; + + +### Options + +* **qualité**: qualité de l'image enregistrée, exprimée en une gamme de 0 à 100, 100 étant généralement pleine résolution sans perte de compression de fichiers. La valeur par défaut est 50. *(Nombre)* (Notez que les informations sur la résolution de la caméra sont indisponibles). + +* **destinationType**: choisissez le format de la valeur de retour. La valeur par défaut est FILE_URI. Définies dans `navigator.camera.DestinationType` *(nombre)* + + Camera.DestinationType = { + DATA_URL : 0, // Return image as base64-encoded string + FILE_URI : 1, // Return image file URI + NATIVE_URI : 2 // Return image native URI (e.g., assets-library:// on iOS or content:// on Android) + }; + + +* **sourceType**: définissez la source de l'image. La valeur par défaut est la caméra. Définies dans `navigator.camera.PictureSourceType` *(nombre)* + + Camera.PictureSourceType = { + PHOTOLIBRARY : 0, + CAMERA : 1, + SAVEDPHOTOALBUM : 2 + }; + + +* **allowEdit**: permettre un montage simple d'image avant la sélection. *(Booléen)* + +* **encodingType**: choisir le fichier image retournée de codage. Valeur par défaut est JPEG. Définies dans `navigator.camera.EncodingType` *(nombre)* + + Camera.EncodingType = { + JPEG : 0, // Return JPEG encoded image + PNG : 1 // Return PNG encoded image + }; + + +* **targetWidth**: largeur en pixels de l'image de l'échelle. Doit être utilisé avec **targetHeight**. Aspect ratio reste constant. *(Nombre)* + +* **targetHeight**: hauteur en pixels de l'image de l'échelle. Doit être utilisé avec **targetWidth**. Aspect ratio reste constant. *(Nombre)* + +* **mediaType**: définir le type de média pour choisir de. Ne fonctionne que quand `PictureSourceType` est `PHOTOLIBRARY` ou `SAVEDPHOTOALBUM` . Définies dans `nagivator.camera.MediaType` *(nombre)* + + Camera.MediaType = { + PICTURE: 0, // allow selection of still pictures only. PAR DÉFAUT. Will return format specified via DestinationType + VIDEO: 1, // allow selection of video only, WILL ALWAYS RETURN FILE_URI + ALLMEDIA : 2 // allow selection from all media types + }; + + +* **correctOrientation**: faire pivoter l'image afin de corriger l'orientation de l'appareil lors de la capture. *(Booléen)* + +* **saveToPhotoAlbum**: enregistrer l'image sur l'album photo sur l'appareil après la capture. *(Booléen)* + +* **popoverOptions**: iOS uniquement des options qui spécifient l'emplacement de kangourou dans iPad. Défini dans`CameraPopoverOptions`. + +* **cameraDirection**: choisissez la caméra à utiliser (ou dos-face). La valeur par défaut est de retour. Définies dans `navigator.camera.Direction` *(nombre)* + + Camera.Direction = { + BACK : 0, // Use the back-facing camera + FRONT : 1 // Use the front-facing camera + }; + + +### Amazon Fire OS Quirks + +* Tout `cameraDirection` résultats dans le back-face photo de valeur. + +* Ignore la `allowEdit` paramètre. + +* `Camera.PictureSourceType.PHOTOLIBRARY`et `Camera.PictureSourceType.SAVEDPHOTOALBUM` les deux affichent le même album photo. + +### Quirks Android + +* Tout `cameraDirection` résultats dans le back-face photo de valeur. + +* Ignore la `allowEdit` paramètre. + +* `Camera.PictureSourceType.PHOTOLIBRARY`et `Camera.PictureSourceType.SAVEDPHOTOALBUM` les deux affichent le même album photo. + +### BlackBerry 10 Quirks + +* Ignore la `quality` paramètre. + +* Ignore la `allowEdit` paramètre. + +* `Camera.MediaType`n'est pas pris en charge. + +* Ignore la `correctOrientation` paramètre. + +* Ignore la `cameraDirection` paramètre. + +### Firefox OS Quirks + +* Ignore la `quality` paramètre. + +* `Camera.DestinationType`est ignorée et est égal à `1` (URI du fichier image) + +* Ignore la `allowEdit` paramètre. + +* Ignore la `PictureSourceType` paramètre (utilisateur il choisit dans une fenêtre de dialogue) + +* Ignore le`encodingType` + +* Ignore la `targetWidth` et`targetHeight` + +* `Camera.MediaType`n'est pas pris en charge. + +* Ignore la `correctOrientation` paramètre. + +* Ignore la `cameraDirection` paramètre. + +### iOS Quirks + +* La valeur `quality` inférieur à 50 pour éviter les erreurs de mémoire sur certains appareils. + +* Lorsque vous utilisez `destinationType.FILE_URI` , les photos sont sauvegardées dans le répertoire temporaire de l'application. Le contenu du répertoire temporaire de l'application est supprimé lorsque l'application se termine. + +### Bizarreries de paciarelli + +* options non prises en charge + +* retourne toujours un URI de fichier + +### Windows Phone 7 et 8 Quirks + +* Ignore la `allowEdit` paramètre. + +* Ignore la `correctOrientation` paramètre. + +* Ignore la `cameraDirection` paramètre. + +* Ignore la `saveToPhotoAlbum` paramètre. IMPORTANT : Toutes les images prises avec la caméra de cordova wp7/8 API sont toujours copiés au rôle d'appareil photo du téléphone. Selon les paramètres de l'utilisateur, cela pourrait également signifier que l'image est auto-téléchargées à leur OneDrive. Potentiellement, cela pourrait signifier que l'image est disponible à un public plus large que votre application destinée. Si ce un bloqueur pour votre application, vous devrez implémenter le CameraCaptureTask tel que documenté sur msdn : vous pouvez aussi commenter ou haut-vote la question connexe dans le [gestionnaire d'incidents][3] + +* Ignore la `mediaType` propriété de `cameraOptions` comme le kit de développement Windows Phone ne fournit pas un moyen de choisir les vidéos de PHOTOLIBRARY. + + [3]: https://issues.apache.org/jira/browse/CB-2083 + +## CameraError + +fonction de rappel onError qui fournit un message d'erreur. + + function(message) {/ / afficher un message utile} + + +### Paramètres + +* **message**: le message est fourni par du code natif de l'appareil. *(String)* + +## cameraSuccess + +fonction de rappel onSuccess qui fournit les données d'image. + + function(ImageData) {/ / faire quelque chose avec l'image} + + +### Paramètres + +* **imageData**: codage Base64 de l'image, *ou* le fichier image URI, selon `cameraOptions` en vigueur. *(String)* + +### Exemple + + Afficher image / / function cameraCallback(imageData) {var image = document.getElementById('myImage') ; + image.src = "données : image / jpeg ; base64," + imageData;} + + +## CameraPopoverHandle + +Un handle vers la boîte de dialogue de kangourou créé par`navigator.camera.getPicture`. + +### Méthodes + +* **setPosition**: définir la position de la kangourou. + +### Plates-formes prises en charge + +* iOS + +### setPosition + +Définir la position de la kangourou. + +**Paramètres**: + +* `cameraPopoverOptions`: la `CameraPopoverOptions` qui spécifie la nouvelle position + +### Exemple + + var cameraPopoverHandle = navigator.camera.getPicture (onSuccess, onFail, {destinationType : Camera.DestinationType.FILE_URI, TypeSource : Camera.PictureSourceType.PHOTOLIBRARY, popoverOptions : nouvelle CameraPopoverOptions (300, 300, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY)}) ; + + Repositionner le kangourou si l'orientation change. + Window.onorientationchange = function() {var cameraPopoverOptions = new CameraPopoverOptions (0, 0, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY) ; + cameraPopoverHandle.setPosition(cameraPopoverOptions) ; + } + + +## CameraPopoverOptions + +iOS uniquement les paramètres qui spécifient la direction ancre élément emplacement et de la flèche de la kangourou lors de la sélection des images de la bibliothèque de l'iPad ou l'album. + + {x: 0, y: 32, largeur : 320, hauteur : 480, arrowDir : Camera.PopoverArrowDirection.ARROW_ANY} ; + + +### CameraPopoverOptions + +* **x**: coordonnée de pixel de l'élément de l'écran sur lequel ancrer le kangourou x. *(Nombre)* + +* **y**: coordonnée de y pixels de l'élément de l'écran sur lequel ancrer le kangourou. *(Nombre)* + +* **largeur**: largeur, en pixels, de l'élément de l'écran sur lequel ancrer le kangourou. *(Nombre)* + +* **hauteur**: hauteur, en pixels, de l'élément de l'écran sur lequel ancrer le kangourou. *(Nombre)* + +* **arrowDir**: Direction de la flèche sur le kangourou doit pointer. Définies dans `Camera.PopoverArrowDirection` *(nombre)* + + Camera.PopoverArrowDirection = { + ARROW_UP : 1, // matches iOS UIPopoverArrowDirection constants + ARROW_DOWN : 2, + ARROW_LEFT : 4, + ARROW_RIGHT : 8, + ARROW_ANY : 15 + }; + + +Notez que la taille de la kangourou peut changer pour s'adapter à la direction de la flèche et l'orientation de l'écran. Assurez-vous que tenir compte des changements d'orientation lors de la spécification de l'emplacement d'élément d'ancrage. + +## Navigator.Camera.Cleanup + +Supprime les intermédiaires photos prises par la caméra de stockage temporaire. + + Navigator.Camera.Cleanup (cameraSuccess, cameraError) ; + + +### Description + +Supprime les intermédiaires les fichiers image qui sont gardées en dépôt temporaire après avoir appelé `camera.getPicture` . S'applique uniquement lorsque la valeur de `Camera.sourceType` est égale à `Camera.PictureSourceType.CAMERA` et le `Camera.destinationType` est égal à`Camera.DestinationType.FILE_URI`. + +### Plates-formes prises en charge + +* iOS + +### Exemple + + Navigator.Camera.Cleanup (onSuccess, onFail) ; + + fonction onSuccess() {console.log ("succès de caméra nettoyage.")} + + function onFail(message) {alert (' a échoué car: "+ message);} diff --git a/plugins/cordova-plugin-camera/doc/img/android-fail.png b/plugins/cordova-plugin-camera/doc/img/android-fail.png new file mode 100644 index 0000000000000000000000000000000000000000..f9e4e8628b064b7b2719e3f3a3a11eb6edb814f9 GIT binary patch literal 753 zcmVPx#1ZP1_K>z@;j|==^1poj532;bRa{vGi!vFvd!vV){sAK>D02p*dSaefwW^{L9 za%BK;VQFr3E^cLXAT%y8E;VI^GGzb&0%A!-K~z{r?UylY+dvqGwY5w87xD)T?$UM$ zG)p1SrDQ4{O1pJvL8CVRfON=G(@D5Pz)L4-&|r!{PznX(skovb3k*?&sSkmXFbJ;i zcd{czK1Fr1R3^s@x|7~dy63*{4y63?ybq5ayt<>jY`A~`5YD-B{ILE0uJZYw(!bwq z0RbSuA-Emj$pjGKP|8XV8ZF@5BHdJK$gqJqcY7O;q|)GDI@)?zA6|#lQp0l=nQx73 zc=Tz`f?4Zlhb*)W*CDLJ>&R!Ez=5t3r-qosf- zw$$y}MO#Zf^RsH;v7;iNLq`mKJ3PlFiB1oM^WdiwV4S++7#A_8m6O??IZ1hNrtS>~ z=%6Kw0ljLqrev0cOI3pem8i-*P4aY^>wbQ7_CD;S$v$UE;~w1{IDFM(Zbvq!KBg?zNCA z!X>&I>G_muiCXIRhj|6EP|a;$%?WNTzMRYmz7h%biEcc2ZHVbgkwgts;aU2)TzK+u ziE6TBXjYsM&$kv0vwejl)hgOL^o`WFd|F643|5<-v&hXlJUWFFX(Z^?{uVda&ddN+ z91oNqNq9bof@+XR`|TotvEP>LrTPx#1ZP1_K>z@;j|==^1poj532;bRa{vGi!vFvd!vV){sAK>D02p*dSaefwW^{L9 za%BK;VQFr3E^cLXAT%y8E;VI^GGzb&0zFAYK~z{r?U=!8;!qTZ^9o9Rkv>3YR%I52 z4qfyO24OlYp$sV9bovl38oC*9Hg?lRx=|?2VoE^@ccsOmld+OO9g#o?6z=@zBpI#V z#A;__F#M3*+;eWuch5NyqdorV9O&=1i`nh3sZcQs94V#t`E={Ux9rCs8++AU3Iq_~ z07?U5YN!GM2T&T)H#Lz00cs8QKUESw+FQy|WoAmLW7xaSaWtIoz6@CY&UB?5IHml| z)FP@_%Y#94+!qE5sQ9oOx6`wWXd$p!y$vjXb0(h7%SJRDQ_W<|C^g*Sbn)*ckhx)&M7tEVT5^davtazZ#o*9~U@0yH88iM>Jq#g}YLTU{@9EnHKcD znr`F@BAyDmN3jf>V)L4eT6Ma~oBAv+ug)o!AP8}bhzGs>LYvzpj4bGx?$1WK>D%Hr z*;wuO`L+Pt!+o?AjMeT6C4w1Ij}n`mL>0*RbkVClP<|%B=-K14DN}NW;%;&l*Zd&g z)Oj6FAlq<(xK8Pxag4h{iC~b4EyM!jBc6(a!(MXP#Da~3UJ5M6U7>kk&;(m7RW*0i z>%zePRc=!C#)6?@X`TL;uw7MPT-8*Hg?4MY6xHquy#fpZo987^k+=hWw{}gNO0SCW zl^}=KD7cVT2bM@F6>Hf2d^55P44{~o2jxoP{vwP>uLD~_t-)4JYp_)lgB3Gr{G*xS yPXj0E`ZREoJ^a3-;nx6cKt%e|pkfA8Qp&%Fe;&Px#1ZP1_K>z@;j|==^1poj532;bRa{vGi!vFvd!vV){sAK>D02p*dSaefwW^{L9 za%BK;VQFr3E^cLXAT%y8E;VI^GGzb&17b-;K~z{r?U=u7+dve@wY5wAFZdr2s7ty8 z+NEH~)+ux-=@@81qc*RB7Mi7@lTZhP7K1^CY6wAKCDpp3cED2HjP+z1Gqq*-og`iZ z{D{#3{x37RsL5@FOzR-&8EZWw31`H^0Zf`?EP|QW?lEo;m62BI!sJ@wRLOv9ax1BK zPqm&=v2{N7;aSs5h#sm1rUfl#H99< zFWDAcwFi7?1V(3VAIh*?wD7I&5d6!RkZ>joy^e<_dNcIYMAeR)LRL;3=*`Xu9k>-N z7@4+sI(5d^A~U_w@Us2RDLm~(Rkz;nPu;)`fNDrUjyUQ;LzI^Z@Q9Us~CZ{d5r2S#xZipMIZmGy`T zBaa_zQ7@5`E@I?Ozp&wxS`XX1L)thqa;^lfXG9Cux7t=Yw6H!q=|?A1a#q4vHco!W zn~rRmSivHVChQ9+mWh598T-mb-GsmM>M2Qu1IZzRkfj>@;h?Tuu{3?F*4)1(C*HQm z?<)p)c4}7}85NF35bIt3iY&Y|1s^zba5tdmnkx(2oNM&+VcC#$JPmr2=T;9>J$u$y zd$gO&(c>1V%lZ_V}R6 z;%T6Zsu}NJrfJaEyo>K6c7qa7+|v{{%@{u|pG(cjoU?Fk?9-)gf2On}VS*DpEvJOE5U3yLaN fQosZNA%y+`ssO6HPx#1ZP1_K>z@;j|==^1poj532;bRa{vGi!vFvd!vV){sAK>D02p*dSaefwW^{L9 za%BK;VQFr3E^cLXAT%y8E;VI^GGzb&14&6lK~z{r?U=u7+dve@{Vyam|A_y9HdE+O zXz}3xAPCw_g;KD|;&$zlNkdJB7SzRFjFE@h5bQxAAOg444mNgFC&-W}7}G;wP``I4 zSvp&Gez`+~jxX4HdiQkqxp(h`QWsADUGc?EZgb~jqB!L?!N>Ew)Z4GmUw+zr^W#~j zw3TR4AOk+2lmfE^(`tbaD5a2Kb2kz#3X~F3chcHO6-PIydEQuy8XIF~n={5LwtKAc zu{tVSQ_8}+tzuv-bjgI7ZhGBp=qc+Vq?FSZ;$DyPie%TUm|4XdWA(`H_fnp?5mHC& zDZOr5=@QQyG>@X5q3%seVB*a-PolT}S5iv9gKQ$FTNyqztDlygeceJzIX)y;WmOL@ zLrhC@%C+q&eyG(KX&g*d&zlpzmBNnc;^hDXhO>PMi|^_0I5y&CF@uiNfq9zt{oPh$ z2%~L{qnCg9HWN@pC_zUe#Uq5ICZl{XBS|YsAuZVuJ(t#t`qq200u#iCLaSf&tik+9 zjqwdgondS@ZIW)XTb%~{$q7c=>uy&Z>e0Fycq(Su2#ZBrOxBV1&Nw6764UkuhN-q) zo0!t&*>5&x*HJOr{qwqUEb?XTq;&CA)?8|{q4E}o2@0S@pB*t~^xev^-earGNJV@i z-DwAFbA7od8ReKN`!j0@B~5$229?q^2W}`7d&clE81~vpK`pF|7?al&Ps150+WsYXr_~CxcN%_KjfuI?aWyGFdEE(VlE5PStfx*fMPMz*1c|A(RO}Qa z4y_-|jALzoIKZ!cuD02BW~BH*gB2_n^xfJ}JCK>WldAf2NldnpJ$I}X;OSHkZY5RP zGtqZ?@@;0(3v5PHQW5o+pM6$$dmU#VU{Sgf6QuRV<%(ZxJBG~ExeZ|QJnt`+DQ?>R)md)<00001KIqEP)Px#1ZP1_K>z@;j|==^1poj532;bRa{vGi!vFvd!vV){sAK>D02p*dSaefwW^{L9 za%BK;VQFr3E^cLXAT%y8E;VI^GGzb&0+&fdK~z{r?UylY+dve@wY5wA75oJZ?$UNJ zv`fLzrDQ4{3fVHWpix`bLJIa$lgX%qK}*3P4<1Yr2ttBE7!So20ofq1EKDr~rov#j z{@;BPj!g|bb|susk72Msu(d6p696RU;L~kpgc?z){$u9>!`6 z45u?*GjA#vtsWjIVA+#(F$E(q{J3g?-!ib)%9J&w`#bg-7Ukc}jmA@@xRW`#li2nl z!7@}kJTSh$S^K?S6&k_C;IbF>=zGZ?wHgDIPI)sdkX4aD|ITFGnXN}azhIOrUtv&KvriZF^OZ7#>tH9@y;Boy9+n0Cjk`4_-#B)x^ zBR*FvQ-R_WVd}!xe#R$wm z8uDz(>tUPu2HS^3Rw*X|^h$Z>Ed6(O8&VGK9w`rYphyS!3y444_lNSM4v;S|pG&yr kK?OLpEY}7E@G!>y0F4#wz4jCndH?_b07*qoM6N<$g4j4?+5i9m literal 0 HcmV?d00001 diff --git a/plugins/cordova-plugin-camera/doc/img/browser-success.png b/plugins/cordova-plugin-camera/doc/img/browser-success.png new file mode 100644 index 0000000000000000000000000000000000000000..6c2c000e3975523c631bcdaf54b305851a7b9325 GIT binary patch literal 776 zcmV+j1NZ!iP)Px#1ZP1_K>z@;j|==^1poj532;bRa{vGi!vFvd!vV){sAK>D02p*dSaefwW^{L9 za%BK;VQFr3E^cLXAT%y8E;VI^GGzb&0(nV9K~z{r?U>Dq+E5h7eFdeyh!4Eiwk<4NghGyX)h>(pRD6y%P1ZETwE*FH`|G78T zj~Sh|3>1TxKbU)R&&mCrbCO_UKS%Bx{mDT-aquoG$|pc1gowTV^!VAw#LF*_(#2#n z1Qrm1D+bCafhmCqTrm`J?L;&Lu07j*(t|PXT`@7%?Eg{!!j^5=Qz34GLUzS&c)QM~ zz~u1jwdGU0#+JQ0bFNLznok#C8|ub=e}*6CxfvM4M&)*8(C5fSJ*5wEKnwgK+@%W! zx1EVP8apmsVj2|Ejq;7Maa*VObKhCN-bmewyu6c8TiGrRk2WeeE9+J==WGFk(`Zc?^?Adr zx+w}M>&B-g?SgzYRj6>ZE31+3)K)ggMpnXjYHR?5Zn04=?`2CK4}BQDz|cD=rtn8* z<#HbL;;=epV%CO5`m$DYe(C|(pe4M`V36ubTSHHx0IYmU#?>8kXojB5b=#^Z$=IYu z6(cQe{ccOL>w)hN4s({)o5^%YUp_HDpqoae(}!V$fXCQYFv#dl%&+0?-mccEuVk`m zc&=Kr_AF6Gtw#&6p8AttpQwO((00Dtsx2iz=6ochEk8>Zk?+u-vF)bzY`dvF+ips- z<>L|kZyJ~16pkYIP2ni<_Ve=?-V(qAC5jjk<>LSoLi_@ghZlf7-fxEh0000> literal 0 HcmV?d00001 diff --git a/plugins/cordova-plugin-camera/doc/img/firefox-fail.png b/plugins/cordova-plugin-camera/doc/img/firefox-fail.png new file mode 100644 index 0000000000000000000000000000000000000000..2c6cbd1908d2379200eb461a75c96042e02c5df9 GIT binary patch literal 802 zcmV+-1Ks?IP)Px#1ZP1_K>z@;j|==^1poj532;bRa{vGi!vFvd!vV){sAK>D02p*dSaefwW^{L9 za%BK;VQFr3E^cLXAT%y8E;VI^GGzb&0+UHZK~z{r?U=u7+fWe4wY5wAFZdr2s7t#9 z+NBWamZ@|oWOJbfjoR`Dv`{ZKos2sKv;+*+AZQ2zm6Bo*si7c5s4Otp7N&Yt2^Ipw z>%Eg){j{8h42_8R4tnqIp5N#0^n}d)wC%SK@4vXiJ+FlT1aK&&+?xl&>$}{?dz{>; zg8&3@0E!{jhAI-^02C`<&QJpZ)GgR1?S1eFJgamy{JbDE)TO*bQAtR9kTYGAs==Cu zJ`1h>kdKDD=OeNlwzaI!`G``YO-BKpfB$tUuyjcOOWt}tssj6TXtJzAUL9cDwXGl; zE|q5~H_?UM6U|6ww(1HY|E$W2ts5qD1*W~1_}ErFO|4#hZ}kiv!-!@p;}xAv#inr# zHxN6XO3ic#Yl_H3gNtJk+H!3*U0fv8#iEZasY^Dj%1$L1D94tiLZ#E+^TCI07bod> zBDNP~<_=C*H1Imm*aUko6>UV`f_Y79|I-Jb6CJwYl;3=|w@R(r~eAqgUe6lb5 z^DBcjk`9Cmdot&+8El=-VN}5QGVPQVYfD@SilBvYeK`3g7R2eFV0eiSR*Y?CC)z`a zs=+c;(N$pE4u(4m7VkP$d|Xpr-qn7u5VS_Md7i*iF?f*iBQd!D{=V3188#>h;$E;JknGh=UgdumK{J guLc4TprVxi0XCOR_`;pcRsaA107*qoM6N<$f-uWsGynhq literal 0 HcmV?d00001 diff --git a/plugins/cordova-plugin-camera/doc/img/firefox-success.png b/plugins/cordova-plugin-camera/doc/img/firefox-success.png new file mode 100644 index 0000000000000000000000000000000000000000..deb9d24abadf059dc89639bdc8c9b78b61b3096d GIT binary patch literal 770 zcmV+d1O5DoP)000&U0ssI22R!za00001b5ch_0Itp) z=>Px#1ZP1_K>z@;j|==^1poj532;bRa{vGi!vFvd!vV){sAK>D02p*dSaefwW^{L9 za%BK;VQFr3E^cLXAT%y8E;VI^GGzb&0&_`3K~z{r?U=u7+dve@{V&+m|A_y9)>G(E zXwlGr!O(6drC^gK&Dy1thKdX=sEfTBWk>{}8XOG5prN&lO>ET(5+pLJ;5aZ`-<{-I z(eIcn7Cyd%bnm_MectyhW0h{~>-WNogI49>W3kk#02d*o^zQ5Pm!B$cemvtk)glRq zfD7nKz*;;!PrwCqB``D;D3X9~PnciI=@i2ko8Y_t2ou*j4ktvlDd8KT&=YAJ!p2Z> z3Awl05BF3%vtg%-Y9oSv&2te3OM0Kf(WlX)2|YYEOmz?pwKZ@9E5c?bQ(KfgS{a0m zt5fZ+%S-Fq4PMwo+41LzBl_2lC|FB+ffac%!_X16CfvdWA*-1>tOZNJPd`MEc}rJb zM|F)Y;#%!!4mZ5Gr?+WsN+rA$jTI|L7lKr6YKeGEK|@3XlIXtKB$@S9euPc!&j1rN z9oHy1J(htI4MN12)Eg5G0H)(ACmr@(M6VZJS$j=CE|Npnal1!XT?1`LD0%y%10ypP z50p%}ZZPjz>JMEGM48)5Z3wo|J~GFu+<;l+_KsM2Ob+u9yFLEg+e3^}2|)_<-rJBr z67WFTglvmw^gE^`p0HE@N&Cv?lXA|P)hk`T{J-o2Wf6h`kjZ$UY(j3#?i}$LPKVw5 z5{$ACoWSNp_fKi3&d&$^xk7D3$~SN+k|S8Axj1Y}{B-4aA*vjNAb>uie$p5Yz_39Z5zY}TU1KePgX%XiqI`tAtUclGYfrfQVuY=7q5lDw z*;|a0g1*H#seJhUssz6;012#MXra_910EsdA8>npDfJGffB*mh07*qoM6N<$f`x8R AKmY&$ literal 0 HcmV?d00001 diff --git a/plugins/cordova-plugin-camera/doc/img/fireos-fail.png b/plugins/cordova-plugin-camera/doc/img/fireos-fail.png new file mode 100644 index 0000000000000000000000000000000000000000..b1e7b9b9e1282bd7d844e9ba8355b1876508980c GIT binary patch literal 965 zcmV;$13LVPP)Px#1ZP1_K>z@;j|==^1poj532;bRa{vGi!vFvd!vV){sAK>D02p*dSaefwW^{L9 za%BK;VQFr3E^cLXAT%y8E;VI^GGzb&12#!SK~z{r?U=u7+dve@wY5w8FZdrYxJ$Yi znxzoP<|%Y2Wb@F1Mr~OGDa1=dC*uwVEe3-2`61GiRHjD^8) zeeZO(^~1945=d!ve23HB(|hO7z4tKUe(3s#moMHv;oigw7w`c}gb?m*FZKQ@_xTwo zK93bD-~*I^6_Sf#Z6lxrtT5Sp8?nL!tYTg}=pW*h`7}169g}(E%g7`%MerLugraz5 z3YOU)T^u-%6+xPq>OG%W8T>6ublQZNa<6TZ!MC4}#7h{`8-s%YvWg&2ohQ3>>$iM# z@px2IZu-|BSetnznwR~#!^kye3SV)XCHbDgxK8O-Q=yNB+%s&TYZbG)1{1a$YVQoY zevNUvG_F0l^f(+2aM3F6ucA}w8t&uJ3T&#nW1g}-kT8#j*Bpz#8J)niK z1+O*stm2$P+me^N2Djlw-P)sbdgk>}I5C~QhaO_9`XMv(X)`Z+=XA`J)0 z1Fz9<&#y8ChF!l2>-WU8G-m>t=sLjKeoxF_cRu5TPMfZT^!uiw4og^1P?8LBKoPt^ zm2}EYM@pxb^Z!uMykfZ(^V&@@uiX^$+D*tS{$9AH*!RM-z0|w-dvuh54^aB}`V|NN nKmZw#gJg>pCg20G2qC`#6CBds&-WPC00000NkvXXu0mjf>ngtc literal 0 HcmV?d00001 diff --git a/plugins/cordova-plugin-camera/doc/img/fireos-success.png b/plugins/cordova-plugin-camera/doc/img/fireos-success.png new file mode 100644 index 0000000000000000000000000000000000000000..7b6289e063de5f7022e2cac418fd5852a1ab674f GIT binary patch literal 936 zcmV;Z16TZsP)Px#1ZP1_K>z@;j|==^1poj532;bRa{vGi!vFvd!vV){sAK>D02p*dSaefwW^{L9 za%BK;VQFr3E^cLXAT%y8E;VI^GGzb&0~tv~K~z{r?U=u7+dve@{Vycc|A_y9wo~X( zNb!*WpcvZCxD;%%q+L5ClZT27DY%Qh6yprB!9+uXK^QbNR)~qMIzfWiMim?a!S#D5 zIo6LzR!tzK==ct&yQlX~pL_3YE^{-xelNV(DsOImOtnhoO|YVrX5M{${_4}_oA1x^ z^=ztmff87OSO)x3WXT0qAeKSm1twC(3&c`tf35$Hns_+0a9C68?rdODQ{M|3Jcibx zR_Kc+rBl692u(e;a>p|O6QvoUJ^W} z`_3Y?t7vNOV7BU{p4${99EInaWj3oP_ilrVr3Q)EA2)*2qLH!1O(#3NG!jsIz}~Gv zr}Pq1^HyaNYTPXuT<|qN93`7SDV^a|v6W8OH4A7JHOK=l5?MXFI~l=18&_GfB%tG`yidTxSLjBbIT1}0g4Ae4ed)T&F^B@#O&^2vRDz-%R9-lQ?WAbu5TARcAJ6Y)gaom1WkT*}ZzyuK}H_hSNb- z`qtphyG4I~^E+U?b3EfC5x)k4uE=B2DN+}7NXe+B@++mbj#6stD5bWJQfljnQ!8(z zx01=lZzVVQ4fyBuIyaF(39LSRd!5056@UXjBwnf&DsKQ8rSuPjCc2qVVr6~+0000< KMNUMnLSTZv!K;b@ literal 0 HcmV?d00001 diff --git a/plugins/cordova-plugin-camera/doc/img/ios-fail.png b/plugins/cordova-plugin-camera/doc/img/ios-fail.png new file mode 100644 index 0000000000000000000000000000000000000000..2d8caf80736086f202655632a7528774fa656769 GIT binary patch literal 573 zcmV-D0>b@?P)Px#1ZP1_K>z@;j|==^1poj532;bRa{vGi!vFvd!vV){sAK>D02p*dSaefwW^{L9 za%BK;VQFr3E^cLXAT%y8E;VI^GGzb&0j^0zK~zXf?Up}F!$26uv+1H=p5C*S}Dng)_En+s5& zX(^x18pU%Gz0*;(B-_uevAE(FmdR1PV30(x^X1;+_P5)$v#5b&|zobY!BuDUr z%~Ty>8~8#C>`_H+R62-YSXM04CvNR2TN@2xAH%+z=d+rY#H2JkNgO z*4r8BicmCO^jnx5!E!uKGr2c6Ac5_i%wG|T#20BjnfYGvN_2sCdgeAQe!0VouUG78 z@%!V)oSrTX0~VIJA{3qd@k^KGR8Z-X&p}|j*@e+#Ga-$hW!m0@!RsHt_j+c2)>M6Y zBV%YKe!cp~Zy3Mf=LTLp7n^u&0eX9MsNh#c1PBDBNKC+iO$hk{!BAtggYvr=00000 LNkvXXu0mjfpv~~P literal 0 HcmV?d00001 diff --git a/plugins/cordova-plugin-camera/doc/img/ios-success.png b/plugins/cordova-plugin-camera/doc/img/ios-success.png new file mode 100644 index 0000000000000000000000000000000000000000..3bf3b5ac773635d4188fa85c16eff5a254165883 GIT binary patch literal 550 zcmV+>0@?kEP)Px#1ZP1_K>z@;j|==^1poj532;bRa{vGi!vFvd!vV){sAK>D02p*dSaefwW^{L9 za%BK;VQFr3E^cLXAT%y8E;VI^GGzb&0hdWcK~zXf?UpfX!ax+q^A!yBi}VAuouosD z;+F`tn^+2wF4hl`p`lB`F1nR0DhL@WLJ=}mQQC%963~hSj(~9e=VDN=Bua*)6p!C> z_wsl@-n+mFU*B(+>TymMbJuAgi>OX16)x_MPH)BY$Af$=n>?tC>TnQXl$L}Ks>4A* zbGShAz~R4nlns|UcKO%&PQ>w$db&gD)GkRI=gE5b5^Py7T|OF{Egn+m-k8)CE!eIk z_~vnu*ACV3yX$R;HD=%Rno|~}uCA`7tP|f@8mRayL;{3+AlfKCJA^L!tu~jnWSa+AQwf&^(MN9&+Xnyn{0AU06x=U04yX o9?k^(=}>_Ynv()@1`?Fg9|9!GmclbI6aWAK07*qoM6N<$f+>LK)c^nh literal 0 HcmV?d00001 diff --git a/plugins/cordova-plugin-camera/doc/img/ubuntu-fail.png b/plugins/cordova-plugin-camera/doc/img/ubuntu-fail.png new file mode 100644 index 0000000000000000000000000000000000000000..ca82c79fa90acd2c65e60e65ad779de3658d5c19 GIT binary patch literal 649 zcmV;40(Sk0P)Px#1ZP1_K>z@;j|==^1poj532;bRa{vGi!vFvd!vV){sAK>D02p*dSaefwW^{L9 za%BK;VQFr3E^cLXAT%y8E;VI^GGzb&0s2WqK~z{r?UylY!ax+qv$ae674iiHyR?hY zE`>n1jvY$7w~*1zwa|iHy4yj>D7ZK{1cYJ{L>!6+K|=)-hc*PHK?q#m-Pt4_mkS~V zBZfbCIsfnO{qEi!MEV*IpH7ah_oSNMG+Fm zn&D{AEh}-(McdS;HvE9|jO@JS<6am+|KyL)k&pz$!YpAB1219Q)ddH@uDy$$Y@*buRb!(#67PvJ z=#mvJWbrFKGhWZUjUE;GqlL@QH!XV6xn<}qeH&W8KEey(^~NgobDV#r>$nDO&~RmF z;8pu+s8#;>9EnLlaxE9lJ6p>I?afjmNouqs**t9*$@Y9{!FS_b%D;Xg|CjSq2`*`X j0Vdd>Gzu~Y41~}x{C literal 0 HcmV?d00001 diff --git a/plugins/cordova-plugin-camera/doc/img/ubuntu-success.png b/plugins/cordova-plugin-camera/doc/img/ubuntu-success.png new file mode 100644 index 0000000000000000000000000000000000000000..b15227db767a6af50209aded158bd89b989eab0c GIT binary patch literal 622 zcmV-!0+IcRP)Px#1ZP1_K>z@;j|==^1poj532;bRa{vGi!vFvd!vV){sAK>D02p*dSaefwW^{L9 za%BK;VQFr3E^cLXAT%y8E;VI^GGzb&0pCePK~z{r?U%nw!$26o^9l|2Mfw1`6$e3a z=qnV|Nf063w5y9#2aAgkmu8WYE)@y^D?%t_(m^T#OA6Hz0!N^5es`C)F}++Gi$hAo z4|2JDU+#YQ4{l10M#6 zfQ|%H7I~3rKxd000&U0ssI22R!za00001b5ch_0Itp) z=>Px#1ZP1_K>z@;j|==^1poj532;bRa{vGi!vFvd!vV){sAK>D02p*dSaefwW^{L9 za%BK;VQFr3E^cLXAT%y8E;VI^GGzb&0)a_HK~z{r?U*rZ+fWe4wY5w075oJZ?$R!X zdMOyPbt)Z7vt?+(qqeMp7VM=VlTio5TM7Yt&|r!{Pz(lPJOovQssck|QDUKDEChnr zyL)aVEADei3Tf0l{@|z6>3qL?_nwiJbJu~CzO2)0c=XG^cgyqKRG!j&q5%_8; z<3`D$+3=m^%aL&>skl(aAs7%r3~KCNNm9Sy4&$>b#`O!rP!eBZ)!m5~@yJdstCA8nv0-Qgese!IT`GwW3o!5P>gCof5|vsb`5M+w##GV03SNpm8QI=Wek-!A)(q0Z&cTjK zhWo<4JZX6F<156$N$7|PIDbS!g#|5=fC%t7=RW}i%xjDrv(j_` O0000Px#1ZP1_K>z@;j|==^1poj532;bRa{vGi!vFvd!vV){sAK>D02p*dSaefwW^{L9 za%BK;VQFr3E^cLXAT%y8E;VI^GGzb&0%%D@K~z{r?U*rZ+dve@^%ZRDFOmW~;rH8>c8;g-a~#;tIS1hIuG5CXyV-8(yy z<>nmRK+Dy~AAEZ6>GXbjPbVzpYBqXlJld_7ci+gUdKu^_rOJzs51+g%Kl}VZZC2zH zZ~+}KDnKkNBp1*DqXNY(IOG#BZaMEw2PC19f3RZDs{t`=gyxFt9<&K(t>;9PPW?u0 z#dVAB!U;0ne}|Jp;_%M8Mem>K?{U^nkI1#9+l#{tvQSS<5k}&Wkk0}#V!@H$XmLwu z8h*egkwaqmiQQ2Z&#g9n4~~SyL>P%$%UZ_?%Au~=W6xQ$(V4E=m~r;Bh&WYDdOCTP>r7_keX9-n zyl(~T8@}g__cdD|ru=^WMt9%@0csqtfn?H$kR0nJ)?>-_2X3G5Lo~ShiTe=LB;*qa zhJd{m>%+x9G&dIZA<_DV-zPsD-ntt-pAu=yDVMgKatS%>rT^f6b_u_m97_G&Px#1ZP1_K>z@;j|==^1poj532;bRa{vGi!vFvd!vV){sAK>D02p*dSaefwW^{L9 za%BK;VQFr3E^cLXAT%y8E;VI^GGzb&0y{}WK~zXf?Uq4H<3JS0=eAz#SMUo2>SgyL ztQR5Rt*5ewg}tq?3q9r|2nzP%;;Ga_As3-w4*~ZO2rPv{&>j{ILK-NT7TFGkkPs-0 z@6E(E9W`o2n!^r%$Ykc_@tgO52_gSncmLD+*AL`N4g?qg!x$rbAB#U%$nh%C3(FT^ z01O}@U{08X00xk-bkfGs1xWv~Q0i63hmM9Zahe@P+D(*=wPss>JbPHZ?$WSRHRobp zr_7l_6#0#+no$ zlv%CP(TEC?)QB$K(ln+%7K_vzI>~I0_JCA8*;%oIR)?1WItmM1(bYExaU8}XYa*UPJ-$3|7 w{gJ1iW`H@|`b?lJfeZklbW0at025>E4%6p6>jF19od5s;07*qoM6N<$g6_IIKmY&$ literal 0 HcmV?d00001 diff --git a/plugins/cordova-plugin-camera/doc/img/wp8-success.png b/plugins/cordova-plugin-camera/doc/img/wp8-success.png new file mode 100644 index 0000000000000000000000000000000000000000..a37cad6971d8a57154ac01752725f483c8c4d7da GIT binary patch literal 679 zcmV;Y0$BZtP)Px#1ZP1_K>z@;j|==^1poj532;bRa{vGi!vFvd!vV){sAK>D02p*dSaefwW^{L9 za%BK;VQFr3E^cLXAT%y8E;VI^GGzb&0vJg|K~zXf?Uubt!%!5*^9n8IMSK9=#6eIp zZ10Fx*gW!Bw*cwOILtiKJ-9^oBfP*Zg=Z+!)aiqJhRVhs(o zw0+$>%VTux(dA|UC#%ALV%8Wj++S5=SH(4zPshr03j;C*j%l+A86&fFtKE4(L0au{ zGwK@SLv)eV(zV*6)UG+B`+7sJWAeiDXDD}LL~c{of{m1G_ciqaXP*qq^#%`p!iNW} zF@Q#6Fu5nLS$v=v;*6cWH8F9hNcyD3JjB16=T|b;nDv+aneMeA9z1u!^|Sp2#2}af zhf-$d+nI5-*mIUgZ7&F<49+Yi0i^0Bk9BF;cLh%%F!kME~?@9%f@&ll|k+E+_3 zMZZ(O#q}rn3YiqYPc!U&f0WAi{ZV%BVncw*1w + +# cordova-plugin-camera + +[![Build Status](https://travis-ci.org/apache/cordova-plugin-camera.svg)](https://travis-ci.org/apache/cordova-plugin-camera) + +Questo plugin definisce un oggetto globale `navigator.camera`, che fornisce un'API per scattare foto e per aver scelto immagini dalla libreria di immagini del sistema. + +Anche se l'oggetto è associato con ambito globale del `navigator`, non è disponibile fino a dopo l'evento `deviceready`. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(navigator.camera); + } + + +## Installazione + + cordova plugin add cordova-plugin-camera + + +## API + + * Fotocamera + * navigator.camera.getPicture(success, fail, options) + * CameraOptions + * CameraPopoverHandle + * CameraPopoverOptions + * navigator.camera.cleanup + +## navigator.camera.getPicture + +Prende una foto utilizzando la fotocamera, o recupera una foto dalla galleria di immagini del dispositivo. L'immagine è passata al callback di successo come `String` con codifica base64, o come l'URI per il file di immagine. Lo stesso metodo restituisce un oggetto `CameraPopoverHandle` che può essere utilizzato per riposizionare il Muffin di selezione file. + + navigator.camera.getPicture(cameraSuccess, cameraError, cameraOptions); + + +#### Descrizione + +La funzione `camera.getPicture` apre predefinito fotocamera applicazione il dispositivo che consente agli utenti di scattare foto. Questo comportamento si verifica per impostazione predefinita, quando `Camera.sourceType` è uguale a `Camera.PictureSourceType.CAMERA`. Una volta che l'utente scatta la foto, si chiude l'applicazione fotocamera e l'applicazione viene ripristinato. + +Se `Camera.sourceType` è `Camera.PictureSourceType.PHOTOLIBRARY` o `Camera.PictureSourceType.SAVEDPHOTOALBUM`, una finestra di dialogo Visualizza che permette agli utenti di selezionare un'immagine esistente. La funzione `camera.getPicture` restituisce un oggetto `CameraPopoverHandle` che può essere utilizzato per riposizionare la finestra di selezione immagine, ad esempio, quando l'orientamento del dispositivo. + +Il valore restituito viene inviato alla funzione di callback `cameraSuccess`, in uno dei seguenti formati, a seconda il `cameraOptions` specificato: + + * A `String` contenente l'immagine della foto con codifica base64. + + * A `String` che rappresenta il percorso del file di immagine su archiviazione locale (predefinito). + +Si può fare quello che vuoi con l'immagine codificata o URI, ad esempio: + + * Il rendering dell'immagine in un `` tag, come nell'esempio qui sotto + + * Salvare i dati localmente ( `LocalStorage` , [Lawnchair](http://brianleroux.github.com/lawnchair/), ecc.) + + * Inviare i dati a un server remoto + +**Nota**: risoluzione foto sui più recenti dispositivi è abbastanza buona. Foto selezionate dalla galleria del dispositivo non è percepiranno di qualità inferiore, anche se viene specificato un parametro di `quality`. Per evitare problemi di memoria comune, impostare `Camera.destinationType` `FILE_URI` piuttosto che `DATA_URL`. + +#### Piattaforme supportate + +![](doc/img/android-success.png) ![](doc/img/blackberry-success.png) ![](doc/img/browser-success.png) ![](doc/img/firefox-success.png) ![](doc/img/fireos-success.png) ![](doc/img/ios-success.png) ![](doc/img/windows-success.png) ![](doc/img/wp8-success.png) ![](doc/img/ubuntu-success.png) + +#### Esempio + +Scattare una foto e recuperarla come un'immagine con codifica base64: + + navigator.camera.getPicture(onSuccess, onFail, { quality: 50, + destinationType: Camera.DestinationType.DATA_URL + }); + + function onSuccess(imageData) { + var image = document.getElementById('myImage'); + image.src = "data:image/jpeg;base64," + imageData; + } + + function onFail(message) { + alert('Failed because: ' + message); + } + + +Scattare una foto e recuperare il percorso del file dell'immagine: + + navigator.camera.getPicture(onSuccess, onFail, { quality: 50, + destinationType: Camera.DestinationType.FILE_URI }); + + function onSuccess(imageURI) { + var image = document.getElementById('myImage'); + image.src = imageURI; + } + + function onFail(message) { + alert('Failed because: ' + message); + } + + +#### Preferenze (iOS) + + * **CameraUsesGeolocation** (boolean, default è false). Per l'acquisizione di immagini JPEG, impostato su true per ottenere dati di geolocalizzazione nell'intestazione EXIF. Questo innescherà una richiesta per le autorizzazioni di geolocalizzazione, se impostato su true. + + + + +#### Amazon fuoco OS stranezze + +Amazon fuoco OS utilizza intenti a lanciare l'attività della fotocamera sul dispositivo per catturare immagini e sui telefoni con poca memoria, l'attività di Cordova può essere ucciso. In questo scenario, l'immagine potrebbe non apparire quando viene ripristinata l'attività di cordova. + +#### Stranezze Android + +Android utilizza intenti a lanciare l'attività della fotocamera sul dispositivo per catturare immagini e sui telefoni con poca memoria, l'attività di Cordova può essere ucciso. In questo scenario, l'immagine potrebbe non apparire quando viene ripristinata l'attività di Cordova. + +#### Stranezze browser + +Può restituire solo la foto come immagine con codifica base64. + +#### Firefox OS stranezze + +Fotocamera plugin è attualmente implementato mediante [Web Activities](https://hacks.mozilla.org/2013/01/introducing-web-activities/). + +#### iOS stranezze + +Compreso un JavaScript `alert()` in una delle funzioni di callback può causare problemi. Avvolgere l'avviso all'interno di un `setTimeout()` per consentire la selezione immagine iOS o muffin per chiudere completamente la prima che viene visualizzato l'avviso: + + setTimeout(function() { + // do your thing here! + }, 0); + + +#### Windows Phone 7 capricci + +Richiamando l'applicazione nativa fotocamera mentre il dispositivo è collegato tramite Zune non funziona e innesca un callback di errore. + +#### Tizen stranezze + +Tizen supporta solo a `destinationType` di `Camera.DestinationType.FILE_URI` e un `sourceType` di `Camera.PictureSourceType.PHOTOLIBRARY`. + +## CameraOptions + +Parametri opzionali per personalizzare le impostazioni della fotocamera. + + { quality : 75, + destinationType : Camera.DestinationType.DATA_URL, + sourceType : Camera.PictureSourceType.CAMERA, + allowEdit : true, + encodingType: Camera.EncodingType.JPEG, + targetWidth: 100, + targetHeight: 100, + popoverOptions: CameraPopoverOptions, + saveToPhotoAlbum: false }; + + + * **quality**: qualità dell'immagine salvata, espressa come un intervallo di 0-100, dove 100 è tipicamente piena risoluzione senza perdita di compressione file. Il valore predefinito è 50. *(Numero)* (Si noti che informazioni sulla risoluzione della fotocamera non sono disponibile). + + * **destinationType**: Scegli il formato del valore restituito. Il valore predefinito è FILE_URI. Definito in `navigator.camera.DestinationType` *(numero)* + + Camera.DestinationType = { + DATA_URL : 0, // Return image as base64-encoded string + FILE_URI : 1, // Return image file URI + NATIVE_URI : 2 // Return image native URI (e.g., assets-library:// on iOS or content:// on Android) + }; + + + * **sourceType**: impostare l'origine dell'immagine. Il valore predefinito è la fotocamera. Definito in `navigator.camera.PictureSourceType` *(numero)* + + Camera.PictureSourceType = { + PHOTOLIBRARY : 0, + CAMERA : 1, + SAVEDPHOTOALBUM : 2 + }; + + + * **Proprietà allowEdit**: consentire la semplice modifica dell'immagine prima di selezione. *(Booleano)* + + * **encodingType**: scegliere il file immagine restituita di codifica. Predefinito è JPEG. Definito in `navigator.camera.EncodingType` *(numero)* + + Camera.EncodingType = { + JPEG : 0, // Return JPEG encoded image + PNG : 1 // Return PNG encoded image + }; + + + * **targetWidth**: larghezza in pixel all'immagine della scala. Deve essere usato con **targetHeight**. Proporzioni rimane costante. *(Numero)* + + * **targetHeight**: altezza in pixel all'immagine della scala. Deve essere usato con **targetWidth**. Proporzioni rimane costante. *(Numero)* + + * **mediaType**: impostare il tipo di supporto per scegliere da. Funziona solo quando `PictureSourceType` è `PHOTOLIBRARY` o `SAVEDPHOTOALBUM` . Definito in `nagivator.camera.MediaType` *(numero)* + + Camera.MediaType = { + PICTURE: 0, // allow selection of still pictures only. PER IMPOSTAZIONE PREDEFINITA. Will return format specified via DestinationType + VIDEO: 1, // allow selection of video only, WILL ALWAYS RETURN FILE_URI + ALLMEDIA : 2 // allow selection from all media types + }; + + + * **correctOrientation**: ruotare l'immagine per correggere l'orientamento del dispositivo durante l'acquisizione. *(Booleano)* + + * **saveToPhotoAlbum**: salvare l'immagine nell'album di foto sul dispositivo dopo la cattura. *(Booleano)* + + * **popoverOptions**: solo iOS opzioni che specificano la posizione di muffin in iPad. Definito in`CameraPopoverOptions`. + + * **cameraDirection**: scegliere la telecamera da utilizzare (o retro-frontale). Il valore predefinito è tornato. Definito in `navigator.camera.Direction` *(numero)* + + Camera.Direction = { + BACK : 0, // Use the back-facing camera + FRONT : 1 // Use the front-facing camera + }; + + +#### Amazon fuoco OS stranezze + + * Qualsiasi `cameraDirection` valore i risultati in una foto di lamatura. + + * Ignora il `allowEdit` parametro. + + * `Camera.PictureSourceType.PHOTOLIBRARY`e `Camera.PictureSourceType.SAVEDPHOTOALBUM` entrambi visualizzare l'album fotografico stesso. + +#### Stranezze Android + + * Qualsiasi `cameraDirection` valore i risultati in una foto di lamatura. + + * Android utilizza anche l'attività di ritaglio per allowEdit, anche se raccolto dovrebbe funzionare ed effettivamente passare l'immagine ritagliata a Cordova, l'unico che funziona è sempre quello in bundle con l'applicazione di Google Plus foto. Altre colture potrebbero non funzionare. + + * `Camera.PictureSourceType.PHOTOLIBRARY`e `Camera.PictureSourceType.SAVEDPHOTOALBUM` entrambi visualizzare l'album fotografico stesso. + +#### BlackBerry 10 capricci + + * Ignora il `quality` parametro. + + * Ignora il `allowEdit` parametro. + + * `Camera.MediaType`non è supportato. + + * Ignora il `correctOrientation` parametro. + + * Ignora il `cameraDirection` parametro. + +#### Firefox OS stranezze + + * Ignora il `quality` parametro. + + * `Camera.DestinationType`viene ignorato e corrisponde a `1` (URI del file di immagine) + + * Ignora il `allowEdit` parametro. + + * Ignora il `PictureSourceType` parametro (utente ne sceglie in una finestra di dialogo) + + * Ignora il`encodingType` + + * Ignora le `targetWidth` e`targetHeight` + + * `Camera.MediaType`non è supportato. + + * Ignora il `correctOrientation` parametro. + + * Ignora il `cameraDirection` parametro. + +#### iOS stranezze + + * Impostare `quality` inferiore al 50 per evitare errori di memoria su alcuni dispositivi. + + * Quando si utilizza `destinationType.FILE_URI` , foto vengono salvati nella directory temporanea dell'applicazione. Il contenuto della directory temporanea dell'applicazione viene eliminato quando l'applicazione termina. + +#### Tizen stranezze + + * opzioni non supportate + + * restituisce sempre un URI del FILE + +#### Windows Phone 7 e 8 stranezze + + * Ignora il `allowEdit` parametro. + + * Ignora il `correctOrientation` parametro. + + * Ignora il `cameraDirection` parametro. + + * Ignora il `saveToPhotoAlbum` parametro. IMPORTANTE: Tutte le immagini scattate con la fotocamera di cordova wp7/8 API vengono sempre copiate rotolo fotocamera del telefono cellulare. A seconda delle impostazioni dell'utente, questo potrebbe anche significare che l'immagine viene caricato in automatico a loro OneDrive. Questo potenzialmente potrebbe significare che l'immagine è disponibile a un pubblico più ampio di app destinate. Se questo un blocco dell'applicazione, sarà necessario implementare il CameraCaptureTask come documentato su msdn: si può anche commentare o up-voto la questione correlata nel [tracciatore di problemi](https://issues.apache.org/jira/browse/CB-2083) + + * Ignora la `mediaType` proprietà di `cameraOptions` come il SDK di Windows Phone non fornisce un modo per scegliere il video da PHOTOLIBRARY. + +## CameraError + +funzione di callback onError che fornisce un messaggio di errore. + + function(message) { + // Show a helpful message + } + + +#### Descrizione + + * **message**: il messaggio è fornito dal codice nativo del dispositivo. *(String)* + +## cameraSuccess + +funzione di callback onSuccess che fornisce i dati di immagine. + + function(imageData) { + // Do something with the image + } + + +#### Descrizione + + * **imageData**: Base64 codifica dei dati immagine, *o* il file di immagine URI, a seconda `cameraOptions` in vigore. *(String)* + +#### Esempio + + // Show image + // + function cameraCallback(imageData) { + var image = document.getElementById('myImage'); + image.src = "data:image/jpeg;base64," + imageData; + } + + +## CameraPopoverHandle + +Un handle per la finestra di dialogo di muffin creato da `navigator.camera.getPicture`. + +#### Descrizione + + * **setPosition**: Set the position of the popover. Takes the `CameraPopoverOptions` that specify the new position. + +#### Piattaforme supportate + +![](doc/img/android-fail.png) ![](doc/img/blackberry-fail.png) ![](doc/img/browser-fail.png) ![](doc/img/firefox-fail.png) ![](doc/img/fireos-fail.png) ![](doc/img/ios-success.png) ![](doc/img/windows-fail.png) ![](doc/img/wp8-fail.png) ![](doc/img/ubuntu-fail.png) + +#### Esempio + + var cameraPopoverHandle = navigator.camera.getPicture(onSuccess, onFail, + { destinationType: Camera.DestinationType.FILE_URI, + sourceType: Camera.PictureSourceType.PHOTOLIBRARY, + popoverOptions: new CameraPopoverOptions(300, 300, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY) + }); + + // Reposition the popover if the orientation changes. + window.onorientationchange = function() { + var cameraPopoverOptions = new CameraPopoverOptions(0, 0, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY); + cameraPopoverHandle.setPosition(cameraPopoverOptions); + } + + +## CameraPopoverOptions + +iOS solo parametri che specificano l'ancoraggio elemento posizione e freccia direzione il Muffin quando si selezionano le immagini dalla libreria un iPad o un album. + + { x : 0, + y : 32, + width : 320, + height : 480, + arrowDir : Camera.PopoverArrowDirection.ARROW_ANY + }; + + +#### Descrizione + + * **x**: pixel coordinata x dell'elemento dello schermo su cui ancorare il muffin. *(Numero)* + + * **y**: coordinata y di pixel dell'elemento dello schermo su cui ancorare il muffin. *(Numero)* + + * **width**: larghezza, in pixel, dell'elemento dello schermo su cui ancorare il muffin. *(Numero)* + + * **height**: altezza, in pixel, dell'elemento dello schermo su cui ancorare il muffin. *(Numero)* + + * **arrowDir**: direzione dovrebbe puntare la freccia il muffin. Definito in `Camera.PopoverArrowDirection` *(numero)* + + Camera.PopoverArrowDirection = { + ARROW_UP : 1, // matches iOS UIPopoverArrowDirection constants + ARROW_DOWN : 2, + ARROW_LEFT : 4, + ARROW_RIGHT : 8, + ARROW_ANY : 15 + }; + + +Si noti che la dimensione del muffin possa cambiare per regolare la direzione della freccia e l'orientamento dello schermo. Assicurarsi che tenere conto di modifiche di orientamento quando si specifica la posizione di elemento di ancoraggio. + +## navigator.camera.cleanup + +Rimuove intermedio foto scattate con la fotocamera da deposito temporaneo. + + navigator.camera.cleanup( cameraSuccess, cameraError ); + + +#### Descrizione + +Rimuove i file di immagine intermedia che vengono tenuti in custodia temporanea dopo la chiamata a `camera.getPicture`. Si applica solo quando il valore di `Camera.sourceType` è uguale a `Camera.PictureSourceType.CAMERA` e il `Camera.destinationType` è uguale a `Camera.DestinationType.FILE_URI`. + +#### Piattaforme supportate + +![](doc/img/android-fail.png) ![](doc/img/blackberry-fail.png) ![](doc/img/browser-fail.png) ![](doc/img/firefox-fail.png) ![](doc/img/fireos-fail.png) ![](doc/img/ios-success.png) ![](doc/img/windows-fail.png) ![](doc/img/wp8-fail.png) ![](doc/img/ubuntu-fail.png) + +#### Esempio + + navigator.camera.cleanup(onSuccess, onFail); + + function onSuccess() { + console.log("Camera cleanup success.") + } + + function onFail(message) { + alert('Failed because: ' + message); + } \ No newline at end of file diff --git a/plugins/cordova-plugin-camera/doc/it/index.md b/plugins/cordova-plugin-camera/doc/it/index.md new file mode 100644 index 0000000..da0b919 --- /dev/null +++ b/plugins/cordova-plugin-camera/doc/it/index.md @@ -0,0 +1,434 @@ + + +# cordova-plugin-camera + +Questo plugin definisce un oggetto globale `navigator.camera`, che fornisce un'API per scattare foto e per aver scelto immagini dalla libreria di immagini del sistema. + +Anche se l'oggetto è associato con ambito globale del `navigator`, non è disponibile fino a dopo l'evento `deviceready`. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(navigator.camera); + } + + +## Installazione + + cordova plugin add cordova-plugin-camera + + +## navigator.camera.getPicture + +Prende una foto utilizzando la fotocamera, o recupera una foto dalla galleria di immagini del dispositivo. L'immagine è passata al callback di successo come `String` con codifica base64, o come l'URI per il file di immagine. Lo stesso metodo restituisce un oggetto `CameraPopoverHandle` che può essere utilizzato per riposizionare il Muffin di selezione file. + + navigator.camera.getPicture( cameraSuccess, cameraError, cameraOptions ); + + +### Descrizione + +La funzione `camera.getPicture` apre predefinito fotocamera applicazione il dispositivo che consente agli utenti di scattare foto. Questo comportamento si verifica per impostazione predefinita, quando `Camera.sourceType` è uguale a `Camera.PictureSourceType.CAMERA`. Una volta che l'utente scatta la foto, si chiude l'applicazione fotocamera e l'applicazione viene ripristinato. + +Se `Camera.sourceType` è `Camera.PictureSourceType.PHOTOLIBRARY` o `Camera.PictureSourceType.SAVEDPHOTOALBUM`, una finestra di dialogo Visualizza che permette agli utenti di selezionare un'immagine esistente. La funzione `camera.getPicture` restituisce un oggetto `CameraPopoverHandle` che può essere utilizzato per riposizionare la finestra di selezione immagine, ad esempio, quando l'orientamento del dispositivo. + +Il valore restituito viene inviato alla funzione di callback `cameraSuccess`, in uno dei seguenti formati, a seconda il `cameraOptions` specificato: + +* A `String` contenente l'immagine della foto con codifica base64. + +* A `String` che rappresenta il percorso del file di immagine su archiviazione locale (predefinito). + +Si può fare quello che vuoi con l'immagine codificata o URI, ad esempio: + +* Il rendering dell'immagine in un `` tag, come nell'esempio qui sotto + +* Salvare i dati localmente ( `LocalStorage` , [Lawnchair][1], ecc.) + +* Inviare i dati a un server remoto + + [1]: http://brianleroux.github.com/lawnchair/ + +**Nota**: risoluzione foto sui più recenti dispositivi è abbastanza buona. Foto selezionate dalla galleria del dispositivo non è percepiranno di qualità inferiore, anche se viene specificato un parametro di `quality`. Per evitare problemi di memoria comune, impostare `Camera.destinationType` `FILE_URI` piuttosto che `DATA_URL`. + +### Piattaforme supportate + +* Amazon fuoco OS +* Android +* BlackBerry 10 +* Browser +* Firefox OS +* iOS +* Tizen +* Windows Phone 7 e 8 +* Windows 8 + +### Preferenze (iOS) + +* **CameraUsesGeolocation** (boolean, default è false). Per l'acquisizione di immagini JPEG, impostato su true per ottenere dati di geolocalizzazione nell'intestazione EXIF. Questo innescherà una richiesta per le autorizzazioni di geolocalizzazione, se impostato su true. + + + + +### Amazon fuoco OS stranezze + +Amazon fuoco OS utilizza intenti a lanciare l'attività della fotocamera sul dispositivo per catturare immagini e sui telefoni con poca memoria, l'attività di Cordova può essere ucciso. In questo scenario, l'immagine potrebbe non apparire quando viene ripristinata l'attività di cordova. + +### Stranezze Android + +Android utilizza intenti a lanciare l'attività della fotocamera sul dispositivo per catturare immagini e sui telefoni con poca memoria, l'attività di Cordova può essere ucciso. In questo scenario, l'immagine potrebbe non apparire quando viene ripristinata l'attività di Cordova. + +### Stranezze browser + +Può restituire solo la foto come immagine con codifica base64. + +### Firefox OS stranezze + +Fotocamera plugin è attualmente implementato mediante [Web Activities][2]. + + [2]: https://hacks.mozilla.org/2013/01/introducing-web-activities/ + +### iOS stranezze + +Compreso un JavaScript `alert()` in una delle funzioni di callback può causare problemi. Avvolgere l'avviso all'interno di un `setTimeout()` per consentire la selezione immagine iOS o muffin per chiudere completamente la prima che viene visualizzato l'avviso: + + setTimeout(function() { + // do your thing here! + }, 0); + + +### Windows Phone 7 stranezze + +Richiamando l'applicazione nativa fotocamera mentre il dispositivo è collegato tramite Zune non funziona e innesca un callback di errore. + +### Tizen stranezze + +Tizen supporta solo a `destinationType` di `Camera.DestinationType.FILE_URI` e un `sourceType` di `Camera.PictureSourceType.PHOTOLIBRARY`. + +### Esempio + +Scattare una foto e recuperarla come un'immagine con codifica base64: + + navigator.camera.getPicture(onSuccess, onFail, { quality: 50, + destinationType: Camera.DestinationType.DATA_URL + }); + + function onSuccess(imageData) { + var image = document.getElementById('myImage'); + image.src = "data:image/jpeg;base64," + imageData; + } + + function onFail(message) { + alert('Failed because: ' + message); + } + + +Scattare una foto e recuperare il percorso del file dell'immagine: + + navigator.camera.getPicture(onSuccess, onFail, { quality: 50, + destinationType: Camera.DestinationType.FILE_URI }); + + function onSuccess(imageURI) { + var image = document.getElementById('myImage'); + image.src = imageURI; + } + + function onFail(message) { + alert('Failed because: ' + message); + } + + +## CameraOptions + +Parametri opzionali per personalizzare le impostazioni della fotocamera. + + { quality : 75, + destinationType : Camera.DestinationType.DATA_URL, + sourceType : Camera.PictureSourceType.CAMERA, + allowEdit : true, + encodingType: Camera.EncodingType.JPEG, + targetWidth: 100, + targetHeight: 100, + popoverOptions: CameraPopoverOptions, + saveToPhotoAlbum: false }; + + +### Opzioni + +* **quality**: qualità dell'immagine salvata, espressa come un intervallo di 0-100, dove 100 è tipicamente piena risoluzione senza perdita di compressione file. Il valore predefinito è 50. *(Numero)* (Si noti che informazioni sulla risoluzione della fotocamera non sono disponibile). + +* **destinationType**: Scegli il formato del valore restituito. Il valore predefinito è FILE_URI. Definito in `navigator.camera.DestinationType` *(numero)* + + Camera.DestinationType = { + DATA_URL : 0, // Return image as base64-encoded string + FILE_URI : 1, // Return image file URI + NATIVE_URI : 2 // Return image native URI (e.g., assets-library:// on iOS or content:// on Android) + }; + + +* **sourceType**: impostare l'origine dell'immagine. Il valore predefinito è la fotocamera. Definito in `navigator.camera.PictureSourceType` *(numero)* + + Camera.PictureSourceType = { + PHOTOLIBRARY : 0, + CAMERA : 1, + SAVEDPHOTOALBUM : 2 + }; + + +* **Proprietà allowEdit**: consentire la semplice modifica dell'immagine prima di selezione. *(Booleano)* + +* **encodingType**: scegliere il file immagine restituita di codifica. Predefinito è JPEG. Definito in `navigator.camera.EncodingType` *(numero)* + + Camera.EncodingType = { + JPEG : 0, // Return JPEG encoded image + PNG : 1 // Return PNG encoded image + }; + + +* **targetWidth**: larghezza in pixel all'immagine della scala. Deve essere usato con **targetHeight**. Proporzioni rimane costante. *(Numero)* + +* **targetHeight**: altezza in pixel all'immagine della scala. Deve essere usato con **targetWidth**. Proporzioni rimane costante. *(Numero)* + +* **mediaType**: impostare il tipo di supporto per scegliere da. Funziona solo quando `PictureSourceType` è `PHOTOLIBRARY` o `SAVEDPHOTOALBUM` . Definito in `nagivator.camera.MediaType` *(numero)* + + Camera.MediaType = { + PICTURE: 0, // allow selection of still pictures only. PER IMPOSTAZIONE PREDEFINITA. Will return format specified via DestinationType + VIDEO: 1, // allow selection of video only, WILL ALWAYS RETURN FILE_URI + ALLMEDIA : 2 // allow selection from all media types + }; + + +* **correctOrientation**: ruotare l'immagine per correggere l'orientamento del dispositivo durante l'acquisizione. *(Booleano)* + +* **saveToPhotoAlbum**: salvare l'immagine nell'album di foto sul dispositivo dopo la cattura. *(Booleano)* + +* **popoverOptions**: solo iOS opzioni che specificano la posizione di muffin in iPad. Definito in`CameraPopoverOptions`. + +* **cameraDirection**: scegliere la telecamera da utilizzare (o retro-frontale). Il valore predefinito è tornato. Definito in `navigator.camera.Direction` *(numero)* + + Camera.Direction = { + BACK : 0, // Use the back-facing camera + FRONT : 1 // Use the front-facing camera + }; + + +### Amazon fuoco OS stranezze + +* Qualsiasi `cameraDirection` valore i risultati in una foto di lamatura. + +* Ignora il `allowEdit` parametro. + +* `Camera.PictureSourceType.PHOTOLIBRARY`e `Camera.PictureSourceType.SAVEDPHOTOALBUM` entrambi visualizzare l'album fotografico stesso. + +### Stranezze Android + +* Qualsiasi `cameraDirection` valore i risultati in una foto di lamatura. + +* Ignora il `allowEdit` parametro. + +* `Camera.PictureSourceType.PHOTOLIBRARY`e `Camera.PictureSourceType.SAVEDPHOTOALBUM` entrambi visualizzare l'album fotografico stesso. + +### BlackBerry 10 capricci + +* Ignora il `quality` parametro. + +* Ignora il `allowEdit` parametro. + +* `Camera.MediaType`non è supportato. + +* Ignora il `correctOrientation` parametro. + +* Ignora il `cameraDirection` parametro. + +### Firefox OS stranezze + +* Ignora il `quality` parametro. + +* `Camera.DestinationType`viene ignorato e corrisponde a `1` (URI del file di immagine) + +* Ignora il `allowEdit` parametro. + +* Ignora il `PictureSourceType` parametro (utente ne sceglie in una finestra di dialogo) + +* Ignora il`encodingType` + +* Ignora le `targetWidth` e`targetHeight` + +* `Camera.MediaType`non è supportato. + +* Ignora il `correctOrientation` parametro. + +* Ignora il `cameraDirection` parametro. + +### iOS stranezze + +* Impostare `quality` inferiore al 50 per evitare errori di memoria su alcuni dispositivi. + +* Quando si utilizza `destinationType.FILE_URI` , foto vengono salvati nella directory temporanea dell'applicazione. Il contenuto della directory temporanea dell'applicazione viene eliminato quando l'applicazione termina. + +### Tizen stranezze + +* opzioni non supportate + +* restituisce sempre un URI del FILE + +### Windows Phone 7 e 8 stranezze + +* Ignora il `allowEdit` parametro. + +* Ignora il `correctOrientation` parametro. + +* Ignora il `cameraDirection` parametro. + +* Ignora il `saveToPhotoAlbum` parametro. IMPORTANTE: Tutte le immagini scattate con la fotocamera di cordova wp7/8 API vengono sempre copiate rotolo fotocamera del telefono cellulare. A seconda delle impostazioni dell'utente, questo potrebbe anche significare che l'immagine viene caricato in automatico a loro OneDrive. Questo potenzialmente potrebbe significare che l'immagine è disponibile a un pubblico più ampio di app destinate. Se questo un blocco dell'applicazione, sarà necessario implementare il CameraCaptureTask come documentato su msdn: si può anche commentare o up-voto la questione correlata nel [tracciatore di problemi][3] + +* Ignora la `mediaType` proprietà di `cameraOptions` come il SDK di Windows Phone non fornisce un modo per scegliere il video da PHOTOLIBRARY. + + [3]: https://issues.apache.org/jira/browse/CB-2083 + +## CameraError + +funzione di callback onError che fornisce un messaggio di errore. + + function(message) { + // Show a helpful message + } + + +### Parametri + +* **message**: il messaggio è fornito dal codice nativo del dispositivo. *(String)* + +## cameraSuccess + +funzione di callback onSuccess che fornisce i dati di immagine. + + function(imageData) { + // Do something with the image + } + + +### Parametri + +* **imageData**: Base64 codifica dei dati immagine, *o* il file di immagine URI, a seconda `cameraOptions` in vigore. *(String)* + +### Esempio + + // Show image + // + function cameraCallback(imageData) { + var image = document.getElementById('myImage'); + image.src = "data:image/jpeg;base64," + imageData; + } + + +## CameraPopoverHandle + +Un handle per la finestra di dialogo di muffin creato da `navigator.camera.getPicture`. + +### Metodi + +* **setPosition**: impostare la posizione dei muffin. + +### Piattaforme supportate + +* iOS + +### setPosition + +Impostare la posizione dei muffin. + +**Parametri**: + +* `cameraPopoverOptions`: il `CameraPopoverOptions` che specificare la nuova posizione + +### Esempio + + var cameraPopoverHandle = navigator.camera.getPicture(onSuccess, onFail, + { destinationType: Camera.DestinationType.FILE_URI, + sourceType: Camera.PictureSourceType.PHOTOLIBRARY, + popoverOptions: new CameraPopoverOptions(300, 300, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY) + }); + + // Reposition the popover if the orientation changes. + window.onorientationchange = function() { + var cameraPopoverOptions = new CameraPopoverOptions(0, 0, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY); + cameraPopoverHandle.setPosition(cameraPopoverOptions); + } + + +## CameraPopoverOptions + +iOS solo parametri che specificano l'ancoraggio elemento posizione e freccia direzione il Muffin quando si selezionano le immagini dalla libreria un iPad o un album. + + { x : 0, + y : 32, + width : 320, + height : 480, + arrowDir : Camera.PopoverArrowDirection.ARROW_ANY + }; + + +### CameraPopoverOptions + +* **x**: pixel coordinata x dell'elemento dello schermo su cui ancorare il muffin. *(Numero)* + +* **y**: coordinata y di pixel dell'elemento dello schermo su cui ancorare il muffin. *(Numero)* + +* **width**: larghezza, in pixel, dell'elemento dello schermo su cui ancorare il muffin. *(Numero)* + +* **height**: altezza, in pixel, dell'elemento dello schermo su cui ancorare il muffin. *(Numero)* + +* **arrowDir**: direzione dovrebbe puntare la freccia il muffin. Definito in `Camera.PopoverArrowDirection` *(numero)* + + Camera.PopoverArrowDirection = { + ARROW_UP : 1, // matches iOS UIPopoverArrowDirection constants + ARROW_DOWN : 2, + ARROW_LEFT : 4, + ARROW_RIGHT : 8, + ARROW_ANY : 15 + }; + + +Si noti che la dimensione del muffin possa cambiare per regolare la direzione della freccia e l'orientamento dello schermo. Assicurarsi che tenere conto di modifiche di orientamento quando si specifica la posizione di elemento di ancoraggio. + +## navigator.camera.cleanup + +Rimuove intermedio foto scattate con la fotocamera da deposito temporaneo. + + navigator.camera.cleanup( cameraSuccess, cameraError ); + + +### Descrizione + +Rimuove i file di immagine intermedia che vengono tenuti in custodia temporanea dopo la chiamata a `camera.getPicture`. Si applica solo quando il valore di `Camera.sourceType` è uguale a `Camera.PictureSourceType.CAMERA` e il `Camera.destinationType` è uguale a `Camera.DestinationType.FILE_URI`. + +### Piattaforme supportate + +* iOS + +### Esempio + + navigator.camera.cleanup(onSuccess, onFail); + + function onSuccess() { + console.log("Camera cleanup success.") + } + + function onFail(message) { + alert('Failed because: ' + message); + } diff --git a/plugins/cordova-plugin-camera/doc/ja/README.md b/plugins/cordova-plugin-camera/doc/ja/README.md new file mode 100644 index 0000000..a50c185 --- /dev/null +++ b/plugins/cordova-plugin-camera/doc/ja/README.md @@ -0,0 +1,421 @@ + + +# cordova-plugin-camera + +[![Build Status](https://travis-ci.org/apache/cordova-plugin-camera.svg)](https://travis-ci.org/apache/cordova-plugin-camera) + +このプラグインは、写真を撮るため、システムのイメージ ライブラリからイメージを選択するために API を提供します、グローバル `navigator.camera` オブジェクトを定義します。 + +オブジェクトは、グローバル スコープの `ナビゲーター` に添付、それがないまで `deviceready` イベントの後。 + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(navigator.camera); + } + + +## インストール + + cordova plugin add cordova-plugin-camera + + +## API + + * カメラ + * navigator.camera.getPicture(success, fail, options) + * CameraOptions + * CameraPopoverHandle + * CameraPopoverOptions + * navigator.camera.cleanup + +## navigator.camera.getPicture + +カメラを使用して写真を取るか、デバイスの画像ギャラリーから写真を取得します。 イメージが渡されます成功時のコールバックを base64 エンコードされた `文字列`、または、URI としてイメージ ファイル。 メソッド自体はファイル選択ポップ オーバーの位置を変更するために使用できる `CameraPopoverHandle` オブジェクトを返します。 + + navigator.camera.getPicture(cameraSuccess, cameraError, cameraOptions); + + +#### 解説 + +`camera.getPicture` 関数は、ユーザーの写真をスナップすることができますデバイスのデフォルト カメラ アプリケーションを開きます。 `Camera.sourceType` が `Camera.PictureSourceType.CAMERA` と等しい場合既定では、この現象が発生します。 ユーザーは写真をスナップ、カメラ アプリケーションを閉じるし、アプリケーションが復元されます。 + +`Camera.sourceType` `Camera.PictureSourceType.PHOTOLIBRARY` または `Camera.PictureSourceType.SAVEDPHOTOALBUM` の場合、ダイアログ ボックスはユーザーを既存のイメージを選択することができますが表示されます。 `camera.getPicture` 関数は、デバイスの向きが変更されたとき、たとえば、イメージの選択ダイアログには、位置を変更するために使用することができます、`CameraPopoverHandle` オブジェクトを返します。 + +戻り値が `cameraSuccess` コールバック関数の指定 `cameraOptions` に応じて、次の形式のいずれかに送信されます。 + + * A `String` 写真の base64 でエンコードされたイメージを含んでいます。 + + * A `String` (既定値) のローカル記憶域上のイメージ ファイルの場所を表します。 + +自由に変更、エンコードされたイメージ、または URI などを行うことができます。 + + * イメージをレンダリングする `` 以下の例のように、タグ + + * ローカル データの保存 ( `LocalStorage` 、 [Lawnchair](http://brianleroux.github.com/lawnchair/)など)。 + + * リモート サーバーにデータを投稿します。 + +**注**: 新しいデバイス上の写真の解像度はかなり良いです。 デバイスのギャラリーから選択した写真は `quality` パラメーターが指定されて場合でも下方の品質に縮小されません。 一般的なメモリの問題を避けるために `DATA_URL` ではなく `FILE_URI` に `Camera.destinationType` を設定します。. + +#### サポートされているプラットフォーム + +![](doc/img/android-success.png) ![](doc/img/blackberry-success.png) ![](doc/img/browser-success.png) ![](doc/img/firefox-success.png) ![](doc/img/fireos-success.png) ![](doc/img/ios-success.png) ![](doc/img/windows-success.png) ![](doc/img/wp8-success.png) ![](doc/img/ubuntu-success.png) + +#### 例 + +写真を撮るし、base64 エンコード イメージとして取得します。 + + navigator.camera.getPicture(onSuccess, onFail, { quality: 50, + destinationType: Camera.DestinationType.DATA_URL + }); + + function onSuccess(imageData) { + var image = document.getElementById('myImage'); + image.src = "data:image/jpeg;base64," + imageData; + } + + function onFail(message) { + alert('Failed because: ' + message); + } + + +写真を撮るし、イメージのファイルの場所を取得します。 + + navigator.camera.getPicture(onSuccess, onFail, { quality: 50, + destinationType: Camera.DestinationType.FILE_URI }); + + function onSuccess(imageURI) { + var image = document.getElementById('myImage'); + image.src = imageURI; + } + + function onFail(message) { + alert('Failed because: ' + message); + } + + +#### 環境設定 (iOS) + + * **CameraUsesGeolocation**(ブール値、デフォルトは false)。 Jpeg 画像をキャプチャするため EXIF ヘッダーで地理位置情報データを取得する場合は true に設定します。 これは、場合地理位置情報のアクセス許可に対する要求をトリガーする true に設定します。 + + + + +#### アマゾン火 OS 癖 + +アマゾン火 OS イメージをキャプチャするデバイス上のカメラの活動を開始する意図を使用して、メモリの少ない携帯電話、コルドバ活動が殺されるかもしれない。 このシナリオではコルドバ活動が復元されると、イメージが表示されません。 + +#### Android の癖 + +アンドロイド、イメージをキャプチャするデバイス上でカメラのアクティビティを開始する意図を使用し、メモリの少ない携帯電話、コルドバ活動が殺されるかもしれない。 このシナリオではコルドバ活動が復元されると、イメージが表示されません。 + +#### ブラウザーの癖 + +Base64 エンコード イメージとして写真を返すのみことができます。 + +#### Firefox OS 癖 + +カメラのプラグインは現在、[Web アクティビティ](https://hacks.mozilla.org/2013/01/introducing-web-activities/) を使用して実装されていた. + +#### iOS の癖 + +コールバック関数のいずれかの JavaScript `alert()` を含む問題が発生することができます。 IOS イメージ ピッカーまたは完全が終了するまで、警告が表示されますポップ オーバーを許可する `setTimeout()` 内でアラートをラップします。 + + setTimeout(function() { + // do your thing here! + }, 0); + + +#### Windows Phone 7 の癖 + +ネイティブ カメラ アプリケーションを呼び出すと、デバイスが Zune を介して接続されている動作しませんし、エラー コールバックをトリガーします。 + +#### Tizen の癖 + +Tizen のみ `Camera.DestinationType.FILE_URI` の `destinationType` と `Camera.PictureSourceType.PHOTOLIBRARY` の `sourceType` をサポートしています. + +## CameraOptions + +カメラの設定をカスタマイズするオプションのパラメーター。 + + { quality : 75, + destinationType : Camera.DestinationType.DATA_URL, + sourceType : Camera.PictureSourceType.CAMERA, + allowEdit : true, + encodingType: Camera.EncodingType.JPEG, + targetWidth: 100, + targetHeight: 100, + popoverOptions: CameraPopoverOptions, + saveToPhotoAlbum: false }; + + + * **quality**: 0-100、100 がファイルの圧縮から損失なしで通常のフル解像度の範囲で表される、保存されたイメージの品質。 既定値は 50 です。 *(数)*(カメラの解像度についての情報が利用できないことに注意してください)。 + + * **destinationType**: 戻り値の形式を選択します。既定値は FILE_URI です。定義されている `navigator.camera.DestinationType` *(番号)* + + Camera.DestinationType = { + DATA_URL : 0, // Return image as base64-encoded string + FILE_URI : 1, // Return image file URI + NATIVE_URI : 2 // Return image native URI (e.g., assets-library:// on iOS or content:// on Android) + }; + + + * **sourceType**: 画像のソースを設定します。既定値は、カメラです。定義されている `navigator.camera.PictureSourceType` *(番号)* + + Camera.PictureSourceType = { + PHOTOLIBRARY : 0, + CAMERA : 1, + SAVEDPHOTOALBUM : 2 + }; + + + * **allowEdit**: 単純な選択の前に画像の編集を許可します。*(ブール値)* + + * **encodingType**: 返されるイメージ ファイルのエンコーディングを選択します。デフォルトは JPEG です。定義されている `navigator.camera.EncodingType` *(番号)* + + Camera.EncodingType = { + JPEG : 0, // Return JPEG encoded image + PNG : 1 // Return PNG encoded image + }; + + + * **targetWidth**: スケール イメージにピクセル単位の幅。**TargetHeight**を使用する必要があります。縦横比は変わりません。*(数)* + + * **targetHeight**: スケール イメージにピクセル単位の高さ。**TargetWidth**を使用する必要があります。縦横比は変わりません。*(数)* + + * **mediaType**: から選択するメディアの種類を設定します。 場合にのみ働きます `PictureSourceType` は `PHOTOLIBRARY` または `SAVEDPHOTOALBUM` 。 定義されている `nagivator.camera.MediaType` *(番号)* + + Camera.MediaType = { + PICTURE: 0, // allow selection of still pictures only. DEFAULT. Will return format specified via DestinationType + VIDEO: 1, // allow selection of video only, WILL ALWAYS RETURN FILE_URI + ALLMEDIA : 2 // allow selection from all media types + }; + + + * **correctOrientation**: キャプチャ中に、デバイスの向きを修正する画像を回転させます。*(ブール値)* + + * **saveToPhotoAlbum**: キャプチャ後、デバイス上のフォト アルバムに画像を保存します。*(ブール値)* + + * **popoverOptions**: iPad のポップ オーバーの場所を指定する iOS のみのオプションです。定義されています。`CameraPopoverOptions`. + + * **cameraDirection**: (前面または背面側) を使用するカメラを選択します。既定値は戻るです。定義されている `navigator.camera.Direction` *(番号)* + + Camera.Direction = { + BACK : 0, // Use the back-facing camera + FRONT : 1 // Use the front-facing camera + }; + + +#### アマゾン火 OS 癖 + + * 任意 `cameraDirection` 背面写真で結果の値します。 + + * 無視、 `allowEdit` パラメーター。 + + * `Camera.PictureSourceType.PHOTOLIBRARY``Camera.PictureSourceType.SAVEDPHOTOALBUM`両方のアルバムが表示されます同じ写真。 + +#### Android の癖 + + * 任意 `cameraDirection` 背面写真で結果の値します。 + + * アンドロイドも使用しています作物活性、allowEdit もトリミングする必要があります動作し、実際にトリミングされた画像をコルドバで 1 つだけの作品一貫して Google プラス写真アプリケーションにバンドルされているものであることに渡します。 他の作物が機能しません。 + + * `Camera.PictureSourceType.PHOTOLIBRARY``Camera.PictureSourceType.SAVEDPHOTOALBUM`両方のアルバムが表示されます同じ写真。 + +#### ブラックベリー 10 癖 + + * 無視、 `quality` パラメーター。 + + * 無視、 `allowEdit` パラメーター。 + + * `Camera.MediaType`サポートされていません。 + + * 無視、 `correctOrientation` パラメーター。 + + * 無視、 `cameraDirection` パラメーター。 + +#### Firefox OS 癖 + + * 無視、 `quality` パラメーター。 + + * `Camera.DestinationType`無視され、等しい `1` (イメージ ファイル URI) + + * 無視、 `allowEdit` パラメーター。 + + * 無視、 `PictureSourceType` パラメーター (ユーザーが選択ダイアログ ウィンドウに) + + * 無視します、`encodingType` + + * 無視、 `targetWidth` と`targetHeight` + + * `Camera.MediaType`サポートされていません。 + + * 無視、 `correctOrientation` パラメーター。 + + * 無視、 `cameraDirection` パラメーター。 + +#### iOS の癖 + + * 設定 `quality` 一部のデバイスでメモリ不足エラーを避けるために 50 の下。 + + * 使用する場合 `destinationType.FILE_URI` 、写真、アプリケーションの一時ディレクトリに保存されます。アプリケーションの一時ディレクトリの内容は、アプリケーションの終了時に削除されます。 + +#### Tizen の癖 + + * サポートされていないオプション + + * 常にファイルの URI を返す + +#### Windows Phone 7 と 8 癖 + + * 無視、 `allowEdit` パラメーター。 + + * 無視、 `correctOrientation` パラメーター。 + + * 無視、 `cameraDirection` パラメーター。 + + * 無視、 `saveToPhotoAlbum` パラメーター。 重要: wp7/8 コルドバ カメラ API で撮影したすべての画像は携帯電話のカメラ巻き物に常にコピーします。 ユーザーの設定に応じて、これも、画像はその OneDrive に自動アップロードを意味できます。 イメージは意図したアプリより広い聴衆に利用できる可能性があります可能性があります。 場合は、このアプリケーションのブロッカー、msdn で説明されているように、CameraCaptureTask を実装する必要があります: コメントにすることがありますもかアップ投票関連の問題を[課題追跡システム](https://issues.apache.org/jira/browse/CB-2083)で + + * 無視、 `mediaType` のプロパティ `cameraOptions` として Windows Phone SDK には、フォト ライブラリからビデオを選択する方法は行いません。 + +## CameraError + +エラー メッセージを提供する onError コールバック関数。 + + function(message) { + // Show a helpful message + } + + +#### 解説 + + * **message**: メッセージは、デバイスのネイティブ コードによって提供されます。*(文字列)* + +## cameraSuccess + +画像データを提供する onSuccess コールバック関数。 + + function(imageData) { + // Do something with the image + } + + +#### 解説 + + * **imagedata を扱う**: Base64 エンコード イメージのデータ、*または*画像ファイルによって URI の `cameraOptions` 効果。*(文字列)* + +#### 例 + + // Show image + // + function cameraCallback(imageData) { + var image = document.getElementById('myImage'); + image.src = "data:image/jpeg;base64," + imageData; + } + + +## CameraPopoverHandle + +`Navigator.camera.getPicture` によって作成されたポップオーバーパン ダイアログ ボックスへのハンドル. + +#### 解説 + + * **setPosition**: Set the position of the popover. Takes the `CameraPopoverOptions` that specify the new position. + +#### サポートされているプラットフォーム + +![](doc/img/android-fail.png) ![](doc/img/blackberry-fail.png) ![](doc/img/browser-fail.png) ![](doc/img/firefox-fail.png) ![](doc/img/fireos-fail.png) ![](doc/img/ios-success.png) ![](doc/img/windows-fail.png) ![](doc/img/wp8-fail.png) ![](doc/img/ubuntu-fail.png) + +#### 例 + + var cameraPopoverHandle = navigator.camera.getPicture(onSuccess, onFail, + { destinationType: Camera.DestinationType.FILE_URI, + sourceType: Camera.PictureSourceType.PHOTOLIBRARY, + popoverOptions: new CameraPopoverOptions(300, 300, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY) + }); + + // Reposition the popover if the orientation changes. + window.onorientationchange = function() { + var cameraPopoverOptions = new CameraPopoverOptions(0, 0, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY); + cameraPopoverHandle.setPosition(cameraPopoverOptions); + } + + +## CameraPopoverOptions + +iOS だけ指定パラメーターをポップ オーバーのアンカー要素の場所および矢印方向計算されたライブラリまたはアルバムから画像を選択するとき。 + + { x : 0, + y : 32, + width : 320, + height : 480, + arrowDir : Camera.PopoverArrowDirection.ARROW_ANY + }; + + +#### 解説 + + * **x**: ピクセルの x 座標画面要素にポップ オーバーのアンカーになります。*(数)* + + * **y**: y ピクセル座標の画面要素にポップ オーバーのアンカーになります。*(数)* + + * **width**: ポップ オーバーのアンカーになる上の画面要素のピクセル単位の幅。*(数)* + + * **height**: ポップ オーバーのアンカーになる上の画面要素のピクセル単位の高さ。*(数)* + + * **arrowDir**: 方向のポップ オーバーで矢印をポイントする必要があります。定義されている `Camera.PopoverArrowDirection` *(番号)* + + Camera.PopoverArrowDirection = { + ARROW_UP : 1, // matches iOS UIPopoverArrowDirection constants + ARROW_DOWN : 2, + ARROW_LEFT : 4, + ARROW_RIGHT : 8, + ARROW_ANY : 15 + }; + + +矢印の方向と、画面の向きを調整するポップ オーバーのサイズを変更可能性がありますに注意してください。 アンカー要素の位置を指定するときの方向の変化を考慮することを確認します。 + +## navigator.camera.cleanup + +削除中間一時ストレージからカメラで撮影した写真。 + + navigator.camera.cleanup( cameraSuccess, cameraError ); + + +#### 解説 + +`camera.getPicture` を呼び出した後一時記憶域に保存されている中間画像ファイルを削除します。 `Camera.sourceType` の値が `Camera.PictureSourceType.CAMERA` に等しい、`Camera.destinationType` が `Camera.DestinationType.FILE_URI` と等しいの場合にのみ適用されます。. + +#### サポートされているプラットフォーム + +![](doc/img/android-fail.png) ![](doc/img/blackberry-fail.png) ![](doc/img/browser-fail.png) ![](doc/img/firefox-fail.png) ![](doc/img/fireos-fail.png) ![](doc/img/ios-success.png) ![](doc/img/windows-fail.png) ![](doc/img/wp8-fail.png) ![](doc/img/ubuntu-fail.png) + +#### 例 + + navigator.camera.cleanup(onSuccess, onFail); + + function onSuccess() { + console.log("Camera cleanup success.") + } + + function onFail(message) { + alert('Failed because: ' + message); + } \ No newline at end of file diff --git a/plugins/cordova-plugin-camera/doc/ja/index.md b/plugins/cordova-plugin-camera/doc/ja/index.md new file mode 100644 index 0000000..5bdb3e1 --- /dev/null +++ b/plugins/cordova-plugin-camera/doc/ja/index.md @@ -0,0 +1,434 @@ + + +# cordova-plugin-camera + +このプラグインは、写真を撮るため、システムのイメージ ライブラリからイメージを選択するために API を提供します、グローバル `navigator.camera` オブジェクトを定義します。 + +オブジェクトは、グローバル スコープの `ナビゲーター` に添付、それがないまで `deviceready` イベントの後。 + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(navigator.camera); + } + + +## インストール + + cordova plugin add cordova-plugin-camera + + +## navigator.camera.getPicture + +カメラを使用して写真を取るか、デバイスの画像ギャラリーから写真を取得します。 イメージが渡されます成功時のコールバックを base64 エンコードされた `文字列`、または、URI としてイメージ ファイル。 メソッド自体はファイル選択ポップ オーバーの位置を変更するために使用できる `CameraPopoverHandle` オブジェクトを返します。 + + navigator.camera.getPicture( cameraSuccess, cameraError, cameraOptions ); + + +### 解説 + +`camera.getPicture` 関数は、ユーザーの写真をスナップすることができますデバイスのデフォルト カメラ アプリケーションを開きます。 `Camera.sourceType` が `Camera.PictureSourceType.CAMERA` と等しい場合既定では、この現象が発生します。 ユーザーは写真をスナップ、カメラ アプリケーションを閉じるし、アプリケーションが復元されます。 + +`Camera.sourceType` `Camera.PictureSourceType.PHOTOLIBRARY` または `Camera.PictureSourceType.SAVEDPHOTOALBUM` の場合、ダイアログ ボックスはユーザーを既存のイメージを選択することができますが表示されます。 `camera.getPicture` 関数は、デバイスの向きが変更されたとき、たとえば、イメージの選択ダイアログには、位置を変更するために使用することができます、`CameraPopoverHandle` オブジェクトを返します。 + +戻り値が `cameraSuccess` コールバック関数の指定 `cameraOptions` に応じて、次の形式のいずれかに送信されます。 + +* A `String` 写真の base64 でエンコードされたイメージを含んでいます。 + +* A `String` (既定値) のローカル記憶域上のイメージ ファイルの場所を表します。 + +自由に変更、エンコードされたイメージ、または URI などを行うことができます。 + +* イメージをレンダリングする `` 以下の例のように、タグ + +* ローカル データの保存 ( `LocalStorage` 、 [Lawnchair][1]など)。 + +* リモート サーバーにデータを投稿します。 + + [1]: http://brianleroux.github.com/lawnchair/ + +**注**: 新しいデバイス上の写真の解像度はかなり良いです。 デバイスのギャラリーから選択した写真は `quality` パラメーターが指定されて場合でも下方の品質に縮小されません。 一般的なメモリの問題を避けるために `DATA_URL` ではなく `FILE_URI` に `Camera.destinationType` を設定します。. + +### サポートされているプラットフォーム + +* アマゾン火 OS +* アンドロイド +* ブラックベリー 10 +* ブラウザー +* Firefox の OS +* iOS +* Tizen +* Windows Phone 7 と 8 +* Windows 8 + +### 環境設定 (iOS) + +* **CameraUsesGeolocation**(ブール値、デフォルトは false)。 Jpeg 画像をキャプチャするため EXIF ヘッダーで地理位置情報データを取得する場合は true に設定します。 これは、場合地理位置情報のアクセス許可に対する要求をトリガーする true に設定します。 + + + + +### アマゾン火 OS 癖 + +アマゾン火 OS イメージをキャプチャするデバイス上のカメラの活動を開始する意図を使用して、メモリの少ない携帯電話、コルドバ活動が殺されるかもしれない。 このシナリオではコルドバ活動が復元されると、イメージが表示されません。 + +### Android の癖 + +アンドロイド、イメージをキャプチャするデバイス上でカメラのアクティビティを開始する意図を使用し、メモリの少ない携帯電話、コルドバ活動が殺されるかもしれない。 このシナリオではコルドバ活動が復元されると、イメージが表示されません。 + +### ブラウザーの癖 + +Base64 エンコード イメージとして写真を返すのみことができます。 + +### Firefox OS 癖 + +カメラのプラグインは現在、[Web アクティビティ][2] を使用して実装されていた. + + [2]: https://hacks.mozilla.org/2013/01/introducing-web-activities/ + +### iOS の癖 + +コールバック関数のいずれかの JavaScript `alert()` を含む問題が発生することができます。 IOS イメージ ピッカーまたは完全が終了するまで、警告が表示されますポップ オーバーを許可する `setTimeout()` 内でアラートをラップします。 + + setTimeout(function() { + // do your thing here! + }, 0); + + +### Windows Phone 7 の癖 + +ネイティブ カメラ アプリケーションを呼び出すと、デバイスが Zune を介して接続されている動作しませんし、エラー コールバックをトリガーします。 + +### Tizen の癖 + +Tizen のみ `Camera.DestinationType.FILE_URI` の `destinationType` と `Camera.PictureSourceType.PHOTOLIBRARY` の `sourceType` をサポートしています. + +### 例 + +写真を撮るし、base64 エンコード イメージとして取得します。 + + navigator.camera.getPicture(onSuccess, onFail, { quality: 50, + destinationType: Camera.DestinationType.DATA_URL + }); + + function onSuccess(imageData) { + var image = document.getElementById('myImage'); + image.src = "data:image/jpeg;base64," + imageData; + } + + function onFail(message) { + alert('Failed because: ' + message); + } + + +写真を撮るし、イメージのファイルの場所を取得します。 + + navigator.camera.getPicture(onSuccess, onFail, { quality: 50, + destinationType: Camera.DestinationType.FILE_URI }); + + function onSuccess(imageURI) { + var image = document.getElementById('myImage'); + image.src = imageURI; + } + + function onFail(message) { + alert('Failed because: ' + message); + } + + +## CameraOptions + +カメラの設定をカスタマイズするオプションのパラメーター。 + + { quality : 75, + destinationType : Camera.DestinationType.DATA_URL, + sourceType : Camera.PictureSourceType.CAMERA, + allowEdit : true, + encodingType: Camera.EncodingType.JPEG, + targetWidth: 100, + targetHeight: 100, + popoverOptions: CameraPopoverOptions, + saveToPhotoAlbum: false }; + + +### オプション + +* **quality**: 0-100、100 がファイルの圧縮から損失なしで通常のフル解像度の範囲で表される、保存されたイメージの品質。 既定値は 50 です。 *(数)*(カメラの解像度についての情報が利用できないことに注意してください)。 + +* **destinationType**: 戻り値の形式を選択します。既定値は FILE_URI です。定義されている `navigator.camera.DestinationType` *(番号)* + + Camera.DestinationType = { + DATA_URL : 0, // Return image as base64-encoded string + FILE_URI : 1, // Return image file URI + NATIVE_URI : 2 // Return image native URI (e.g., assets-library:// on iOS or content:// on Android) + }; + + +* **sourceType**: 画像のソースを設定します。既定値は、カメラです。定義されている `navigator.camera.PictureSourceType` *(番号)* + + Camera.PictureSourceType = { + PHOTOLIBRARY : 0, + CAMERA : 1, + SAVEDPHOTOALBUM : 2 + }; + + +* **allowEdit**: 単純な選択の前に画像の編集を許可します。*(ブール値)* + +* **encodingType**: 返されるイメージ ファイルのエンコーディングを選択します。デフォルトは JPEG です。定義されている `navigator.camera.EncodingType` *(番号)* + + Camera.EncodingType = { + JPEG : 0, // Return JPEG encoded image + PNG : 1 // Return PNG encoded image + }; + + +* **targetWidth**: スケール イメージにピクセル単位の幅。**TargetHeight**を使用する必要があります。縦横比は変わりません。*(数)* + +* **targetHeight**: スケール イメージにピクセル単位の高さ。**TargetWidth**を使用する必要があります。縦横比は変わりません。*(数)* + +* **mediaType**: から選択するメディアの種類を設定します。 場合にのみ働きます `PictureSourceType` は `PHOTOLIBRARY` または `SAVEDPHOTOALBUM` 。 定義されている `nagivator.camera.MediaType` *(番号)* + + Camera.MediaType = { + PICTURE: 0, // allow selection of still pictures only. DEFAULT. Will return format specified via DestinationType + VIDEO: 1, // allow selection of video only, WILL ALWAYS RETURN FILE_URI + ALLMEDIA : 2 // allow selection from all media types + }; + + +* **correctOrientation**: キャプチャ中に、デバイスの向きを修正する画像を回転させます。*(ブール値)* + +* **saveToPhotoAlbum**: キャプチャ後、デバイス上のフォト アルバムに画像を保存します。*(ブール値)* + +* **popoverOptions**: iPad のポップ オーバーの場所を指定する iOS のみのオプションです。定義されています。`CameraPopoverOptions`. + +* **cameraDirection**: (前面または背面側) を使用するカメラを選択します。既定値は戻るです。定義されている `navigator.camera.Direction` *(番号)* + + Camera.Direction = { + BACK : 0, // Use the back-facing camera + FRONT : 1 // Use the front-facing camera + }; + + +### アマゾン火 OS 癖 + +* 任意 `cameraDirection` 背面写真で結果の値します。 + +* 無視、 `allowEdit` パラメーター。 + +* `Camera.PictureSourceType.PHOTOLIBRARY``Camera.PictureSourceType.SAVEDPHOTOALBUM`両方のアルバムが表示されます同じ写真。 + +### Android の癖 + +* 任意 `cameraDirection` 背面写真で結果の値します。 + +* 無視、 `allowEdit` パラメーター。 + +* `Camera.PictureSourceType.PHOTOLIBRARY``Camera.PictureSourceType.SAVEDPHOTOALBUM`両方のアルバムが表示されます同じ写真。 + +### ブラックベリー 10 癖 + +* 無視、 `quality` パラメーター。 + +* 無視、 `allowEdit` パラメーター。 + +* `Camera.MediaType`サポートされていません。 + +* 無視、 `correctOrientation` パラメーター。 + +* 無視、 `cameraDirection` パラメーター。 + +### Firefox OS 癖 + +* 無視、 `quality` パラメーター。 + +* `Camera.DestinationType`無視され、等しい `1` (イメージ ファイル URI) + +* 無視、 `allowEdit` パラメーター。 + +* 無視、 `PictureSourceType` パラメーター (ユーザーが選択ダイアログ ウィンドウに) + +* 無視します、`encodingType` + +* 無視、 `targetWidth` と`targetHeight` + +* `Camera.MediaType`サポートされていません。 + +* 無視、 `correctOrientation` パラメーター。 + +* 無視、 `cameraDirection` パラメーター。 + +### iOS の癖 + +* 設定 `quality` 一部のデバイスでメモリ不足エラーを避けるために 50 の下。 + +* 使用する場合 `destinationType.FILE_URI` 、写真、アプリケーションの一時ディレクトリに保存されます。アプリケーションの一時ディレクトリの内容は、アプリケーションの終了時に削除されます。 + +### Tizen の癖 + +* サポートされていないオプション + +* 常にファイルの URI を返す + +### Windows Phone 7 と 8 癖 + +* 無視、 `allowEdit` パラメーター。 + +* 無視、 `correctOrientation` パラメーター。 + +* 無視、 `cameraDirection` パラメーター。 + +* 無視、 `saveToPhotoAlbum` パラメーター。 重要: wp7/8 コルドバ カメラ API で撮影したすべての画像は携帯電話のカメラ巻き物に常にコピーします。 ユーザーの設定に応じて、これも、画像はその OneDrive に自動アップロードを意味できます。 イメージは意図したアプリより広い聴衆に利用できる可能性があります可能性があります。 場合は、このアプリケーションのブロッカー、msdn で説明されているように、CameraCaptureTask を実装する必要があります: コメントにすることがありますもかアップ投票関連の問題を[課題追跡システム][3]で + +* 無視、 `mediaType` のプロパティ `cameraOptions` として Windows Phone SDK には、フォト ライブラリからビデオを選択する方法は行いません。 + + [3]: https://issues.apache.org/jira/browse/CB-2083 + +## CameraError + +エラー メッセージを提供する onError コールバック関数。 + + function(message) { + // Show a helpful message + } + + +### パラメーター + +* **message**: メッセージは、デバイスのネイティブ コードによって提供されます。*(文字列)* + +## cameraSuccess + +画像データを提供する onSuccess コールバック関数。 + + function(imageData) { + // Do something with the image + } + + +### パラメーター + +* **imagedata を扱う**: Base64 エンコード イメージのデータ、*または*画像ファイルによって URI の `cameraOptions` 効果。*(文字列)* + +### 例 + + // Show image + // + function cameraCallback(imageData) { + var image = document.getElementById('myImage'); + image.src = "data:image/jpeg;base64," + imageData; + } + + +## CameraPopoverHandle + +`Navigator.camera.getPicture` によって作成されたポップオーバーパン ダイアログ ボックスへのハンドル. + +### メソッド + +* **setPosition**: ポップ オーバーの位置を設定します。 + +### サポートされているプラットフォーム + +* iOS + +### setPosition + +ポップ オーバーの位置を設定します。 + +**パラメーター**: + +* `cameraPopoverOptions`:、 `CameraPopoverOptions` の新しい位置を指定します。 + +### 例 + + var cameraPopoverHandle = navigator.camera.getPicture(onSuccess, onFail, + { destinationType: Camera.DestinationType.FILE_URI, + sourceType: Camera.PictureSourceType.PHOTOLIBRARY, + popoverOptions: new CameraPopoverOptions(300, 300, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY) + }); + + // Reposition the popover if the orientation changes. + window.onorientationchange = function() { + var cameraPopoverOptions = new CameraPopoverOptions(0, 0, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY); + cameraPopoverHandle.setPosition(cameraPopoverOptions); + } + + +## CameraPopoverOptions + +iOS だけ指定パラメーターをポップ オーバーのアンカー要素の場所および矢印方向計算されたライブラリまたはアルバムから画像を選択するとき。 + + { x : 0, + y : 32, + width : 320, + height : 480, + arrowDir : Camera.PopoverArrowDirection.ARROW_ANY + }; + + +### CameraPopoverOptions + +* **x**: ピクセルの x 座標画面要素にポップ オーバーのアンカーになります。*(数)* + +* **y**: y ピクセル座標の画面要素にポップ オーバーのアンカーになります。*(数)* + +* **width**: ポップ オーバーのアンカーになる上の画面要素のピクセル単位の幅。*(数)* + +* **height**: ポップ オーバーのアンカーになる上の画面要素のピクセル単位の高さ。*(数)* + +* **arrowDir**: 方向のポップ オーバーで矢印をポイントする必要があります。定義されている `Camera.PopoverArrowDirection` *(番号)* + + Camera.PopoverArrowDirection = { + ARROW_UP : 1, // matches iOS UIPopoverArrowDirection constants + ARROW_DOWN : 2, + ARROW_LEFT : 4, + ARROW_RIGHT : 8, + ARROW_ANY : 15 + }; + + +矢印の方向と、画面の向きを調整するポップ オーバーのサイズを変更可能性がありますに注意してください。 アンカー要素の位置を指定するときの方向の変化を考慮することを確認します。 + +## navigator.camera.cleanup + +削除中間一時ストレージからカメラで撮影した写真。 + + navigator.camera.cleanup( cameraSuccess, cameraError ); + + +### 説明 + +`camera.getPicture` を呼び出した後一時記憶域に保存されている中間画像ファイルを削除します。 `Camera.sourceType` の値が `Camera.PictureSourceType.CAMERA` に等しい、`Camera.destinationType` が `Camera.DestinationType.FILE_URI` と等しいの場合にのみ適用されます。. + +### サポートされているプラットフォーム + +* iOS + +### 例 + + navigator.camera.cleanup(onSuccess, onFail); + + function onSuccess() { + console.log("Camera cleanup success.") + } + + function onFail(message) { + alert('Failed because: ' + message); + } diff --git a/plugins/cordova-plugin-camera/doc/ko/README.md b/plugins/cordova-plugin-camera/doc/ko/README.md new file mode 100644 index 0000000..7b7c215 --- /dev/null +++ b/plugins/cordova-plugin-camera/doc/ko/README.md @@ -0,0 +1,421 @@ + + +# cordova-plugin-camera + +[![Build Status](https://travis-ci.org/apache/cordova-plugin-camera.svg)](https://travis-ci.org/apache/cordova-plugin-camera) + +이 플러그인 시스템의 이미지 라이브러리에서 이미지를 선택 및 사진 촬영을 위한 API를 제공 하는 글로벌 `navigator.camera` 개체를 정의 합니다. + +개체 `navigator` 글로벌 범위 첨부 아니에요 때까지 사용할 수 있는 `deviceready` 이벤트 후. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(navigator.camera); + } + + +## 설치 + + cordova plugin add cordova-plugin-camera + + +## API + + * 카메라 + * navigator.camera.getPicture(success, fail, options) + * CameraOptions + * CameraPopoverHandle + * CameraPopoverOptions + * navigator.camera.cleanup + +## navigator.camera.getPicture + +카메라를 사용 하 여 사진을 걸립니다 또는 소자의 이미지 갤러리에서 사진을 검색 합니다. 이미지는 성공 콜백에 전달 base64 인코딩된 `문자열` 또는 URI로 이미지 파일에 대 한. 방법 자체는 파일 선택 popover 위치를 사용할 수 있는 `CameraPopoverHandle` 개체를 반환 합니다. + + navigator.camera.getPicture(cameraSuccess, cameraError, cameraOptions); + + +#### 설명 + +`Camera.getPicture` 함수 스냅 사진을 사용자가 소자의 기본 카메라 응용 프로그램을 엽니다. 이 문제는 `Camera.sourceType` `Camera.PictureSourceType.CAMERA` 경우 기본적으로 발생 합니다. 일단 사용자 스냅 사진, 카메라 응용 프로그램 종료 하 고 응용 프로그램 복원 됩니다. + +`Camera.sourceType`은 `Camera.PictureSourceType.PHOTOLIBRARY` 또는 `Camera.PictureSourceType.SAVEDPHOTOALBUM`, 대화 상자가 사용자가 기존 이미지를 선택할 수 있도록 표시 됩니다. `camera.getPicture` 함수는 장치 방향 변경 될 때 이미지 선택 대화 상자, 예를 들어, 위치를 변경 하려면 사용할 수 있는 `CameraPopoverHandle` 개체를 반환 합니다. + +반환 값은 `cameraSuccess` 콜백 함수 지정된 `cameraOptions`에 따라 다음 형식 중 하나에 전송 됩니다. + + * A `String` base64 인코딩된 사진 이미지를 포함 합니다. + + * A `String` 로컬 저장소 (기본값)의 이미지 파일 위치를 나타내는. + +할 수 있는 당신이 원하는대로 인코딩된 이미지 또는 URI, 예를 들면: + + * 렌더링 이미지는 `` 아래 예제와 같이 태그 + + * 로컬로 데이터를 저장 ( `LocalStorage` , [Lawnchair](http://brianleroux.github.com/lawnchair/), 등.) + + * 원격 서버에 데이터 게시 + +**참고**: 더 새로운 장치에 사진 해상도 아주 좋은. 소자의 갤러리에서 선택 된 사진 `품질` 매개 변수를 지정 하는 경우에 낮은 품질에 관하여 하지는. 일반적인 메모리 문제를 피하기 위해 `DATA_URL` 보다 `FILE_URI` `Camera.destinationType` 설정. + +#### 지원 되는 플랫폼 + +![](doc/img/android-success.png) ![](doc/img/blackberry-success.png) ![](doc/img/browser-success.png) ![](doc/img/firefox-success.png) ![](doc/img/fireos-success.png) ![](doc/img/ios-success.png) ![](doc/img/windows-success.png) ![](doc/img/wp8-success.png) ![](doc/img/ubuntu-success.png) + +#### 예를 들어 + +촬영 및 base64 인코딩 이미지로 검색: + + navigator.camera.getPicture(onSuccess, onFail, { quality: 50, + destinationType: Camera.DestinationType.DATA_URL + }); + + function onSuccess(imageData) { + var image = document.getElementById('myImage'); + image.src = "data:image/jpeg;base64," + imageData; + } + + function onFail(message) { + alert('Failed because: ' + message); + } + + +촬영 하 고 이미지의 파일 위치를 검색: + + navigator.camera.getPicture(onSuccess, onFail, { quality: 50, + destinationType: Camera.DestinationType.FILE_URI }); + + function onSuccess(imageURI) { + var image = document.getElementById('myImage'); + image.src = imageURI; + } + + function onFail(message) { + alert('Failed because: ' + message); + } + + +#### 환경 설정 (iOS) + + * **CameraUsesGeolocation** (boolean, 기본값: false)입니다. 캡처 Jpeg, EXIF 헤더에 지리적 데이터를 true로 설정 합니다. 이 경우 위치 정보 사용 권한에 대 한 요청을 일으킬 것 이다 true로 설정 합니다. + + + + +#### 아마존 화재 OS 단점 + +아마존 화재 OS 의도 사용 하 여 이미지 캡처 장치에서 카메라 활동을 시작 하 고 낮은 메모리와 휴대 전화에 코르 도우 바 활동 살해 수 있습니다. 코르도바 활동 복원 되 면이 시나리오에서는 이미지가 나타나지 않을 수 있습니다. + +#### 안 드 로이드 단점 + +안 드 로이드 의도 사용 하 여 이미지 캡처 장치에서 카메라 활동을 시작 하 고 낮은 메모리와 휴대 전화에 코르 도우 바 활동 살해 수 있습니다. 코르도바 활동 복원 되 면이 시나리오에서는 이미지가 나타나지 않을 수 있습니다. + +#### 브라우저 만지면 + +수 base64 인코딩 이미지로 사진을 반환 합니다. + +#### 파이어 폭스 OS 단점 + +카메라 플러그인은 현재 [웹 활동](https://hacks.mozilla.org/2013/01/introducing-web-activities/)를 사용 하 여 구현. + +#### iOS 단점 + +자바 `alert()`를 포함 하 여 콜백 함수 중 하나에 문제가 발생할 수 있습니다. 포장 허용 iOS 이미지 피커 또는 popover를 완벽 하 게 경고를 표시 하기 전에 닫습니다 `setTimeout()` 내에서 경고: + + setTimeout(function() { + // do your thing here! + }, 0); + + +#### Windows Phone 7 단점 + +장치 Zune 통해 연결 된 동안 네이티브 카메라 응용 프로그램을 호출 하면 작동 하지 않습니다 하 고 오류 콜백 트리거합니다. + +#### Tizen 특수 + +`Camera.DestinationType.FILE_URI`의 `destinationType`와 `Camera.PictureSourceType.PHOTOLIBRARY`의 `sourceType` Tizen 지원. + +## CameraOptions + +카메라 설정을 사용자 지정 하는 선택적 매개 변수. + + { quality : 75, + destinationType : Camera.DestinationType.DATA_URL, + sourceType : Camera.PictureSourceType.CAMERA, + allowEdit : true, + encodingType: Camera.EncodingType.JPEG, + targetWidth: 100, + targetHeight: 100, + popoverOptions: CameraPopoverOptions, + saveToPhotoAlbum: false }; + + + * **품질**: 범위 0-100, 100은 파일 압축에서 손실 없이 일반적으로 전체 해상도 저장된 된 이미지의 품질. 기본값은 50입니다. *(수)* (Note 카메라의 해상도 대 한 정보는 사용할 수 없습니다.) + + * **destinationType**: 반환 값의 형식을 선택 합니다. 기본값은 FILE_URI입니다. 에 정의 된 `navigator.camera.DestinationType` *(수)* + + Camera.DestinationType = { + DATA_URL : 0, // Return image as base64-encoded string + FILE_URI : 1, // Return image file URI + NATIVE_URI : 2 // Return image native URI (e.g., assets-library:// on iOS or content:// on Android) + }; + + + * **sourceType**: 그림의 소스를 설정 합니다. 기본값은 카메라입니다. 에 정의 된 `navigator.camera.PictureSourceType` *(수)* + + Camera.PictureSourceType = { + PHOTOLIBRARY : 0, + CAMERA : 1, + SAVEDPHOTOALBUM : 2 + }; + + + * **allowEdit**: 선택 하기 전에 이미지의 간단한 편집을 허용 합니다. *(부울)* + + * **encodingType**: 반환 된 이미지 파일의 인코딩을 선택 합니다. 기본값은 JPEG입니다. 에 정의 된 `navigator.camera.EncodingType` *(수)* + + Camera.EncodingType = { + JPEG : 0, // Return JPEG encoded image + PNG : 1 // Return PNG encoded image + }; + + + * **targetWidth**: 스케일 이미지를 픽셀 너비. **TargetHeight**와 함께 사용 해야 합니다. 가로 세로 비율이 일정 하 게 유지 합니다. *(수)* + + * **targetHeight**: 스케일 이미지를 픽셀 단위로 높이. **TargetWidth**와 함께 사용 해야 합니다. 가로 세로 비율이 일정 하 게 유지 합니다. *(수)* + + * **mediaType**:에서 선택 미디어 유형을 설정 합니다. 때에 작동 `PictureSourceType` 는 `PHOTOLIBRARY` 또는 `SAVEDPHOTOALBUM` . 에 정의 된 `nagivator.camera.MediaType` *(수)* + + Camera.MediaType = { + PICTURE: 0, // allow selection of still pictures only. 기본입니다. Will return format specified via DestinationType + VIDEO: 1, // allow selection of video only, WILL ALWAYS RETURN FILE_URI + ALLMEDIA : 2 // allow selection from all media types + }; + + + * **correctOrientation**: 캡처 도중 장치의 방향에 대 한 해결 하기 위해 이미지를 회전 합니다. *(부울)* + + * **saveToPhotoAlbum**: 캡처 후 장치에서 사진 앨범에 이미지를 저장 합니다. *(부울)* + + * **popoverOptions**: iPad에 popover 위치를 지정 하는 iOS 전용 옵션. 에 정의 된`CameraPopoverOptions`. + + * **cameraDirection**: (앞 이나 뒤로-연결)를 사용 하 여 카메라를 선택 하십시오. 기본값은 다시. 에 정의 된 `navigator.camera.Direction` *(수)* + + Camera.Direction = { + BACK : 0, // Use the back-facing camera + FRONT : 1 // Use the front-facing camera + }; + + +#### 아마존 화재 OS 단점 + + * 어떤 `cameraDirection` 다시 연결 사진에 결과 값. + + * 무시는 `allowEdit` 매개 변수. + + * `Camera.PictureSourceType.PHOTOLIBRARY`그리고 `Camera.PictureSourceType.SAVEDPHOTOALBUM` 둘 다 동일한 사진 앨범을 표시 합니다. + +#### 안 드 로이드 단점 + + * 어떤 `cameraDirection` 다시 연결 사진에 결과 값. + + * 안 드 로이드도 사용 자르기 활동 allowEdit, 비록 작물 작업과 실제로 코르도바, 유일 하 게 작품 지속적으로 구글 플러스 사진 응용 프로그램과 함께 번들로 제공 하는 것은 등을 맞댄 자른된 이미지를 전달 해야 합니다. 다른 작물은 작동 하지 않을 수 있습니다. + + * `Camera.PictureSourceType.PHOTOLIBRARY`그리고 `Camera.PictureSourceType.SAVEDPHOTOALBUM` 둘 다 동일한 사진 앨범을 표시 합니다. + +#### 블랙베리 10 단점 + + * 무시는 `quality` 매개 변수. + + * 무시는 `allowEdit` 매개 변수. + + * `Camera.MediaType`지원 되지 않습니다. + + * 무시는 `correctOrientation` 매개 변수. + + * 무시는 `cameraDirection` 매개 변수. + +#### 파이어 폭스 OS 단점 + + * 무시는 `quality` 매개 변수. + + * `Camera.DestinationType`무시 되 고 `1` (이미지 파일 URI) + + * 무시는 `allowEdit` 매개 변수. + + * 무시는 `PictureSourceType` 매개 변수 (사용자가 선택 그것 대화 창에서) + + * 무시 하는`encodingType` + + * 무시는 `targetWidth` 와`targetHeight` + + * `Camera.MediaType`지원 되지 않습니다. + + * 무시는 `correctOrientation` 매개 변수. + + * 무시는 `cameraDirection` 매개 변수. + +#### iOS 단점 + + * 설정 `quality` 일부 장치 메모리 오류를 피하기 위해 50 아래. + + * 사용 하는 경우 `destinationType.FILE_URI` , 사진 응용 프로그램의 임시 디렉터리에 저장 됩니다. 응용 프로그램이 종료 될 때 응용 프로그램의 임시 디렉터리의 내용은 삭제 됩니다. + +#### Tizen 특수 + + * 지원 되지 않는 옵션 + + * 항상 파일 URI를 반환 합니다. + +#### Windows Phone 7, 8 특수 + + * 무시는 `allowEdit` 매개 변수. + + * 무시는 `correctOrientation` 매개 변수. + + * 무시는 `cameraDirection` 매개 변수. + + * 무시는 `saveToPhotoAlbum` 매개 변수. 중요: 모든 이미지 API wp7/8 코르도바 카메라로 촬영 항상 복사 됩니다 휴대 전화의 카메라 롤에. 사용자의 설정에 따라이 또한 그들의 OneDrive에 자동 업로드 이미지는 의미. 이 잠재적으로 이미지는 당신의 애플 리 케이 션을 위한 보다 넓은 청중에 게 사용할 수 있는 의미. 이 경우 응용 프로그램에 대 한 차단, 당신은 msdn에 설명 대로 단말기를 구현 해야 합니다: 수 있습니다 또한 의견 또는 [이슈 트래커](https://issues.apache.org/jira/browse/CB-2083) 에서 업-투표 관련된 문제 + + * 무시는 `mediaType` 속성을 `cameraOptions` 으로 Windows Phone SDK PHOTOLIBRARY에서 비디오를 선택 하는 방법을 제공 하지 않습니다. + +## CameraError + +오류 메시지를 제공 하는 onError 콜백 함수. + + function(message) { + // Show a helpful message + } + + +#### 설명 + + * **메시지**: 메시지는 장치의 네이티브 코드에 의해 제공 됩니다. *(문자열)* + +## cameraSuccess + +이미지 데이터를 제공 하는 onSuccess 콜백 함수. + + function(imageData) { + // Do something with the image + } + + +#### 설명 + + * **imageData**: Base64 인코딩은 이미지 데이터, *또는* 이미지 파일에 따라 URI의 `cameraOptions` 적용. *(문자열)* + +#### 예를 들어 + + // Show image + // + function cameraCallback(imageData) { + var image = document.getElementById('myImage'); + image.src = "data:image/jpeg;base64," + imageData; + } + + +## CameraPopoverHandle + +`navigator.camera.getPicture`에 의해 만들어진 popover 대화에 대 한 핸들. + +#### 설명 + + * **setPosition**: Set the position of the popover. Takes the `CameraPopoverOptions` that specify the new position. + +#### 지원 되는 플랫폼 + +![](doc/img/android-fail.png) ![](doc/img/blackberry-fail.png) ![](doc/img/browser-fail.png) ![](doc/img/firefox-fail.png) ![](doc/img/fireos-fail.png) ![](doc/img/ios-success.png) ![](doc/img/windows-fail.png) ![](doc/img/wp8-fail.png) ![](doc/img/ubuntu-fail.png) + +#### 예를 들어 + + var cameraPopoverHandle = navigator.camera.getPicture(onSuccess, onFail, + { destinationType: Camera.DestinationType.FILE_URI, + sourceType: Camera.PictureSourceType.PHOTOLIBRARY, + popoverOptions: new CameraPopoverOptions(300, 300, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY) + }); + + // Reposition the popover if the orientation changes. + window.onorientationchange = function() { + var cameraPopoverOptions = new CameraPopoverOptions(0, 0, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY); + cameraPopoverHandle.setPosition(cameraPopoverOptions); + } + + +## CameraPopoverOptions + +iOS 전용 매개 변수 iPad의 보관 함 또는 앨범에서 이미지를 선택 하면 앵커 요소 위치와 화살표의 방향으로 popover 지정 하는. + + { x : 0, + y : 32, + width : 320, + height : 480, + arrowDir : Camera.PopoverArrowDirection.ARROW_ANY + }; + + +#### 설명 + + * **x**: x는 popover 앵커는 화면 요소의 픽셀 좌표. *(수)* + + * **y**: y 픽셀 좌표는 popover 앵커는 화면 요소입니다. *(수)* + + * **폭**: 폭 (픽셀)는 popover 앵커는 화면 요소. *(수)* + + * **높이**: 높이 (픽셀)는 popover 앵커는 화면 요소. *(수)* + + * **arrowDir**: 방향 화살표는 popover 가리켜야 합니다. 에 정의 된 `Camera.PopoverArrowDirection` *(수)* + + Camera.PopoverArrowDirection = { + ARROW_UP : 1, // matches iOS UIPopoverArrowDirection constants + ARROW_DOWN : 2, + ARROW_LEFT : 4, + ARROW_RIGHT : 8, + ARROW_ANY : 15 + }; + + +참고는 popover의 크기 조정 화살표 방향 및 화면 방향 변경 될 수 있습니다. 앵커 요소 위치를 지정 하는 경우 방향 변경에 대 한 계정에 있는지 확인 합니다. + +## navigator.camera.cleanup + +제거 임시 저장소에서 카메라로 찍은 사진을 중간. + + navigator.camera.cleanup( cameraSuccess, cameraError ); + + +#### 설명 + +`camera.getPicture`를 호출한 후 임시 저장소에 보관 됩니다 중간 이미지 파일을 제거 합니다. `Camera.sourceType` 값은 `Camera.PictureSourceType.CAMERA` 및 `Camera.destinationType`와 `Camera.DestinationType.FILE_URI` 때만 적용 됩니다.. + +#### 지원 되는 플랫폼 + +![](doc/img/android-fail.png) ![](doc/img/blackberry-fail.png) ![](doc/img/browser-fail.png) ![](doc/img/firefox-fail.png) ![](doc/img/fireos-fail.png) ![](doc/img/ios-success.png) ![](doc/img/windows-fail.png) ![](doc/img/wp8-fail.png) ![](doc/img/ubuntu-fail.png) + +#### 예를 들어 + + navigator.camera.cleanup(onSuccess, onFail); + + function onSuccess() { + console.log("Camera cleanup success.") + } + + function onFail(message) { + alert('Failed because: ' + message); + } \ No newline at end of file diff --git a/plugins/cordova-plugin-camera/doc/ko/index.md b/plugins/cordova-plugin-camera/doc/ko/index.md new file mode 100644 index 0000000..794aa97 --- /dev/null +++ b/plugins/cordova-plugin-camera/doc/ko/index.md @@ -0,0 +1,434 @@ + + +# cordova-plugin-camera + +이 플러그인 시스템의 이미지 라이브러리에서 이미지를 선택 및 사진 촬영을 위한 API를 제공 하는 글로벌 `navigator.camera` 개체를 정의 합니다. + +개체 `navigator` 글로벌 범위 첨부 아니에요 때까지 사용할 수 있는 `deviceready` 이벤트 후. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(navigator.camera); + } + + +## 설치 + + cordova plugin add cordova-plugin-camera + + +## navigator.camera.getPicture + +카메라를 사용 하 여 사진을 걸립니다 또는 소자의 이미지 갤러리에서 사진을 검색 합니다. 이미지는 성공 콜백에 전달 base64 인코딩된 `문자열` 또는 URI로 이미지 파일에 대 한. 방법 자체는 파일 선택 popover 위치를 사용할 수 있는 `CameraPopoverHandle` 개체를 반환 합니다. + + navigator.camera.getPicture( cameraSuccess, cameraError, cameraOptions ); + + +### 설명 + +`Camera.getPicture` 함수 스냅 사진을 사용자가 소자의 기본 카메라 응용 프로그램을 엽니다. 이 문제는 `Camera.sourceType` `Camera.PictureSourceType.CAMERA` 경우 기본적으로 발생 합니다. 일단 사용자 스냅 사진, 카메라 응용 프로그램 종료 하 고 응용 프로그램 복원 됩니다. + +`Camera.sourceType`은 `Camera.PictureSourceType.PHOTOLIBRARY` 또는 `Camera.PictureSourceType.SAVEDPHOTOALBUM`, 대화 상자가 사용자가 기존 이미지를 선택할 수 있도록 표시 됩니다. `camera.getPicture` 함수는 장치 방향 변경 될 때 이미지 선택 대화 상자, 예를 들어, 위치를 변경 하려면 사용할 수 있는 `CameraPopoverHandle` 개체를 반환 합니다. + +반환 값은 `cameraSuccess` 콜백 함수 지정된 `cameraOptions`에 따라 다음 형식 중 하나에 전송 됩니다. + +* A `String` base64 인코딩된 사진 이미지를 포함 합니다. + +* A `String` 로컬 저장소 (기본값)의 이미지 파일 위치를 나타내는. + +할 수 있는 당신이 원하는대로 인코딩된 이미지 또는 URI, 예를 들면: + +* 렌더링 이미지는 `` 아래 예제와 같이 태그 + +* 로컬로 데이터를 저장 ( `LocalStorage` , [Lawnchair][1], 등.) + +* 원격 서버에 데이터 게시 + + [1]: http://brianleroux.github.com/lawnchair/ + +**참고**: 더 새로운 장치에 사진 해상도 아주 좋은. 소자의 갤러리에서 선택 된 사진 `품질` 매개 변수를 지정 하는 경우에 낮은 품질에 관하여 하지는. 일반적인 메모리 문제를 피하기 위해 `DATA_URL` 보다 `FILE_URI` `Camera.destinationType` 설정. + +### 지원 되는 플랫폼 + +* 아마존 화재 운영 체제 +* 안 드 로이드 +* 블랙베리 10 +* 브라우저 +* Firefox 운영 체제 +* iOS +* Tizen +* Windows Phone 7과 8 +* 윈도우 8 + +### 환경 설정 (iOS) + +* **CameraUsesGeolocation** (boolean, 기본값: false)입니다. 캡처 Jpeg, EXIF 헤더에 지리적 데이터를 true로 설정 합니다. 이 경우 위치 정보 사용 권한에 대 한 요청을 일으킬 것 이다 true로 설정 합니다. + + + + +### 아마존 화재 OS 단점 + +아마존 화재 OS 의도 사용 하 여 이미지 캡처 장치에서 카메라 활동을 시작 하 고 낮은 메모리와 휴대 전화에 코르 도우 바 활동 살해 수 있습니다. 코르도바 활동 복원 되 면이 시나리오에서는 이미지가 나타나지 않을 수 있습니다. + +### 안 드 로이드 단점 + +안 드 로이드 의도 사용 하 여 이미지 캡처 장치에서 카메라 활동을 시작 하 고 낮은 메모리와 휴대 전화에 코르 도우 바 활동 살해 수 있습니다. 코르도바 활동 복원 되 면이 시나리오에서는 이미지가 나타나지 않을 수 있습니다. + +### 브라우저 만지면 + +수 base64 인코딩 이미지로 사진을 반환 합니다. + +### 파이어 폭스 OS 단점 + +카메라 플러그인은 현재 [웹 활동][2]를 사용 하 여 구현. + + [2]: https://hacks.mozilla.org/2013/01/introducing-web-activities/ + +### iOS 단점 + +자바 `alert()`를 포함 하 여 콜백 함수 중 하나에 문제가 발생할 수 있습니다. 포장 허용 iOS 이미지 피커 또는 popover를 완벽 하 게 경고를 표시 하기 전에 닫습니다 `setTimeout()` 내에서 경고: + + setTimeout(function() { + // do your thing here! + }, 0); + + +### Windows Phone 7 단점 + +장치 Zune 통해 연결 된 동안 네이티브 카메라 응용 프로그램을 호출 하면 작동 하지 않습니다 하 고 오류 콜백 트리거합니다. + +### Tizen 특수 + +`Camera.DestinationType.FILE_URI`의 `destinationType`와 `Camera.PictureSourceType.PHOTOLIBRARY`의 `sourceType` Tizen 지원. + +### 예를 들어 + +촬영 및 base64 인코딩 이미지로 검색: + + navigator.camera.getPicture(onSuccess, onFail, { quality: 50, + destinationType: Camera.DestinationType.DATA_URL + }); + + function onSuccess(imageData) { + var image = document.getElementById('myImage'); + image.src = "data:image/jpeg;base64," + imageData; + } + + function onFail(message) { + alert('Failed because: ' + message); + } + + +촬영 하 고 이미지의 파일 위치를 검색: + + navigator.camera.getPicture(onSuccess, onFail, { quality: 50, + destinationType: Camera.DestinationType.FILE_URI }); + + function onSuccess(imageURI) { + var image = document.getElementById('myImage'); + image.src = imageURI; + } + + function onFail(message) { + alert('Failed because: ' + message); + } + + +## CameraOptions + +카메라 설정을 사용자 지정 하는 선택적 매개 변수. + + { quality : 75, + destinationType : Camera.DestinationType.DATA_URL, + sourceType : Camera.PictureSourceType.CAMERA, + allowEdit : true, + encodingType: Camera.EncodingType.JPEG, + targetWidth: 100, + targetHeight: 100, + popoverOptions: CameraPopoverOptions, + saveToPhotoAlbum: false }; + + +### 옵션 + +* **품질**: 범위 0-100, 100은 파일 압축에서 손실 없이 일반적으로 전체 해상도 저장된 된 이미지의 품질. 기본값은 50입니다. *(수)* (Note 카메라의 해상도 대 한 정보는 사용할 수 없습니다.) + +* **destinationType**: 반환 값의 형식을 선택 합니다. 기본값은 FILE_URI입니다. 에 정의 된 `navigator.camera.DestinationType` *(수)* + + Camera.DestinationType = { + DATA_URL : 0, // Return image as base64-encoded string + FILE_URI : 1, // Return image file URI + NATIVE_URI : 2 // Return image native URI (e.g., assets-library:// on iOS or content:// on Android) + }; + + +* **sourceType**: 그림의 소스를 설정 합니다. 기본값은 카메라입니다. 에 정의 된 `navigator.camera.PictureSourceType` *(수)* + + Camera.PictureSourceType = { + PHOTOLIBRARY : 0, + CAMERA : 1, + SAVEDPHOTOALBUM : 2 + }; + + +* **allowEdit**: 선택 하기 전에 이미지의 간단한 편집을 허용 합니다. *(부울)* + +* **encodingType**: 반환 된 이미지 파일의 인코딩을 선택 합니다. 기본값은 JPEG입니다. 에 정의 된 `navigator.camera.EncodingType` *(수)* + + Camera.EncodingType = { + JPEG : 0, // Return JPEG encoded image + PNG : 1 // Return PNG encoded image + }; + + +* **targetWidth**: 스케일 이미지를 픽셀 너비. **TargetHeight**와 함께 사용 해야 합니다. 가로 세로 비율이 일정 하 게 유지 합니다. *(수)* + +* **targetHeight**: 스케일 이미지를 픽셀 단위로 높이. **TargetWidth**와 함께 사용 해야 합니다. 가로 세로 비율이 일정 하 게 유지 합니다. *(수)* + +* **mediaType**:에서 선택 미디어 유형을 설정 합니다. 때에 작동 `PictureSourceType` 는 `PHOTOLIBRARY` 또는 `SAVEDPHOTOALBUM` . 에 정의 된 `nagivator.camera.MediaType` *(수)* + + Camera.MediaType = { + PICTURE: 0, // allow selection of still pictures only. 기본입니다. Will return format specified via DestinationType + VIDEO: 1, // allow selection of video only, WILL ALWAYS RETURN FILE_URI + ALLMEDIA : 2 // allow selection from all media types + }; + + +* **correctOrientation**: 캡처 도중 장치의 방향에 대 한 해결 하기 위해 이미지를 회전 합니다. *(부울)* + +* **saveToPhotoAlbum**: 캡처 후 장치에서 사진 앨범에 이미지를 저장 합니다. *(부울)* + +* **popoverOptions**: iPad에 popover 위치를 지정 하는 iOS 전용 옵션. 에 정의 된`CameraPopoverOptions`. + +* **cameraDirection**: (앞 이나 뒤로-연결)를 사용 하 여 카메라를 선택 하십시오. 기본값은 다시. 에 정의 된 `navigator.camera.Direction` *(수)* + + Camera.Direction = { + BACK : 0, // Use the back-facing camera + FRONT : 1 // Use the front-facing camera + }; + + +### 아마존 화재 OS 단점 + +* 어떤 `cameraDirection` 다시 연결 사진에 결과 값. + +* 무시는 `allowEdit` 매개 변수. + +* `Camera.PictureSourceType.PHOTOLIBRARY`그리고 `Camera.PictureSourceType.SAVEDPHOTOALBUM` 둘 다 동일한 사진 앨범을 표시 합니다. + +### 안 드 로이드 단점 + +* 어떤 `cameraDirection` 다시 연결 사진에 결과 값. + +* 무시는 `allowEdit` 매개 변수. + +* `Camera.PictureSourceType.PHOTOLIBRARY`그리고 `Camera.PictureSourceType.SAVEDPHOTOALBUM` 둘 다 동일한 사진 앨범을 표시 합니다. + +### 블랙베리 10 단점 + +* 무시는 `quality` 매개 변수. + +* 무시는 `allowEdit` 매개 변수. + +* `Camera.MediaType`지원 되지 않습니다. + +* 무시는 `correctOrientation` 매개 변수. + +* 무시는 `cameraDirection` 매개 변수. + +### 파이어 폭스 OS 단점 + +* 무시는 `quality` 매개 변수. + +* `Camera.DestinationType`무시 되 고 `1` (이미지 파일 URI) + +* 무시는 `allowEdit` 매개 변수. + +* 무시는 `PictureSourceType` 매개 변수 (사용자가 선택 그것 대화 창에서) + +* 무시 하는`encodingType` + +* 무시는 `targetWidth` 와`targetHeight` + +* `Camera.MediaType`지원 되지 않습니다. + +* 무시는 `correctOrientation` 매개 변수. + +* 무시는 `cameraDirection` 매개 변수. + +### iOS 단점 + +* 설정 `quality` 일부 장치 메모리 오류를 피하기 위해 50 아래. + +* 사용 하는 경우 `destinationType.FILE_URI` , 사진 응용 프로그램의 임시 디렉터리에 저장 됩니다. 응용 프로그램이 종료 될 때 응용 프로그램의 임시 디렉터리의 내용은 삭제 됩니다. + +### Tizen 특수 + +* 지원 되지 않는 옵션 + +* 항상 파일 URI를 반환 합니다. + +### Windows Phone 7, 8 특수 + +* 무시는 `allowEdit` 매개 변수. + +* 무시는 `correctOrientation` 매개 변수. + +* 무시는 `cameraDirection` 매개 변수. + +* 무시는 `saveToPhotoAlbum` 매개 변수. 중요: 모든 이미지 API wp7/8 코르도바 카메라로 촬영 항상 복사 됩니다 휴대 전화의 카메라 롤에. 사용자의 설정에 따라이 또한 그들의 OneDrive에 자동 업로드 이미지는 의미. 이 잠재적으로 이미지는 당신의 애플 리 케이 션을 위한 보다 넓은 청중에 게 사용할 수 있는 의미. 이 경우 응용 프로그램에 대 한 차단, 당신은 msdn에 설명 대로 단말기를 구현 해야 합니다: 수 있습니다 또한 의견 또는 [이슈 트래커][3] 에서 업-투표 관련된 문제 + +* 무시는 `mediaType` 속성을 `cameraOptions` 으로 Windows Phone SDK PHOTOLIBRARY에서 비디오를 선택 하는 방법을 제공 하지 않습니다. + + [3]: https://issues.apache.org/jira/browse/CB-2083 + +## CameraError + +오류 메시지를 제공 하는 onError 콜백 함수. + + function(message) { + // Show a helpful message + } + + +### 매개 변수 + +* **메시지**: 메시지는 장치의 네이티브 코드에 의해 제공 됩니다. *(문자열)* + +## cameraSuccess + +이미지 데이터를 제공 하는 onSuccess 콜백 함수. + + function(imageData) { + // Do something with the image + } + + +### 매개 변수 + +* **imageData**: Base64 인코딩은 이미지 데이터, *또는* 이미지 파일에 따라 URI의 `cameraOptions` 적용. *(문자열)* + +### 예를 들어 + + // Show image + // + function cameraCallback(imageData) { + var image = document.getElementById('myImage'); + image.src = "data:image/jpeg;base64," + imageData; + } + + +## CameraPopoverHandle + +`navigator.camera.getPicture`에 의해 만들어진 popover 대화에 대 한 핸들. + +### 메서드 + +* **setPosition**:는 popover의 위치를 설정 합니다. + +### 지원 되는 플랫폼 + +* iOS + +### setPosition + +popover의 위치를 설정 합니다. + +**매개 변수**: + +* `cameraPopoverOptions`:는 `CameraPopoverOptions` 새 위치를 지정 하는 + +### 예를 들어 + + var cameraPopoverHandle = navigator.camera.getPicture(onSuccess, onFail, + { destinationType: Camera.DestinationType.FILE_URI, + sourceType: Camera.PictureSourceType.PHOTOLIBRARY, + popoverOptions: new CameraPopoverOptions(300, 300, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY) + }); + + // Reposition the popover if the orientation changes. + window.onorientationchange = function() { + var cameraPopoverOptions = new CameraPopoverOptions(0, 0, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY); + cameraPopoverHandle.setPosition(cameraPopoverOptions); + } + + +## CameraPopoverOptions + +iOS 전용 매개 변수 iPad의 보관 함 또는 앨범에서 이미지를 선택 하면 앵커 요소 위치와 화살표의 방향으로 popover 지정 하는. + + { x : 0, + y : 32, + width : 320, + height : 480, + arrowDir : Camera.PopoverArrowDirection.ARROW_ANY + }; + + +### CameraPopoverOptions + +* **x**: x는 popover 앵커는 화면 요소의 픽셀 좌표. *(수)* + +* **y**: y 픽셀 좌표는 popover 앵커는 화면 요소입니다. *(수)* + +* **폭**: 폭 (픽셀)는 popover 앵커는 화면 요소. *(수)* + +* **높이**: 높이 (픽셀)는 popover 앵커는 화면 요소. *(수)* + +* **arrowDir**: 방향 화살표는 popover 가리켜야 합니다. 에 정의 된 `Camera.PopoverArrowDirection` *(수)* + + Camera.PopoverArrowDirection = { + ARROW_UP : 1, // matches iOS UIPopoverArrowDirection constants + ARROW_DOWN : 2, + ARROW_LEFT : 4, + ARROW_RIGHT : 8, + ARROW_ANY : 15 + }; + + +참고는 popover의 크기 조정 화살표 방향 및 화면 방향 변경 될 수 있습니다. 앵커 요소 위치를 지정 하는 경우 방향 변경에 대 한 계정에 있는지 확인 합니다. + +## navigator.camera.cleanup + +제거 임시 저장소에서 카메라로 찍은 사진을 중간. + + navigator.camera.cleanup( cameraSuccess, cameraError ); + + +### 설명 + +`camera.getPicture`를 호출한 후 임시 저장소에 보관 됩니다 중간 이미지 파일을 제거 합니다. `Camera.sourceType` 값은 `Camera.PictureSourceType.CAMERA` 및 `Camera.destinationType`와 `Camera.DestinationType.FILE_URI` 때만 적용 됩니다.. + +### 지원 되는 플랫폼 + +* iOS + +### 예를 들어 + + navigator.camera.cleanup(onSuccess, onFail); + + function onSuccess() { + console.log("Camera cleanup success.") + } + + function onFail(message) { + alert('Failed because: ' + message); + } diff --git a/plugins/cordova-plugin-camera/doc/pl/README.md b/plugins/cordova-plugin-camera/doc/pl/README.md new file mode 100644 index 0000000..e7b9d44 --- /dev/null +++ b/plugins/cordova-plugin-camera/doc/pl/README.md @@ -0,0 +1,421 @@ + + +# cordova-plugin-camera + +[![Build Status](https://travis-ci.org/apache/cordova-plugin-camera.svg)](https://travis-ci.org/apache/cordova-plugin-camera) + +Ten plugin definiuje obiekt globalny `navigator.camera`, który dostarcza API do robienia zdjęć i wybór zdjęć z biblioteki obrazów systemu. + +Mimo, że obiekt jest dołączony do globalnego zakresu `navigator`, to nie dostępne dopiero po zdarzeniu `deviceready`. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(navigator.camera); + } + + +## Instalacja + + cordova plugin add cordova-plugin-camera + + +## API + + * Aparat + * navigator.camera.getPicture(success, fail, options) + * CameraOptions + * CameraPopoverHandle + * CameraPopoverOptions + * navigator.camera.cleanup + +## navigator.camera.getPicture + +Ma zdjęcia za pomocą aparatu, lub pobiera zdjęcia z urządzenia Galeria zdjęć. Obraz jest przekazywany do wywołania zwrotnego sukces jako kodowane algorytmem base64 `ciąg`, lub identyfikator URI dla pliku obrazu. Sama metoda zwraca obiekt `CameraPopoverHandle`, który może służyć do zmiany położenia pliku wyboru popover. + + navigator.camera.getPicture(cameraSuccess, cameraError, cameraOptions); + + +#### Opis + +Funkcja `camera.getPicture` otwiera urządzenia domyślnej aplikacji aparat fotograficzny ów pozwala użytkownik wobec chwycić zębami kino. To zachowanie występuje domyślnie, gdy `Camera.sourceType` jest równa `Camera.PictureSourceType.CAMERA`. Gdy użytkownik zaskoczy zdjęcie, ten aparat fotograficzny applicationâ zamyka i aplikacji jest przywracany. + +Jeśli `Camera.sourceType` jest równe `Camera.PictureSourceType.PHOTOLIBRARY` lub `Camera.PictureSourceType.SAVEDPHOTOALBUM`, wtedy zostanie wyświetlone okno dialogowe pozwalające użytkownikowi na wybór istniejącego obrazu. Funkcja `camera.getPicture` zwraca obiekt `CameraPopoverHandle`, który obsługuje zmianę położenia okna wyboru obrazu, np. po zmianie orientacji urządzenia. + +Zwracana wartość jest wysyłany do funkcji wywołania zwrotnego `cameraSuccess`, w jednym z następujących formatów, w zależności od określonego `cameraOptions`: + + * `String` zawierający obraz zakodowany przy pomocy base64. + + * `String` reprezentujący lokalizację pliku obrazu w lokalnym magazynie (domyślnie). + +Może rób, co chcesz z zakodowany obraz lub identyfikatora URI, na przykład: + + * Przedstawić obraz w tagu ``, jak w przykładzie poniżej + + * Zapisać lokalnie dane (`LocalStorage`, [Lawnchair](http://brianleroux.github.com/lawnchair/), etc.) + + * Wysłać dane na zdalny serwer + +**Uwaga**: zdjęcie rozdzielczości na nowsze urządzenia jest bardzo dobry. Zdjęcia wybrane z galerii urządzenia są nie przeskalowanych w dół do niższej jakości, nawet jeśli określono parametr `quality`. Aby uniknąć typowych problemów z pamięci, zestaw `Camera.destinationType` `FILE_URI` zamiast `DATA_URL`. + +#### Obsługiwane platformy + +![](doc/img/android-success.png) ![](doc/img/blackberry-success.png) ![](doc/img/browser-success.png) ![](doc/img/firefox-success.png) ![](doc/img/fireos-success.png) ![](doc/img/ios-success.png) ![](doc/img/windows-success.png) ![](doc/img/wp8-success.png) ![](doc/img/ubuntu-success.png) + +#### Przykład + +Zrób zdjęcie i pobrać go jako kodowane algorytmem base64 obrazu: + + navigator.camera.getPicture(onSuccess, onFail, { quality: 50, + destinationType: Camera.DestinationType.DATA_URL + }); + + function onSuccess(imageData) { + var image = document.getElementById('myImage'); + image.src = "data:image/jpeg;base64," + imageData; + } + + function onFail(message) { + alert('Failed because: ' + message); + } + + +Zrób zdjęcie i pobrać lokalizacji pliku obrazu: + + navigator.camera.getPicture(onSuccess, onFail, { quality: 50, + destinationType: Camera.DestinationType.FILE_URI }); + + function onSuccess(imageURI) { + var image = document.getElementById('myImage'); + image.src = imageURI; + } + + function onFail(message) { + alert('Failed because: ' + message); + } + + +#### Preferencje (iOS) + + * **CameraUsesGeolocation** (boolean, wartość domyślna to false). Do przechwytywania JPEG, zestaw do true, aby uzyskać danych geolokalizacyjnych w nagłówku EXIF. To spowoduje wniosek o geolokalizacji uprawnienia, jeśli zestaw na wartość true. + + + + +#### Amazon ogień OS dziwactwa + +Amazon ogień OS używa intencje do rozpoczęcia działalności aparatu na urządzenie do przechwytywania obrazów, i na telefony z pamięci, Cordova aktywność może zostać zabity. W tym scenariuszu obraz mogą nie być wyświetlane po przywróceniu aktywności cordova. + +#### Dziwactwa Androida + +Android używa intencje do rozpoczęcia działalności aparatu na urządzenie do przechwytywania obrazów, i na telefony z pamięci, Cordova aktywność może zostać zabity. W tym scenariuszu obraz mogą nie być wyświetlane po przywróceniu aktywności Cordova. + +#### Quirks przeglądarki + +Może zwracać tylko zdjęcia jako obraz w formacie algorytmem base64. + +#### Firefox OS dziwactwa + +Aparat plugin jest obecnie implementowane za pomocą [Działania sieci Web](https://hacks.mozilla.org/2013/01/introducing-web-activities/). + +#### Dziwactwa iOS + +W jednej z funkcji wywołania zwrotnego w tym JavaScript `alert()` może powodować problemy. Owinąć w `setTimeout()` umożliwia wybór obrazu iOS lub popover całkowicie zamknąć zanim wyświetli alert alert: + + setTimeout(function() { + // do your thing here! + }, 0); + + +#### Dziwactwa Windows Phone 7 + +Wywoływanie aparat native aplikacji, podczas gdy urządzenie jest podłączone przez Zune nie działa i powoduje błąd wywołania zwrotnego. + +#### Dziwactwa Tizen + +Tizen obsługuje tylko `destinationType` z `Camera.DestinationType.FILE_URI` i `sourceType` z `Camera.PictureSourceType.PHOTOLIBRARY`. + +## CameraOptions + +Opcjonalne parametry, aby dostosować ustawienia aparatu. + + { quality : 75, + destinationType : Camera.DestinationType.DATA_URL, + sourceType : Camera.PictureSourceType.CAMERA, + allowEdit : true, + encodingType: Camera.EncodingType.JPEG, + targetWidth: 100, + targetHeight: 100, + popoverOptions: CameraPopoverOptions, + saveToPhotoAlbum: false }; + + + * **quality**: Jakość zapisywanego obrazu, wyrażona w przedziale 0-100, gdzie 100 zazwyczaj jest maksymalną rozdzielczością bez strat w czasie kompresji pliku. Wartością domyślną jest 50. *(Liczba)* (Pamiętaj, że informacja o rozdzielczości aparatu jest niedostępna.) + + * **destinationType**: Wybierz format zwracanej wartości. Wartością domyślną jest FILE_URI. Zdefiniowane w `navigator.camera.DestinationType` *(numer)* + + Camera.DestinationType = { + DATA_URL : 0, // Return image as base64-encoded string + FILE_URI : 1, // Return image file URI + NATIVE_URI : 2 // Return image native URI (e.g., assets-library:// on iOS or content:// on Android) + }; + + + * **sourceType**: Ustaw źródło obrazu. Wartością domyślną jest aparat fotograficzny. Zdefiniowane w `navigator.camera.PictureSourceType` *(numer)* + + Camera.PictureSourceType = { + PHOTOLIBRARY : 0, + CAMERA : 1, + SAVEDPHOTOALBUM : 2 + }; + + + * **allowEdit**: Pozwala na prostą edycję obrazu przed zaznaczeniem. *(Boolean)* + + * **encodingType**: Wybierz plik obrazu zwracany jest kodowanie. Domyślnie jest JPEG. Zdefiniowane w `navigator.camera.EncodingType` *(numer)* + + Camera.EncodingType = { + JPEG : 0, // Return JPEG encoded image + PNG : 1 // Return PNG encoded image + }; + + + * **targetWidth**: Szerokość w pikselach skalowanego obrazu. Musi być użyte z **targetHeight**. Współczynnik proporcji pozostaje stały. *(Liczba)* + + * **targetHeight**: Wysokość w pikselach skalowanego obrazu. Musi być użyte z **targetWidth**. Współczynnik proporcji pozostaje stały. *(Liczba)* + + * **mediaType**: Ustawia typ nośnika, z którego będzie wybrany. Działa tylko wtedy, gdy `PictureSourceType` jest `PHOTOLIBRARY` lub `SAVEDPHOTOALBUM`. Zdefiniowane w `nagivator.camera.MediaType` *(Liczba)* + + Camera.MediaType = { + PICTURE: 0, // allow selection of still pictures only. DEFAULT. Will return format specified via DestinationType + VIDEO: 1, // allow selection of video only, WILL ALWAYS RETURN FILE_URI + ALLMEDIA : 2 // allow selection from all media types + }; + + + * **correctOrientation**: Obraca obraz aby skorygować orientację urządzenia podczas przechwytywania. *(Boolean)* + + * **saveToPhotoAlbum**: Po przechwyceniu zapisuje na urządzeniu obraz w albumie na zdjęcia. *(Boolean)* + + * **popoverOptions**: Opcja tylko dla platformy iOS, która określa położenie wyskakującego okna na iPadzie. Zdefiniowane w `CameraPopoverOptions`. + + * **cameraDirection**: Wybierz aparat do korzystania (lub z powrotem przodem). Wartością domyślną jest z powrotem. Zdefiniowane w `navigator.camera.Direction` *(numer)* + + Camera.Direction = { + BACK : 0, // Use the back-facing camera + FRONT : 1 // Use the front-facing camera + }; + + +#### Amazon ogień OS dziwactwa + + * Jakakolwiek wartość w `cameraDirection` skutkuje użyciem tylnej kamery. + + * Parametr `allowEdit` jest ignorowany. + + * Oba parametry `Camera.PictureSourceType.PHOTOLIBRARY` oraz `Camera.PictureSourceType.SAVEDPHOTOALBUM` wyświetlają ten sam album ze zdjęciami. + +#### Dziwactwa Androida + + * Jakakolwiek wartość w `cameraDirection` skutkuje użyciem tylnej kamery. + + * Android również używa aktywność upraw dla allowEdit, choć upraw powinien pracować i faktycznie przejść przycięte zdjęcie Wróć do Cordova, ten tylko jeden który działa konsekwentnie jest ten, wiązany z aplikacji Google Plus zdjęcia. Inne rośliny mogą nie działać. + + * Oba parametry `Camera.PictureSourceType.PHOTOLIBRARY` oraz `Camera.PictureSourceType.SAVEDPHOTOALBUM` wyświetlają ten sam album ze zdjęciami. + +#### Jeżyna 10 dziwactwa + + * Parametr `quality` jest ignorowany. + + * Parametr `allowEdit` jest ignorowany. + + * Nie jest wspierane `Camera.MediaType`. + + * Parametr `correctOrientation` jest ignorowany. + + * Parametr `cameraDirection` jest ignorowany. + +#### Firefox OS dziwactwa + + * Parametr `quality` jest ignorowany. + + * `Camera.DestinationType`jest ignorowane i jest równa `1` (plik obrazu URI) + + * Parametr `allowEdit` jest ignorowany. + + * Ignoruje `PictureSourceType` parametr (użytkownik wybiera go w oknie dialogowym) + + * Ignoruje`encodingType` + + * Ignoruje `targetWidth` i`targetHeight` + + * Nie jest wspierane `Camera.MediaType`. + + * Parametr `correctOrientation` jest ignorowany. + + * Parametr `cameraDirection` jest ignorowany. + +#### Dziwactwa iOS + + * Ustaw `quality` poniżej 50 aby uniknąć błędów pamięci na niektórych urządzeniach. + + * Podczas korzystania z `destinationType.FILE_URI` , zdjęcia są zapisywane w katalogu tymczasowego stosowania. Zawartość katalogu tymczasowego stosowania jest usuwany po zakończeniu aplikacji. + +#### Dziwactwa Tizen + + * opcje nie są obsługiwane + + * zawsze zwraca FILE URI + +#### Windows Phone 7 i 8 dziwactwa + + * Parametr `allowEdit` jest ignorowany. + + * Parametr `correctOrientation` jest ignorowany. + + * Parametr `cameraDirection` jest ignorowany. + + * Ignoruje `saveToPhotoAlbum` parametr. Ważne: Wszystkie zdjęcia zrobione aparatem wp7/8 cordova API są zawsze kopiowane do telefonu w kamerze. W zależności od ustawień użytkownika może to też oznaczać że obraz jest automatycznie przesłane do ich OneDrive. Potencjalnie może to oznaczać, że obraz jest dostępne dla szerszego grona odbiorców niż Twoja aplikacja przeznaczona. Jeśli ten bloker aplikacji, trzeba będzie wdrożenie CameraCaptureTask, opisane na msdn: można także komentarz lub górę głosowanie powiązanych kwestii w [śledzenia błędów](https://issues.apache.org/jira/browse/CB-2083) + + * Ignoruje `mediaType` Właściwość `cameraOptions` jako SDK Windows Phone nie umożliwiają wybór filmów z PHOTOLIBRARY. + +## CameraError + +funkcja wywołania zwrotnego PrzyBłędzie, która zawiera komunikat o błędzie. + + function(message) { + // Show a helpful message + } + + +#### Opis + + * **message**: Natywny kod komunikatu zapewniany przez urządzenie. *(Ciąg znaków)* + +## cameraSuccess + +onSuccess funkcji wywołania zwrotnego, który dostarcza dane obrazu. + + function(imageData) { + // Do something with the image + } + + +#### Opis + + * **imageData**: Dane obrazu kodowane przy pomocy Base64 *lub* URI pliku obrazu, w zależności od użycia `cameraOptions`. *(Ciąg znaków)* + +#### Przykład + + // Show image + // + function cameraCallback(imageData) { + var image = document.getElementById('myImage'); + image.src = "data:image/jpeg;base64," + imageData; + } + + +## CameraPopoverHandle + +Uchwyt do okna dialogowego popover, stworzony przez `navigator.camera.getPicture`. + +#### Opis + + * **setPosition**: Set the position of the popover. Takes the `CameraPopoverOptions` that specify the new position. + +#### Obsługiwane platformy + +![](doc/img/android-fail.png) ![](doc/img/blackberry-fail.png) ![](doc/img/browser-fail.png) ![](doc/img/firefox-fail.png) ![](doc/img/fireos-fail.png) ![](doc/img/ios-success.png) ![](doc/img/windows-fail.png) ![](doc/img/wp8-fail.png) ![](doc/img/ubuntu-fail.png) + +#### Przykład + + var cameraPopoverHandle = navigator.camera.getPicture(onSuccess, onFail, + { destinationType: Camera.DestinationType.FILE_URI, + sourceType: Camera.PictureSourceType.PHOTOLIBRARY, + popoverOptions: new CameraPopoverOptions(300, 300, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY) + }); + + // Reposition the popover if the orientation changes. + window.onorientationchange = function() { + var cameraPopoverOptions = new CameraPopoverOptions(0, 0, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY); + cameraPopoverHandle.setPosition(cameraPopoverOptions); + } + + +## CameraPopoverOptions + +tylko do iOS parametrami, które określić kotwicy element lokalizacji i strzałka kierunku popover, przy wyborze zdjęć z iPad biblioteki lub album. + + { x : 0, + y : 32, + width : 320, + height : 480, + arrowDir : Camera.PopoverArrowDirection.ARROW_ANY + }; + + +#### Opis + + * **x**: współrzędna piksela x elementu ekranu, na którym zakotwiczone jest wyskakujące okno. *(Liczba)* + + * **y**: współrzędna piksela y elementu ekranu, na którym zakotwiczone jest wyskakujące okno. *(Liczba)* + + * **width**: szerokość w pikselach elementu ekranu, na którym zakotwiczone jest wyskakujące okno. *(Liczba)* + + * **height**: wysokość w pikselach elementu ekranu, na którym zakotwiczone jest wyskakujące okno. *(Liczba)* + + * **arrowDir**: Kierunek, który powinna wskazywać strzałka na wyskakującym oknie. Zdefiniowane w `Camera.PopoverArrowDirection` *(Liczba)* + + Camera.PopoverArrowDirection = { + ARROW_UP : 1, // matches iOS UIPopoverArrowDirection constants + ARROW_DOWN : 2, + ARROW_LEFT : 4, + ARROW_RIGHT : 8, + ARROW_ANY : 15 + }; + + +Należy pamiętać, że rozmiar popover może zmienić aby zmienić kierunek strzałki i orientacji ekranu. Upewnij się uwzględnić zmiany orientacji podczas określania położenia elementu kotwicy. + +## navigator.camera.cleanup + +Usuwa pośrednie zdjęcia zrobione przez aparat z czasowego składowania. + + navigator.camera.cleanup( cameraSuccess, cameraError ); + + +#### Opis + +Usuwa pliki obrazów pośrednich, które są przechowywane w pamięci tymczasowej po wywołaniu `camera.getPicture`. Ma zastosowanie tylko, gdy wartość `Camera.sourceType` jest równa `Camera.PictureSourceType.CAMERA` i `Camera.destinationType` jest równa `Camera.DestinationType.FILE_URI`. + +#### Obsługiwane platformy + +![](doc/img/android-fail.png) ![](doc/img/blackberry-fail.png) ![](doc/img/browser-fail.png) ![](doc/img/firefox-fail.png) ![](doc/img/fireos-fail.png) ![](doc/img/ios-success.png) ![](doc/img/windows-fail.png) ![](doc/img/wp8-fail.png) ![](doc/img/ubuntu-fail.png) + +#### Przykład + + navigator.camera.cleanup(onSuccess, onFail); + + function onSuccess() { + console.log("Camera cleanup success.") + } + + function onFail(message) { + alert('Failed because: ' + message); + } \ No newline at end of file diff --git a/plugins/cordova-plugin-camera/doc/pl/index.md b/plugins/cordova-plugin-camera/doc/pl/index.md new file mode 100644 index 0000000..f226698 --- /dev/null +++ b/plugins/cordova-plugin-camera/doc/pl/index.md @@ -0,0 +1,434 @@ + + +# cordova-plugin-camera + +Ten plugin definiuje obiekt globalny `navigator.camera`, który dostarcza API do robienia zdjęć i wybór zdjęć z biblioteki obrazów systemu. + +Mimo, że obiekt jest dołączony do globalnego zakresu `navigator`, to nie dostępne dopiero po zdarzeniu `deviceready`. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(navigator.camera); + } + + +## Instalacja + + cordova plugin add cordova-plugin-camera + + +## navigator.camera.getPicture + +Ma zdjęcia za pomocą aparatu, lub pobiera zdjęcia z urządzenia Galeria zdjęć. Obraz jest przekazywany do wywołania zwrotnego sukces jako kodowane algorytmem base64 `ciąg`, lub identyfikator URI dla pliku obrazu. Sama metoda zwraca obiekt `CameraPopoverHandle`, który może służyć do zmiany położenia pliku wyboru popover. + + navigator.camera.getPicture( cameraSuccess, cameraError, cameraOptions ); + + +### Opis + +Funkcja `camera.getPicture` otwiera urządzenia domyślnej aplikacji aparat fotograficzny ów pozwala użytkownik wobec chwycić zębami kino. To zachowanie występuje domyślnie, gdy `Camera.sourceType` jest równa `Camera.PictureSourceType.CAMERA`. Gdy użytkownik zaskoczy zdjęcie, ten aparat fotograficzny applicationâ zamyka i aplikacji jest przywracany. + +Jeśli `Camera.sourceType` jest równe `Camera.PictureSourceType.PHOTOLIBRARY` lub `Camera.PictureSourceType.SAVEDPHOTOALBUM`, wtedy zostanie wyświetlone okno dialogowe pozwalające użytkownikowi na wybór istniejącego obrazu. Funkcja `camera.getPicture` zwraca obiekt `CameraPopoverHandle`, który obsługuje zmianę położenia okna wyboru obrazu, np. po zmianie orientacji urządzenia. + +Zwracana wartość jest wysyłany do funkcji wywołania zwrotnego `cameraSuccess`, w jednym z następujących formatów, w zależności od określonego `cameraOptions`: + +* `String` zawierający obraz zakodowany przy pomocy base64. + +* `String` reprezentujący lokalizację pliku obrazu w lokalnym magazynie (domyślnie). + +Może rób, co chcesz z zakodowany obraz lub identyfikatora URI, na przykład: + +* Przedstawić obraz w tagu ``, jak w przykładzie poniżej + +* Zapisać lokalnie dane (`LocalStorage`, [Lawnchair][1], etc.) + +* Wysłać dane na zdalny serwer + + [1]: http://brianleroux.github.com/lawnchair/ + +**Uwaga**: zdjęcie rozdzielczości na nowsze urządzenia jest bardzo dobry. Zdjęcia wybrane z galerii urządzenia są nie przeskalowanych w dół do niższej jakości, nawet jeśli określono parametr `quality`. Aby uniknąć typowych problemów z pamięci, zestaw `Camera.destinationType` `FILE_URI` zamiast `DATA_URL`. + +### Obsługiwane platformy + +* Amazon Fire OS +* Android +* BlackBerry 10 +* Przeglądarka +* Firefox OS +* iOS +* Tizen +* Windows Phone 7 i 8 +* Windows 8 + +### Preferencje (iOS) + +* **CameraUsesGeolocation** (boolean, wartość domyślna to false). Do przechwytywania JPEG, zestaw do true, aby uzyskać danych geolokalizacyjnych w nagłówku EXIF. To spowoduje wniosek o geolokalizacji uprawnienia, jeśli zestaw na wartość true. + + + + +### Amazon ogień OS dziwactwa + +Amazon ogień OS używa intencje do rozpoczęcia działalności aparatu na urządzenie do przechwytywania obrazów, i na telefony z pamięci, Cordova aktywność może zostać zabity. W tym scenariuszu obraz mogą nie być wyświetlane po przywróceniu aktywności cordova. + +### Dziwactwa Androida + +Android używa intencje do rozpoczęcia działalności aparatu na urządzenie do przechwytywania obrazów, i na telefony z pamięci, Cordova aktywność może zostać zabity. W tym scenariuszu obraz mogą nie być wyświetlane po przywróceniu aktywności Cordova. + +### Quirks przeglądarki + +Może zwracać tylko zdjęcia jako obraz w formacie algorytmem base64. + +### Firefox OS dziwactwa + +Aparat plugin jest obecnie implementowane za pomocą [Działania sieci Web][2]. + + [2]: https://hacks.mozilla.org/2013/01/introducing-web-activities/ + +### Dziwactwa iOS + +W jednej z funkcji wywołania zwrotnego w tym JavaScript `alert()` może powodować problemy. Owinąć w `setTimeout()` umożliwia wybór obrazu iOS lub popover całkowicie zamknąć zanim wyświetli alert alert: + + setTimeout(function() { + // do your thing here! + }, 0); + + +### Dziwactwa Windows Phone 7 + +Wywoływanie aparat native aplikacji, podczas gdy urządzenie jest podłączone przez Zune nie działa i powoduje błąd wywołania zwrotnego. + +### Dziwactwa Tizen + +Tizen obsługuje tylko `destinationType` z `Camera.DestinationType.FILE_URI` i `sourceType` z `Camera.PictureSourceType.PHOTOLIBRARY`. + +### Przykład + +Zrób zdjęcie i pobrać go jako kodowane algorytmem base64 obrazu: + + navigator.camera.getPicture(onSuccess, onFail, { quality: 50, + destinationType: Camera.DestinationType.DATA_URL + }); + + function onSuccess(imageData) { + var image = document.getElementById('myImage'); + image.src = "data:image/jpeg;base64," + imageData; + } + + function onFail(message) { + alert('Failed because: ' + message); + } + + +Zrób zdjęcie i pobrać lokalizacji pliku obrazu: + + navigator.camera.getPicture(onSuccess, onFail, { quality: 50, + destinationType: Camera.DestinationType.FILE_URI }); + + function onSuccess(imageURI) { + var image = document.getElementById('myImage'); + image.src = imageURI; + } + + function onFail(message) { + alert('Failed because: ' + message); + } + + +## CameraOptions + +Opcjonalne parametry, aby dostosować ustawienia aparatu. + + { quality : 75, + destinationType : Camera.DestinationType.DATA_URL, + sourceType : Camera.PictureSourceType.CAMERA, + allowEdit : true, + encodingType: Camera.EncodingType.JPEG, + targetWidth: 100, + targetHeight: 100, + popoverOptions: CameraPopoverOptions, + saveToPhotoAlbum: false }; + + +### Opcje + +* **quality**: Jakość zapisywanego obrazu, wyrażona w przedziale 0-100, gdzie 100 zazwyczaj jest maksymalną rozdzielczością bez strat w czasie kompresji pliku. Wartością domyślną jest 50. *(Liczba)* (Pamiętaj, że informacja o rozdzielczości aparatu jest niedostępna.) + +* **destinationType**: Wybierz format zwracanej wartości. Wartością domyślną jest FILE_URI. Zdefiniowane w `navigator.camera.DestinationType` *(numer)* + + Camera.DestinationType = { + DATA_URL : 0, // Return image as base64-encoded string + FILE_URI : 1, // Return image file URI + NATIVE_URI : 2 // Return image native URI (e.g., assets-library:// on iOS or content:// on Android) + }; + + +* **sourceType**: Ustaw źródło obrazu. Wartością domyślną jest aparat fotograficzny. Zdefiniowane w `navigator.camera.PictureSourceType` *(numer)* + + Camera.PictureSourceType = { + PHOTOLIBRARY : 0, + CAMERA : 1, + SAVEDPHOTOALBUM : 2 + }; + + +* **allowEdit**: Pozwala na prostą edycję obrazu przed zaznaczeniem. *(Boolean)* + +* **encodingType**: Wybierz plik obrazu zwracany jest kodowanie. Domyślnie jest JPEG. Zdefiniowane w `navigator.camera.EncodingType` *(numer)* + + Camera.EncodingType = { + JPEG : 0, // Return JPEG encoded image + PNG : 1 // Return PNG encoded image + }; + + +* **targetWidth**: Szerokość w pikselach skalowanego obrazu. Musi być użyte z **targetHeight**. Współczynnik proporcji pozostaje stały. *(Liczba)* + +* **targetHeight**: Wysokość w pikselach skalowanego obrazu. Musi być użyte z **targetWidth**. Współczynnik proporcji pozostaje stały. *(Liczba)* + +* **mediaType**: Ustawia typ nośnika, z którego będzie wybrany. Działa tylko wtedy, gdy `PictureSourceType` jest `PHOTOLIBRARY` lub `SAVEDPHOTOALBUM`. Zdefiniowane w `nagivator.camera.MediaType` *(Liczba)* + + Camera.MediaType = { + PICTURE: 0, // allow selection of still pictures only. DEFAULT. Will return format specified via DestinationType + VIDEO: 1, // allow selection of video only, WILL ALWAYS RETURN FILE_URI + ALLMEDIA : 2 // allow selection from all media types + }; + + +* **correctOrientation**: Obraca obraz aby skorygować orientację urządzenia podczas przechwytywania. *(Boolean)* + +* **saveToPhotoAlbum**: Po przechwyceniu zapisuje na urządzeniu obraz w albumie na zdjęcia. *(Boolean)* + +* **popoverOptions**: Opcja tylko dla platformy iOS, która określa położenie wyskakującego okna na iPadzie. Zdefiniowane w `CameraPopoverOptions`. + +* **cameraDirection**: Wybierz aparat do korzystania (lub z powrotem przodem). Wartością domyślną jest z powrotem. Zdefiniowane w `navigator.camera.Direction` *(numer)* + + Camera.Direction = { + BACK : 0, // Use the back-facing camera + FRONT : 1 // Use the front-facing camera + }; + + +### Amazon ogień OS dziwactwa + +* Jakakolwiek wartość w `cameraDirection` skutkuje użyciem tylnej kamery. + +* Parametr `allowEdit` jest ignorowany. + +* Oba parametry `Camera.PictureSourceType.PHOTOLIBRARY` oraz `Camera.PictureSourceType.SAVEDPHOTOALBUM` wyświetlają ten sam album ze zdjęciami. + +### Dziwactwa Androida + +* Jakakolwiek wartość w `cameraDirection` skutkuje użyciem tylnej kamery. + +* Parametr `allowEdit` jest ignorowany. + +* Oba parametry `Camera.PictureSourceType.PHOTOLIBRARY` oraz `Camera.PictureSourceType.SAVEDPHOTOALBUM` wyświetlają ten sam album ze zdjęciami. + +### Jeżyna 10 dziwactwa + +* Parametr `quality` jest ignorowany. + +* Parametr `allowEdit` jest ignorowany. + +* Nie jest wspierane `Camera.MediaType`. + +* Parametr `correctOrientation` jest ignorowany. + +* Parametr `cameraDirection` jest ignorowany. + +### Firefox OS dziwactwa + +* Parametr `quality` jest ignorowany. + +* `Camera.DestinationType`jest ignorowane i jest równa `1` (plik obrazu URI) + +* Parametr `allowEdit` jest ignorowany. + +* Ignoruje `PictureSourceType` parametr (użytkownik wybiera go w oknie dialogowym) + +* Ignoruje`encodingType` + +* Ignoruje `targetWidth` i`targetHeight` + +* Nie jest wspierane `Camera.MediaType`. + +* Parametr `correctOrientation` jest ignorowany. + +* Parametr `cameraDirection` jest ignorowany. + +### Dziwactwa iOS + +* Ustaw `quality` poniżej 50 aby uniknąć błędów pamięci na niektórych urządzeniach. + +* Podczas korzystania z `destinationType.FILE_URI` , zdjęcia są zapisywane w katalogu tymczasowego stosowania. Zawartość katalogu tymczasowego stosowania jest usuwany po zakończeniu aplikacji. + +### Dziwactwa Tizen + +* opcje nie są obsługiwane + +* zawsze zwraca FILE URI + +### Windows Phone 7 i 8 dziwactwa + +* Parametr `allowEdit` jest ignorowany. + +* Parametr `correctOrientation` jest ignorowany. + +* Parametr `cameraDirection` jest ignorowany. + +* Ignoruje `saveToPhotoAlbum` parametr. Ważne: Wszystkie zdjęcia zrobione aparatem wp7/8 cordova API są zawsze kopiowane do telefonu w kamerze. W zależności od ustawień użytkownika może to też oznaczać że obraz jest automatycznie przesłane do ich OneDrive. Potencjalnie może to oznaczać, że obraz jest dostępne dla szerszego grona odbiorców niż Twoja aplikacja przeznaczona. Jeśli ten bloker aplikacji, trzeba będzie wdrożenie CameraCaptureTask, opisane na msdn: można także komentarz lub górę głosowanie powiązanych kwestii w [śledzenia błędów][3] + +* Ignoruje `mediaType` Właściwość `cameraOptions` jako SDK Windows Phone nie umożliwiają wybór filmów z PHOTOLIBRARY. + + [3]: https://issues.apache.org/jira/browse/CB-2083 + +## CameraError + +funkcja wywołania zwrotnego PrzyBłędzie, która zawiera komunikat o błędzie. + + function(message) { + // Show a helpful message + } + + +### Parametry + +* **message**: Natywny kod komunikatu zapewniany przez urządzenie. *(Ciąg znaków)* + +## cameraSuccess + +onSuccess funkcji wywołania zwrotnego, który dostarcza dane obrazu. + + function(imageData) { + // Do something with the image + } + + +### Parametry + +* **imageData**: Dane obrazu kodowane przy pomocy Base64 *lub* URI pliku obrazu, w zależności od użycia `cameraOptions`. *(Ciąg znaków)* + +### Przykład + + // Show image + // + function cameraCallback(imageData) { + var image = document.getElementById('myImage'); + image.src = "data:image/jpeg;base64," + imageData; + } + + +## CameraPopoverHandle + +Uchwyt do okna dialogowego popover, stworzony przez `navigator.camera.getPicture`. + +### Metody + +* **setPosition**: Ustawia pozycję wyskakującego okna. + +### Obsługiwane platformy + +* iOS + +### setPosition + +Ustaw pozycję popover. + +**Parametry**: + +* `cameraPopoverOptions`: `CameraPopoverOptions`, która określa nową pozycję + +### Przykład + + var cameraPopoverHandle = navigator.camera.getPicture(onSuccess, onFail, + { destinationType: Camera.DestinationType.FILE_URI, + sourceType: Camera.PictureSourceType.PHOTOLIBRARY, + popoverOptions: new CameraPopoverOptions(300, 300, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY) + }); + + // Reposition the popover if the orientation changes. + window.onorientationchange = function() { + var cameraPopoverOptions = new CameraPopoverOptions(0, 0, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY); + cameraPopoverHandle.setPosition(cameraPopoverOptions); + } + + +## CameraPopoverOptions + +tylko do iOS parametrami, które określić kotwicy element lokalizacji i strzałka kierunku popover, przy wyborze zdjęć z iPad biblioteki lub album. + + { x : 0, + y : 32, + width : 320, + height : 480, + arrowDir : Camera.PopoverArrowDirection.ARROW_ANY + }; + + +### CameraPopoverOptions + +* **x**: współrzędna piksela x elementu ekranu, na którym zakotwiczone jest wyskakujące okno. *(Liczba)* + +* **y**: współrzędna piksela y elementu ekranu, na którym zakotwiczone jest wyskakujące okno. *(Liczba)* + +* **width**: szerokość w pikselach elementu ekranu, na którym zakotwiczone jest wyskakujące okno. *(Liczba)* + +* **height**: wysokość w pikselach elementu ekranu, na którym zakotwiczone jest wyskakujące okno. *(Liczba)* + +* **arrowDir**: Kierunek, który powinna wskazywać strzałka na wyskakującym oknie. Zdefiniowane w `Camera.PopoverArrowDirection` *(Liczba)* + + Camera.PopoverArrowDirection = { + ARROW_UP : 1, // matches iOS UIPopoverArrowDirection constants + ARROW_DOWN : 2, + ARROW_LEFT : 4, + ARROW_RIGHT : 8, + ARROW_ANY : 15 + }; + + +Należy pamiętać, że rozmiar popover może zmienić aby zmienić kierunek strzałki i orientacji ekranu. Upewnij się uwzględnić zmiany orientacji podczas określania położenia elementu kotwicy. + +## navigator.camera.cleanup + +Usuwa pośrednie zdjęcia zrobione przez aparat z czasowego składowania. + + navigator.camera.cleanup( cameraSuccess, cameraError ); + + +### Opis + +Usuwa pliki obrazów pośrednich, które są przechowywane w pamięci tymczasowej po wywołaniu `camera.getPicture`. Ma zastosowanie tylko, gdy wartość `Camera.sourceType` jest równa `Camera.PictureSourceType.CAMERA` i `Camera.destinationType` jest równa `Camera.DestinationType.FILE_URI`. + +### Obsługiwane platformy + +* iOS + +### Przykład + + navigator.camera.cleanup(onSuccess, onFail); + + function onSuccess() { + console.log("Camera cleanup success.") + } + + function onFail(message) { + alert('Failed because: ' + message); + } diff --git a/plugins/cordova-plugin-camera/doc/ru/index.md b/plugins/cordova-plugin-camera/doc/ru/index.md new file mode 100644 index 0000000..f93609c --- /dev/null +++ b/plugins/cordova-plugin-camera/doc/ru/index.md @@ -0,0 +1,417 @@ + + +# cordova-plugin-camera + +Этот плагин предоставляет API для съемки и для выбора изображения из библиотеки изображений системы. + + cordova plugin add cordova-plugin-camera + + +## navigator.camera.getPicture + +Снимает фотографию с помощью камеры, или получает фотографию из галереи изображений устройства. Изображение передается на функцию обратного вызова успешного завершения как `String` в base64-кодировке, или как URI указывающего на файл изображения. Метод возвращает объект `CameraPopoverHandle`, который может использоваться для перемещения инструмента выбора файла. + + navigator.camera.getPicture( cameraSuccess, cameraError, cameraOptions ); + + +### Описание + +Функция `camera.getPicture` открывает приложение камеры устройства, которое позволяет снимать фотографии. Это происходит по умолчанию, когда `Camera.sourceType` равно `Camera.PictureSourceType.CAMERA` . Как только пользователь делает снимок,приложение камеры закрывается и приложение восстанавливается. + +Если `Camera.sourceType` является `Camera.PictureSourceType.PHOTOLIBRARY` или `Camera.PictureSourceType.SAVEDPHOTOALBUM` , то показывается диалоговое окно, которое позволяет пользователям выбрать существующее изображение. Функция `camera.getPicture` возвращает объект `CameraPopoverHandle` объект, который может использоваться для перемещения диалога выбора изображения, например, при изменении ориентации устройства. + +Возвращаемое значение отправляется в функцию обратного вызова `cameraSuccess` в одном из следующих форматов, в зависимости от параметра `cameraOptions` : + +* A объект `String` содержащий фото изображение в base64-кодировке. + +* Объект `String` представляющий расположение файла изображения на локальном хранилище (по умолчанию). + +Вы можете сделать все, что угодно вы хотите с закодированным изображением или URI, например: + +* Отобразить изображение с помощью тега ``, как показано в примере ниже + +* Сохранять данные локально (`LocalStorage`, [Lawnchair][1], и т.д.) + +* Отправлять данные на удаленный сервер + + [1]: http://brianleroux.github.com/lawnchair/ + +**Примечание**: разрешение фото на более новых устройствах является достаточно хорошим. Фотографии из галереи устройства не масштабируются к более низкому качеству, даже если указан параметр `quality`. Чтобы избежать общих проблем с памятью, установите `Camera.destinationType` в `FILE_URI` вместо `DATA_URL`. + +### Поддерживаемые платформы + +* Amazon Fire OS +* Android +* BlackBerry 10 +* Обозреватель +* Firefox OS +* iOS +* Tizen +* Windows Phone 7 и 8 +* Windows 8 + +### Предпочтения (iOS) + +* **CameraUsesGeolocation** (логическое значение, по умолчанию false). Для захвата изображения JPEG, значение true, чтобы получить данные геопозиционирования в заголовке EXIF. Это вызовет запрос на разрешения геолокации, если задано значение true. + + + + +### Особенности Amazon Fire OS + +Amazon Fire OS используют намерения для запуска активности камеры на устройстве для съемки фотографий, и на устройствах с низким объемам памяти, активность Cordova может быть завершена. В этом случае изображение может не появиться при восстановлении активности Cordova. + +### Особенности Android + +Android используют намерения для запуска активности камеры на устройстве для съемки фотографий, и на устройствах с низким объемам памяти, активность Cordova может быть завершена. В этом случае изображение может не появиться при восстановлении активности Cordova. + +### Браузер причуды + +Может возвращать только фотографии как изображения в кодировке base64. + +### Особенности Firefox OS + +Плагин Camera на данный момент реализован с использованием [Web Activities][2]. + + [2]: https://hacks.mozilla.org/2013/01/introducing-web-activities/ + +### Особенности iOS + +Включение функции JavaScript `alert()` в любой из функций обратного вызова функции может вызвать проблемы. Оберните вызов alert в `setTimeout()` для позволения окну выбора изображений iOS полностью закрыться перед отображение оповещения: + + setTimeout(function() {/ / ваши вещи!}, 0); + + +### Особенности Windows Phone 7 + +Вызов встроенного приложения камеры, в то время как устройство подключено к Zune не работает, и инициирует обратный вызов для ошибки. + +### Особенности Tizen + +Tizen поддерживает только значение `destinationType` равное `Camera.DestinationType.FILE_URI` и значение `sourceType` равное `Camera.PictureSourceType.PHOTOLIBRARY`. + +### Пример + +Сделайте фотографию и получите его как изображение в base64-кодировке: + + navigator.camera.getPicture(onSuccess, onFail, { quality: 50, + destinationType: Camera.DestinationType.DATA_URL + }); + + function onSuccess(imageData) { + var image = document.getElementById('myImage'); + image.src = "data:image/jpeg;base64," + imageData; + } + + function onFail(message) { + alert('Failed because: ' + message); + } + + +Сделайте фотографию и получить расположение файла с изображением: + + navigator.camera.getPicture(onSuccess, onFail, { quality: 50, + destinationType: Camera.DestinationType.FILE_URI }); + + function onSuccess(imageURI) { + var image = document.getElementById('myImage'); + image.src = imageURI; + } + + function onFail(message) { + alert('Failed because: ' + message); + } + + +## CameraOptions + +Необязательные параметры для настройки параметров камеры. + + { quality : 75, + destinationType : Camera.DestinationType.DATA_URL, + sourceType : Camera.PictureSourceType.CAMERA, + allowEdit : true, + encodingType: Camera.EncodingType.JPEG, + targetWidth: 100, + targetHeight: 100, + popoverOptions: CameraPopoverOptions, + saveToPhotoAlbum: false }; + + +### Параметры + +* **quality**: качество сохраняемого изображения, выражается в виде числа в диапазоне от 0 до 100, где 100 является обычно полным изображением без потери качества при сжатии. Значение по умолчанию — 50. *(Число)* (Обратите внимание, что информация о разрешении камеры недоступна.) + +* **параметр destinationType**: выберите формат возвращаемого значения. Значение по умолчанию — FILE_URI. Определяется в `navigator.camera.DestinationType` *(число)* + + Camera.DestinationType = { + DATA_URL: 0, / / возвращение изображения в base64-кодировке строки + FILE_URI: 1, / / возврат файла изображения URI + NATIVE_URI: 2 / / возвращение образа собственного URI (например, Библиотека активов: / / на iOS или содержание: / / на андроиде) + }; + + +* **тип источника**: установить источник рисунка. По умолчанию используется камера. Определяется в `navigator.camera.PictureSourceType` *(число)* + + Camera.PictureSourceType = { + PHOTOLIBRARY: 0, + CAMERA: 1, + SAVEDPHOTOALBUM: 2 + }; + + +* **allowEdit**: позволит редактирование изображения средствами телефона перед окончательным выбором изображения. *(Логический)* + +* **Тип_шифрования**: выберите возвращенный файл в кодировку. Значение по умолчанию — JPEG. Определяется в `navigator.camera.EncodingType` *(число)* + + Camera.EncodingType = { + JPEG: 0, // возвращает изображение в формате JPEG + PNG: 1 // возвращает рисунок в формате PNG + }; + + +* **targetWidth**: ширина изображения в пикселах к которой необходимо осуществить масштабирование. Это значение должно использоваться совместно с **targetHeight**. Пропорции изображения останутся неизменными. *(Число)* + +* **targetHeight**: высота изображения в пикселах к которой необходимо осуществить масштабирование. Это значение должно использоваться совместно с **targetWidth**. Пропорции изображения останутся неизменными. *(Число)* + +* **тип носителя**: Установите источник получения изображения, из которого надо выбрать изображение. Работает только если `PictureSourceType` равно `PHOTOLIBRARY` или `SAVEDPHOTOALBUM` . Определяется в `nagivator.camera.MediaType` *(число)* + + Camera.MediaType = { + PICTURE: 0, / / разрешить выбор только сохраненных изображений. DEFAULT. Will return format specified via DestinationType + VIDEO: 1, // allow selection of video only, WILL ALWAYS RETURN FILE_URI + ALLMEDIA : 2 // allow selection from all media types + }; + + +* **correctOrientation**: вращает изображение, чтобы внести исправления к ориентации устройства во время захвата. *(Логический)* + +* **saveToPhotoAlbum**: сохранить изображение в фотоальбом на устройстве после захвата. *(Логическое)* + +* **popoverOptions**: только для iOS параметры, которые определяют местоположение инструмента в iPad. Определены в`CameraPopoverOptions`. + +* **cameraDirection**: выбрать камеру для использования (передней или задней стороне). Значение по умолчанию — обратно. Определяется в `navigator.camera.Direction` *(число)* + + Camera.Direction = { + BACK : 0, // Use the back-facing camera + FRONT : 1 // Use the front-facing camera + }; + + +### Особенности Amazon Fire OS + +* Любое значение `cameraDirection` возвращает фотографию сделанную задней камерой. + +* Игнорирует параметр `allowEdit`. + +* Оба параметра `Camera.PictureSourceType.PHOTOLIBRARY` и `Camera.PictureSourceType.SAVEDPHOTOALBUM` отображают один и тот же фотоальбом. + +### Особенности Android + +* Любое значение `cameraDirection` возвращает фотографию сделанную задней камерой. + +* Игнорирует параметр `allowEdit`. + +* Оба параметра `Camera.PictureSourceType.PHOTOLIBRARY` и `Camera.PictureSourceType.SAVEDPHOTOALBUM` отображают один и тот же фотоальбом. + +### Особенности BlackBerry 10 + +* Игнорирует `quality` параметр. + +* Игнорирует параметр `allowEdit`. + +* `Camera.MediaType` не поддерживается. + +* Игнорирует параметр `correctOrientation`. + +* Игнорирует параметр `cameraDirection`. + +### Особенности Firefox OS + +* Игнорирует `quality` параметр. + +* Значение `Camera.DestinationType` игнорируется и равно `1` (URI для файла изображения) + +* Игнорирует параметр `allowEdit`. + +* Игнорирует параметр `PictureSourceType` (пользователь выбирает его в диалоговом окне) + +* Игнорирует параметр `encodingType` + +* Игнорирует `targetWidth` и `targetHeight` + +* `Camera.MediaType` не поддерживается. + +* Игнорирует параметр `correctOrientation`. + +* Игнорирует параметр `cameraDirection`. + +### Особенности iOS + +* Установите `quality` ниже 50, для того чтобы избежать ошибок памяти на некоторых устройствах. + +* При использовании `destinationType.FILE_URI` , фотографии сохраняются во временном каталоге приложения. Содержимое приложения временного каталога удаляется при завершении приложения. + +### Особенности Tizen + +* options, не поддерживается + +* всегда возвращает URI файла + +### Особенности Windows Phone 7 и 8 + +* Игнорирует параметр `allowEdit`. + +* Игнорирует параметр `correctOrientation`. + +* Игнорирует параметр `cameraDirection`. + +* Игнорирует `saveToPhotoAlbum` параметр. Важно: Все изображения, снятые камерой wp7/8 cordova API всегда копируются в рулон камеры телефона. В зависимости от параметров пользователя это также может означать, что изображение автоматически загружены на их OneDrive. Потенциально это может означать, что этот образ доступен для более широкой аудитории, чем ваше приложение предназначено. Если этот блокатор для вашего приложения, вам нужно будет осуществить CameraCaptureTask, как описано на сайте msdn: вы можете также комментарий или вверх голосование связанный с этим вопрос [отслеживания][3] + +* Игнорирует свойство `mediaType` объекта `cameraOptions` так как Windows Phone SDK не предоставляет способ выбрать видео из PHOTOLIBRARY. + + [3]: https://issues.apache.org/jira/browse/CB-2083 + +## CameraError + +Функция обратного вызова вызываемая в случае возникновения ошибки. + + function(message) { + // Show a helpful message + } + + +### Параметры + +* **сообщение**: сообщение об ошибке предоставляемое платформой устройства. *(Строка)* + +## cameraSuccess + +Функция обратного вызова onSuccess, получающая данные изображения. + + function(imageData) { + // Do something with the image + } + + +### Параметры + +* **imageData**: Данные изображения в Base64 кодировке, *или* URI, в зависимости от применяемых параметров `cameraOptions`. *(Строка)* + +### Пример + + // Show image + // + function cameraCallback(imageData) { + var image = document.getElementById('myImage'); + image.src = "data:image/jpeg;base64," + imageData; + } + + +## CameraPopoverHandle + +Дескриптор диалогового окна инструмента, созданный `navigator.camera.getPicture`. + +### Методы + +* **setPosition**: Задайте положение инструмента выбора изображения. + +### Поддерживаемые платформы + +* iOS + +### setPosition + +Устанавливает положение инструмента выбора изображения. + +**Параметры**: + +* `cameraPopoverOptions`: Объект `CameraPopoverOptions`, определяющий новое положение + +### Пример + + var cameraPopoverHandle = navigator.camera.getPicture(onSuccess, onFail, + { destinationType: Camera.DestinationType.FILE_URI, + sourceType: Camera.PictureSourceType.PHOTOLIBRARY, + popoverOptions: new CameraPopoverOptions(300, 300, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY) + }); + + // Reposition the popover if the orientation changes. + window.onorientationchange = function() { + var cameraPopoverOptions = new CameraPopoverOptions(0, 0, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY); + cameraPopoverHandle.setPosition(cameraPopoverOptions); + } + + +## CameraPopoverOptions + +Параметры только для iOS, которые определяют расположение элемента привязки и направление стрелки инструмента при выборе изображений из библиотеки изображений iPad или альбома. + + {x: 0, y: 32, ширина: 320, высота: 480, arrowDir: Camera.PopoverArrowDirection.ARROW_ANY}; + + +### CameraPopoverOptions + +* **x**: x координата в пикселях элемента экрана, на котором закрепить инструмента. *(Число)* + +* **x**: y координата в пикселях элемента экрана, на котором закрепить инструмента. *(Число)* + +* **width**: ширина в пикселях элемента экрана, на котором закрепить инструмент выбора изображения. *(Число)* + +* **height**: высота в пикселях элемента экрана, на котором закрепить инструмент выбора изображения. *(Число)* + +* **arrowDir**: Направление, куда должна указывать стрелка на инструменте. Определено в `Camera.PopoverArrowDirection` *(число)* + + Camera.PopoverArrowDirection = { + ARROW_UP : 1, // matches iOS UIPopoverArrowDirection constants + ARROW_DOWN : 2, + ARROW_LEFT : 4, + ARROW_RIGHT : 8, + ARROW_ANY : 15 + }; + + +Обратите внимание, что размер инструмента может изменяться для корректировки в зависимости направлении стрелки и ориентации экрана. Убедитесь, что учитываете возможные изменения ориентации при указании расположения элемента привязки. + +## navigator.camera.cleanup + +Удаляет промежуточные фотографии, сделанные камерой из временного хранилища. + + navigator.camera.cleanup( cameraSuccess, cameraError ); + + +### Описание + +Удаляет промежуточные файлы изображений, которые хранятся во временном хранилище после вызова метода `camera.getPicture` . Применяется только тогда, когда значение `Camera.sourceType` равно `Camera.PictureSourceType.CAMERA` и `Camera.destinationType` равняется `Camera.DestinationType.FILE_URI`. + +### Поддерживаемые платформы + +* iOS + +### Пример + + navigator.camera.cleanup(onSuccess, onFail); + + function onSuccess() { + console.log("Camera cleanup success.") + } + + function onFail(message) { + alert('Failed because: ' + message); + } diff --git a/plugins/cordova-plugin-camera/doc/zh/README.md b/plugins/cordova-plugin-camera/doc/zh/README.md new file mode 100644 index 0000000..2f7c9e6 --- /dev/null +++ b/plugins/cordova-plugin-camera/doc/zh/README.md @@ -0,0 +1,421 @@ + + +# cordova-plugin-camera + +[![Build Status](https://travis-ci.org/apache/cordova-plugin-camera.svg)](https://travis-ci.org/apache/cordova-plugin-camera) + +這個外掛程式定義了一個全球 `navigator.camera` 物件,它提供了 API,拍照,從系統的圖像庫中選擇圖像。 + +雖然該物件附加到全球範圍內 `導航器`,它不可用直到 `deviceready` 事件之後。 + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(navigator.camera); + } + + +## 安裝 + + cordova plugin add cordova-plugin-camera + + +## API + + * 相機 + * navigator.camera.getPicture(success, fail, options) + * CameraOptions + * CameraPopoverHandle + * CameraPopoverOptions + * navigator.camera.cleanup + +## navigator.camera.getPicture + +需要一張照片,使用相機,或從設備的圖像庫檢索一張照片。 圖像被傳遞給成功回檔的 base64 編碼 `String`,或作為 URI 為影像檔。 該方法本身返回一個 `CameraPopoverHandle` 物件,它可以用來重新置放檔選擇氣泡框。 + + navigator.camera.getPicture(cameraSuccess, cameraError, cameraOptions); + + +#### 說明 + +`camera.getPicture` 函數打開該設備的預設攝像頭應用程式,允許使用者拍照。 `Camera.sourceType` 等於 `Camera.PictureSourceType.CAMERA` 時,預設情況下,發生此行為。 一旦使用者打斷了他的照片,相機應用程式關閉,且應用程式還原。 + +如果 `Camera.sourceType` 是 `Camera.PictureSourceType.PHOTOLIBRARY` 或 `Camera.PictureSourceType.SAVEDPHOTOALBUM`,然後顯示一個對話方塊,允許使用者選擇一個現有的圖像。 `camera.getPicture` 函數返回一個 `CameraPopoverHandle` 物件,它可以用於重新置放圖像選擇的對話方塊,例如,當設備的方向變化。 + +傳回值是發送到 `cameraSuccess` 回呼函數中,在以下的格式,具體取決於指定的 `cameraOptions` 之一: + + * A `String` 包含的 base64 編碼的照片圖像。 + + * A `String` 表示在本機存放區 (預設值) 上的影像檔位置。 + +你可以做任何你想要的編碼的圖像或 URI,例如: + + * 呈現在圖像 `` 標記,如下面的示例所示 + + * 保存本地的資料 ( `LocalStorage` , [Lawnchair](http://brianleroux.github.com/lawnchair/),等等.) + + * 將資料發佈到遠端伺服器 + +**注**: 在更新設備上的照片解析度是很好。 選擇從設備的庫的照片是不壓縮螢幕使其以較低的品質,即使指定了一個 `quality` 參數。 要避免常見的記憶體問題,請將 `Camera.destinationType` 設置為 `FILE_URI`,而不是 `DATA_URL`. + +#### 支援的平臺 + +![](doc/img/android-success.png) ![](doc/img/blackberry-success.png) ![](doc/img/browser-success.png) ![](doc/img/firefox-success.png) ![](doc/img/fireos-success.png) ![](doc/img/ios-success.png) ![](doc/img/windows-success.png) ![](doc/img/wp8-success.png) ![](doc/img/ubuntu-success.png) + +#### 示例 + +拍一張照片,並檢索它作為一個 base64 編碼的圖像: + + navigator.camera.getPicture(onSuccess, onFail, { quality: 50, + destinationType: Camera.DestinationType.DATA_URL + }); + + function onSuccess(imageData) { + var image = document.getElementById('myImage'); + image.src = "data:image/jpeg;base64," + imageData; + } + + function onFail(message) { + alert('Failed because: ' + message); + } + + +拍一張照片和檢索圖像的檔位置: + + navigator.camera.getPicture(onSuccess, onFail, { quality: 50, + destinationType: Camera.DestinationType.FILE_URI }); + + function onSuccess(imageURI) { + var image = document.getElementById('myImage'); + image.src = imageURI; + } + + function onFail(message) { + alert('Failed because: ' + message); + } + + +#### 首選項 (iOS) + + * **CameraUsesGeolocation**(布林值,預設值為 false)。 用於捕獲 jpeg 檔,設置為 true,以在 EXIF 頭資訊中獲取地理定位資料。 這將觸發請求的地理位置的許可權,如果設置為 true。 + + + + +#### 亞馬遜火 OS 怪癖 + +亞馬遜火 OS 使用意圖啟動相機活動設備來捕捉圖像上, 和手機上記憶體不足,科爾多瓦活動可能被殺害。 在這種情況下,可能不會顯示圖像時恢復了科爾多瓦活動。 + +#### Android 的怪癖 + +Android 使用意圖以啟動相機活動設備來捕捉圖像上, 和手機上記憶體不足,科爾多瓦活動可能被殺害。 在這種情況下,可能不會顯示圖像時恢復了科爾多瓦活動。 + +#### 瀏覽器的怪癖 + +可以只返回照片作為 base64 編碼的圖像。 + +#### 火狐瀏覽器作業系統的怪癖 + +觀景窗外掛程式目前實施使用 [Web 活動](https://hacks.mozilla.org/2013/01/introducing-web-activities/). + +#### iOS 的怪癖 + +包括 JavaScript `alert ()` 中的回呼函數會導致問題。 包裝內 `setTimeout()` 允許 iOS 圖像選取器或氣泡框以完全關閉之前,警報將顯示警報: + + setTimeout(function() { + // do your thing here! + }, 0); + + +#### Windows Phone 7 的怪癖 + +調用本機攝像頭應用程式,而通過 Zune 所連接的設備不能工作,並且觸發錯誤回檔。 + +#### Tizen 怪癖 + +泰只支援 `destinationType` 的 `Camera.DestinationType.FILE_URI` 和 `Camera.PictureSourceType.PHOTOLIBRARY` 的 `sourceType`. + +## CameraOptions + +要自訂相機設置的可選參數。 + + { quality : 75, + destinationType : Camera.DestinationType.DATA_URL, + sourceType : Camera.PictureSourceType.CAMERA, + allowEdit : true, + encodingType: Camera.EncodingType.JPEG, + targetWidth: 100, + targetHeight: 100, + popoverOptions: CameraPopoverOptions, + saveToPhotoAlbum: false }; + + + * **品質**: 保存的圖像,表示為範圍 0-100,100,是通常全解析度,無損失從檔案壓縮的品質。 預設值為 50。 *(人數)*(請注意相機的解析度有關的資訊是不可用)。 + + * **可**: 選擇傳回值的格式。預設值是 FILE_URI。定義在 `navigator.camera.DestinationType` *(人數)* + + Camera.DestinationType = { + DATA_URL : 0, // Return image as base64-encoded string + FILE_URI : 1, // Return image file URI + NATIVE_URI : 2 // Return image native URI (e.g., assets-library:// on iOS or content:// on Android) + }; + + + * **時**: 設置圖片的來源。預設值是觀景窗。定義在 `navigator.camera.PictureSourceType` *(人數)* + + Camera.PictureSourceType = { + PHOTOLIBRARY : 0, + CAMERA : 1, + SAVEDPHOTOALBUM : 2 + }; + + + * **allowEdit**: 允許簡單編輯前選擇圖像。*(布林)* + + * **encodingType**: 選擇返回的影像檔的編碼。預設值為 JPEG。定義在 `navigator.camera.EncodingType` *(人數)* + + Camera.EncodingType = { + JPEG : 0, // Return JPEG encoded image + PNG : 1 // Return PNG encoded image + }; + + + * **targetWidth**: 向尺度圖像的圖元寬度。必須用**targetHeight**。縱橫比保持不變。*(人數)* + + * **targetHeight**: 以圖元為單位向尺度圖像的高度。必須用**targetWidth**。縱橫比保持不變。*(人數)* + + * **媒體類型**: 設置的媒體,從選擇類型。 時才起作用 `PictureSourceType` 是 `PHOTOLIBRARY` 或 `SAVEDPHOTOALBUM` 。 定義在 `nagivator.camera.MediaType` *(人數)* + + Camera.MediaType = { + PICTURE: 0, // allow selection of still pictures only. 預設情況。 Will return format specified via DestinationType + VIDEO: 1, // allow selection of video only, WILL ALWAYS RETURN FILE_URI + ALLMEDIA : 2 // allow selection from all media types + }; + + + * **correctOrientation**: 旋轉圖像,該設備時捕獲的定向的正確。*(布林)* + + * **saveToPhotoAlbum**: 將圖像保存到相冊在設備上捕獲後。*(布林)* + + * **popoverOptions**: 只有 iOS 在 iPad 中指定氣泡框位置的選項。在中定義`CameraPopoverOptions`. + + * **cameraDirection**: 選擇相機以使用 (前面或後面-面向)。預設值是背。定義在 `navigator.camera.Direction` *(人數)* + + Camera.Direction = { + BACK : 0, // Use the back-facing camera + FRONT : 1 // Use the front-facing camera + }; + + +#### 亞馬遜火 OS 怪癖 + + * 任何 `cameraDirection` 值回朝的照片中的結果。 + + * 忽略 `allowEdit` 參數。 + + * `Camera.PictureSourceType.PHOTOLIBRARY`和 `Camera.PictureSourceType.SAVEDPHOTOALBUM` 都顯示相同的相冊。 + +#### Android 的怪癖 + + * 任何 `cameraDirection` 值回朝的照片中的結果。 + + * 安卓也用於作物活動 allowEdit,即使作物應工作,實際上將裁剪的圖像傳回給科爾多瓦,那個唯一的作品一直是一個與谷歌加上照片應用程式捆綁在一起。 其他作物可能無法工作。 + + * `Camera.PictureSourceType.PHOTOLIBRARY`和 `Camera.PictureSourceType.SAVEDPHOTOALBUM` 都顯示相同的相冊。 + +#### 黑莓 10 怪癖 + + * 忽略 `quality` 參數。 + + * 忽略 `allowEdit` 參數。 + + * `Camera.MediaType`不受支援。 + + * 忽略 `correctOrientation` 參數。 + + * 忽略 `cameraDirection` 參數。 + +#### 火狐瀏覽器作業系統的怪癖 + + * 忽略 `quality` 參數。 + + * `Camera.DestinationType`將被忽略並且等於 `1` (影像檔的 URI) + + * 忽略 `allowEdit` 參數。 + + * 忽略 `PictureSourceType` 參數 (使用者選擇它在對話方塊視窗中) + + * 忽略`encodingType` + + * 忽略了 `targetWidth` 和`targetHeight` + + * `Camera.MediaType`不受支援。 + + * 忽略 `correctOrientation` 參數。 + + * 忽略 `cameraDirection` 參數。 + +#### iOS 的怪癖 + + * 設置 `quality` 低於 50,避免在某些設備上的記憶體不足錯誤。 + + * 當使用 `destinationType.FILE_URI` ,照片都保存在應用程式的臨時目錄。應用程式結束時,將刪除該應用程式的臨時目錄中的內容。 + +#### Tizen 怪癖 + + * 不支援的選項 + + * 總是返回一個檔的 URI + +#### Windows Phone 7 和 8 怪癖 + + * 忽略 `allowEdit` 參數。 + + * 忽略 `correctOrientation` 參數。 + + * 忽略 `cameraDirection` 參數。 + + * 忽略 `saveToPhotoAlbum` 參數。 重要: 使用 wp7/8 科爾多瓦攝像頭 API 拍攝的所有圖像總是都複製到手機的相機膠捲。 根據使用者的設置,這可能也意味著圖像是自動上傳到他們另。 這有可能意味著的圖像,可以比你的應用程式的目的更多的觀眾。 如果此阻滯劑您的應用程式,您將需要實現 CameraCaptureTask 在 msdn 上記載: [HTTP://msdn.microsoft.com/en-us/library/windowsphone/develop/hh394006.aspx](http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh394006.aspx)你可能還評論或在[問題追蹤器](https://issues.apache.org/jira/browse/CB-2083)的向上投票的相關的問題 + + * 忽略了 `mediaType` 屬性的 `cameraOptions` 作為 Windows Phone SDK 並不提供從 PHOTOLIBRARY 中選擇視頻的方法。 + +## CameraError + +onError 的回呼函數提供了一條錯誤訊息。 + + function(message) { + // Show a helpful message + } + + +#### 說明 + + * **message**: 消息提供的設備的本機代碼。*(String)* + +## cameraSuccess + +提供的圖像資料的 onSuccess 回呼函數。 + + function(imageData) { + // Do something with the image + } + + +#### 說明 + + * **imageData**: Base64 編碼進行編碼的圖像資料,*或*影像檔的 URI,取決於 `cameraOptions` 效果。*(String)* + +#### 示例 + + // Show image + // + function cameraCallback(imageData) { + var image = document.getElementById('myImage'); + image.src = "data:image/jpeg;base64," + imageData; + } + + +## CameraPopoverHandle + +由 `navigator.camera.getPicture` 創建的氣泡框對話方塊的控制碼. + +#### 說明 + + * **setPosition**: Set the position of the popover. Takes the `CameraPopoverOptions` that specify the new position. + +#### 支援的平臺 + +![](doc/img/android-fail.png) ![](doc/img/blackberry-fail.png) ![](doc/img/browser-fail.png) ![](doc/img/firefox-fail.png) ![](doc/img/fireos-fail.png) ![](doc/img/ios-success.png) ![](doc/img/windows-fail.png) ![](doc/img/wp8-fail.png) ![](doc/img/ubuntu-fail.png) + +#### 示例 + + var cameraPopoverHandle = navigator.camera.getPicture(onSuccess, onFail, + { destinationType: Camera.DestinationType.FILE_URI, + sourceType: Camera.PictureSourceType.PHOTOLIBRARY, + popoverOptions: new CameraPopoverOptions(300, 300, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY) + }); + + // Reposition the popover if the orientation changes. + window.onorientationchange = function() { + var cameraPopoverOptions = new CameraPopoverOptions(0, 0, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY); + cameraPopoverHandle.setPosition(cameraPopoverOptions); + } + + +## CameraPopoverOptions + +iOS 僅指定氣泡框的錨元素的位置和箭頭方向,從 iPad 庫或專輯選擇圖像時的參數。 + + { x : 0, + y : 32, + width : 320, + height : 480, + arrowDir : Camera.PopoverArrowDirection.ARROW_ANY + }; + + +#### 說明 + + * **x**: x 螢幕元素到其錨定氣泡框上的圖元座標。*(人數)* + + * **y**: 螢幕元素到其錨定氣泡框上的 y 圖元座標。*(人數)* + + * **width**: 寬度以圖元為單位),到其錨定氣泡框上的螢幕元素。*(人數)* + + * **height**: 高度以圖元為單位),到其錨定氣泡框上的螢幕元素。*(人數)* + + * **arrowDir**: 氣泡框上的箭頭應指向的方向。定義在 `Camera.PopoverArrowDirection` *(人數)* + + Camera.PopoverArrowDirection = { + ARROW_UP : 1, // matches iOS UIPopoverArrowDirection constants + ARROW_DOWN : 2, + ARROW_LEFT : 4, + ARROW_RIGHT : 8, + ARROW_ANY : 15 + }; + + +請注意氣泡框的大小可能會更改箭頭的方向和螢幕的方向進行調整。 請確保帳戶方向更改時指定錨元素位置。 + +## navigator.camera.cleanup + +刪除中間從臨時存儲攝像機所拍攝的照片。 + + navigator.camera.cleanup( cameraSuccess, cameraError ); + + +#### 說明 + +刪除保留在臨時存儲在調用 `camera.getPicture` 後的中間的影像檔。 適用只有當 `Camera.sourceType` 的值等於 `Camera.PictureSourceType.CAMERA` 和 `Camera.destinationType` 等於 `Camera.DestinationType.FILE_URI`. + +#### 支援的平臺 + +![](doc/img/android-fail.png) ![](doc/img/blackberry-fail.png) ![](doc/img/browser-fail.png) ![](doc/img/firefox-fail.png) ![](doc/img/fireos-fail.png) ![](doc/img/ios-success.png) ![](doc/img/windows-fail.png) ![](doc/img/wp8-fail.png) ![](doc/img/ubuntu-fail.png) + +#### 示例 + + navigator.camera.cleanup(onSuccess, onFail); + + function onSuccess() { + console.log("Camera cleanup success.") + } + + function onFail(message) { + alert('Failed because: ' + message); + } \ No newline at end of file diff --git a/plugins/cordova-plugin-camera/doc/zh/index.md b/plugins/cordova-plugin-camera/doc/zh/index.md new file mode 100644 index 0000000..ab719ab --- /dev/null +++ b/plugins/cordova-plugin-camera/doc/zh/index.md @@ -0,0 +1,435 @@ + + +# cordova-plugin-camera + +這個外掛程式定義了一個全球 `navigator.camera` 物件,它提供了 API,拍照,從系統的圖像庫中選擇圖像。 + +雖然該物件附加到全球範圍內 `導航器`,它不可用直到 `deviceready` 事件之後。 + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(navigator.camera); + } + + +## 安裝 + + cordova plugin add cordova-plugin-camera + + +## navigator.camera.getPicture + +需要一張照片,使用相機,或從設備的圖像庫檢索一張照片。 圖像被傳遞給成功回檔的 base64 編碼 `String`,或作為 URI 為影像檔。 該方法本身返回一個 `CameraPopoverHandle` 物件,它可以用來重新置放檔選擇氣泡框。 + + navigator.camera.getPicture( cameraSuccess, cameraError, cameraOptions ); + + +### 說明 + +`camera.getPicture` 函數打開該設備的預設攝像頭應用程式,允許使用者拍照。 `Camera.sourceType` 等於 `Camera.PictureSourceType.CAMERA` 時,預設情況下,發生此行為。 一旦使用者打斷了他的照片,相機應用程式關閉,且應用程式還原。 + +如果 `Camera.sourceType` 是 `Camera.PictureSourceType.PHOTOLIBRARY` 或 `Camera.PictureSourceType.SAVEDPHOTOALBUM`,然後顯示一個對話方塊,允許使用者選擇一個現有的圖像。 `camera.getPicture` 函數返回一個 `CameraPopoverHandle` 物件,它可以用於重新置放圖像選擇的對話方塊,例如,當設備的方向變化。 + +傳回值是發送到 `cameraSuccess` 回呼函數中,在以下的格式,具體取決於指定的 `cameraOptions` 之一: + +* A `String` 包含的 base64 編碼的照片圖像。 + +* A `String` 表示在本機存放區 (預設值) 上的影像檔位置。 + +你可以做任何你想要的編碼的圖像或 URI,例如: + +* 呈現在圖像 `` 標記,如下面的示例所示 + +* 保存本地的資料 ( `LocalStorage` , [Lawnchair][1],等等.) + +* 將資料發佈到遠端伺服器 + + [1]: http://brianleroux.github.com/lawnchair/ + +**注**: 在更新設備上的照片解析度是很好。 選擇從設備的庫的照片是不壓縮螢幕使其以較低的品質,即使指定了一個 `quality` 參數。 要避免常見的記憶體問題,請將 `Camera.destinationType` 設置為 `FILE_URI`,而不是 `DATA_URL`. + +### 支援的平臺 + +* 亞馬遜火 OS +* Android 系統 +* 黑莓 10 +* 瀏覽器 +* 火狐瀏覽器的作業系統 +* iOS +* 泰 +* Windows Phone 7 和 8 +* Windows 8 + +### 首選項 (iOS) + +* **CameraUsesGeolocation**(布林值,預設值為 false)。 用於捕獲 jpeg 檔,設置為 true,以在 EXIF 頭資訊中獲取地理定位資料。 這將觸發請求的地理位置的許可權,如果設置為 true。 + + + + +### 亞馬遜火 OS 怪癖 + +亞馬遜火 OS 使用意圖啟動相機活動設備來捕捉圖像上, 和手機上記憶體不足,科爾多瓦活動可能被殺害。 在這種情況下,可能不會顯示圖像時恢復了科爾多瓦活動。 + +### Android 的怪癖 + +Android 使用意圖以啟動相機活動設備來捕捉圖像上, 和手機上記憶體不足,科爾多瓦活動可能被殺害。 在這種情況下,可能不會顯示圖像時恢復了科爾多瓦活動。 + +### 瀏覽器的怪癖 + +可以只返回照片作為 base64 編碼的圖像。 + +### 火狐瀏覽器作業系統的怪癖 + +觀景窗外掛程式目前實施使用 [Web 活動][2]. + + [2]: https://hacks.mozilla.org/2013/01/introducing-web-activities/ + +### iOS 的怪癖 + +包括 JavaScript `alert ()` 中的回呼函數會導致問題。 包裝內 `setTimeout()` 允許 iOS 圖像選取器或氣泡框以完全關閉之前,警報將顯示警報: + + setTimeout(function() { + // do your thing here! + }, 0); + + +### Windows Phone 7 的怪癖 + +調用本機攝像頭應用程式,而通過 Zune 所連接的設備不能工作,並且觸發錯誤回檔。 + +### 泰怪癖 + +泰只支援 `destinationType` 的 `Camera.DestinationType.FILE_URI` 和 `Camera.PictureSourceType.PHOTOLIBRARY` 的 `sourceType`. + +### 示例 + +拍一張照片,並檢索它作為一個 base64 編碼的圖像: + + navigator.camera.getPicture(onSuccess, onFail, { quality: 50, + destinationType: Camera.DestinationType.DATA_URL + }); + + function onSuccess(imageData) { + var image = document.getElementById('myImage'); + image.src = "data:image/jpeg;base64," + imageData; + } + + function onFail(message) { + alert('Failed because: ' + message); + } + + +拍一張照片和檢索圖像的檔位置: + + navigator.camera.getPicture(onSuccess, onFail, { quality: 50, + destinationType: Camera.DestinationType.FILE_URI }); + + function onSuccess(imageURI) { + var image = document.getElementById('myImage'); + image.src = imageURI; + } + + function onFail(message) { + alert('Failed because: ' + message); + } + + +## CameraOptions + +要自訂相機設置的可選參數。 + + { quality : 75, + destinationType : Camera.DestinationType.DATA_URL, + sourceType : Camera.PictureSourceType.CAMERA, + allowEdit : true, + encodingType: Camera.EncodingType.JPEG, + targetWidth: 100, + targetHeight: 100, + popoverOptions: CameraPopoverOptions, + saveToPhotoAlbum: false }; + + +### 選項 + +* **品質**: 保存的圖像,表示為範圍 0-100,100,是通常全解析度,無損失從檔案壓縮的品質。 預設值為 50。 *(人數)*(請注意相機的解析度有關的資訊是不可用)。 + +* **可**: 選擇傳回值的格式。預設值是 FILE_URI。定義在 `navigator.camera.DestinationType` *(人數)* + + Camera.DestinationType = { + DATA_URL : 0, // Return image as base64-encoded string + FILE_URI : 1, // Return image file URI + NATIVE_URI : 2 // Return image native URI (e.g., assets-library:// on iOS or content:// on Android) + }; + + +* **時**: 設置圖片的來源。預設值是觀景窗。定義在 `navigator.camera.PictureSourceType` *(人數)* + + Camera.PictureSourceType = { + PHOTOLIBRARY : 0, + CAMERA : 1, + SAVEDPHOTOALBUM : 2 + }; + + +* **allowEdit**: 允許簡單編輯前選擇圖像。*(布林)* + +* **encodingType**: 選擇返回的影像檔的編碼。預設值為 JPEG。定義在 `navigator.camera.EncodingType` *(人數)* + + Camera.EncodingType = { + JPEG : 0, // Return JPEG encoded image + PNG : 1 // Return PNG encoded image + }; + + +* **targetWidth**: 向尺度圖像的圖元寬度。必須用**targetHeight**。縱橫比保持不變。*(人數)* + +* **targetHeight**: 以圖元為單位向尺度圖像的高度。必須用**targetWidth**。縱橫比保持不變。*(人數)* + +* **媒體類型**: 設置的媒體,從選擇類型。 時才起作用 `PictureSourceType` 是 `PHOTOLIBRARY` 或 `SAVEDPHOTOALBUM` 。 定義在 `nagivator.camera.MediaType` *(人數)* + + Camera.MediaType = { + PICTURE: 0, // allow selection of still pictures only. 預設情況。 Will return format specified via DestinationType + VIDEO: 1, // allow selection of video only, WILL ALWAYS RETURN FILE_URI + ALLMEDIA : 2 // allow selection from all media types + }; + + +* **correctOrientation**: 旋轉圖像,該設備時捕獲的定向的正確。*(布林)* + +* **saveToPhotoAlbum**: 將圖像保存到相冊在設備上捕獲後。*(布林)* + +* **popoverOptions**: 只有 iOS 在 iPad 中指定氣泡框位置的選項。在中定義`CameraPopoverOptions`. + +* **cameraDirection**: 選擇相機以使用 (前面或後面-面向)。預設值是背。定義在 `navigator.camera.Direction` *(人數)* + + Camera.Direction = { + BACK : 0, // Use the back-facing camera + FRONT : 1 // Use the front-facing camera + }; + + +### 亞馬遜火 OS 怪癖 + +* 任何 `cameraDirection` 值回朝的照片中的結果。 + +* 忽略 `allowEdit` 參數。 + +* `Camera.PictureSourceType.PHOTOLIBRARY`和 `Camera.PictureSourceType.SAVEDPHOTOALBUM` 都顯示相同的相冊。 + +### Android 的怪癖 + +* 任何 `cameraDirection` 值結果在背面的照片。 + +* 忽略 `allowEdit` 參數。 + +* `Camera.PictureSourceType.PHOTOLIBRARY`和 `Camera.PictureSourceType.SAVEDPHOTOALBUM` 都顯示相同的寫真集。 + +### 黑莓 10 的怪癖 + +* 忽略 `quality` 參數。 + +* 忽略 `allowEdit` 參數。 + +* `Camera.MediaType`不受支援。 + +* 忽略 `correctOrientation` 參數。 + +* 忽略 `cameraDirection` 參數。 + +### 火狐瀏覽器作業系統的怪癖 + +* 忽略 `quality` 參數。 + +* `Camera.DestinationType`將被忽略並且等於 `1` (影像檔的 URI) + +* 忽略 `allowEdit` 參數。 + +* 忽略 `PictureSourceType` 參數 (使用者選擇它在對話方塊視窗中) + +* 忽略`encodingType` + +* 忽略了 `targetWidth` 和`targetHeight` + +* `Camera.MediaType`不受支援。 + +* 忽略 `correctOrientation` 參數。 + +* 忽略 `cameraDirection` 參數。 + +### iOS 的怪癖 + +* 設置 `quality` 低於 50,避免在某些設備上的記憶體不足錯誤。 + +* 當使用 `destinationType.FILE_URI` ,照片都保存在應用程式的臨時目錄。應用程式結束時,將刪除該應用程式的臨時目錄中的內容。 + +### 泰怪癖 + +* 不支援的選項 + +* 總是返回一個檔的 URI + +### Windows Phone 7 和 8 的怪癖 + +* 忽略 `allowEdit` 參數。 + +* 忽略 `correctOrientation` 參數。 + +* 忽略 `cameraDirection` 參數。 + +* 忽略 `saveToPhotoAlbum` 參數。 重要: 使用 wp7/8 科爾多瓦攝像頭 API 拍攝的所有圖像總是都複製到手機的相機膠捲。 根據使用者的設置,這可能也意味著圖像是自動上傳到他們另。 這有可能意味著的圖像,可以比你的應用程式的目的更多的觀眾。 如果此阻滯劑您的應用程式,您將需要實現 CameraCaptureTask 在 msdn 上記載: [HTTP://msdn.microsoft.com/en-us/library/windowsphone/develop/hh394006.aspx][3]你可能還評論或在[問題追蹤器][4]的向上投票的相關的問題 + +* 忽略了 `mediaType` 屬性的 `cameraOptions` 作為 Windows Phone SDK 並不提供從 PHOTOLIBRARY 中選擇視頻的方法。 + + [3]: http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh394006.aspx + [4]: https://issues.apache.org/jira/browse/CB-2083 + +## CameraError + +onError 的回呼函數提供了一條錯誤訊息。 + + function(message) { + // Show a helpful message + } + + +### 參數 + +* **message**: 消息提供的設備的本機代碼。*(String)* + +## cameraSuccess + +提供的圖像資料的 onSuccess 回呼函數。 + + function(imageData) { + // Do something with the image + } + + +### 參數 + +* **imageData**: Base64 編碼進行編碼的圖像資料,*或*影像檔的 URI,取決於 `cameraOptions` 效果。*(String)* + +### 示例 + + // Show image + // + function cameraCallback(imageData) { + var image = document.getElementById('myImage'); + image.src = "data:image/jpeg;base64," + imageData; + } + + +## CameraPopoverHandle + +由 `navigator.camera.getPicture` 創建的氣泡框對話方塊的控制碼. + +### 方法 + +* **setPosition**: 設置氣泡框的位置。 + +### 支援的平臺 + +* iOS + +### setPosition + +設置氣泡框的位置。 + +**參數**: + +* `cameraPopoverOptions`: `CameraPopoverOptions` ,指定新的位置 + +### 示例 + + var cameraPopoverHandle = navigator.camera.getPicture(onSuccess, onFail, + { destinationType: Camera.DestinationType.FILE_URI, + sourceType: Camera.PictureSourceType.PHOTOLIBRARY, + popoverOptions: new CameraPopoverOptions(300, 300, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY) + }); + + // Reposition the popover if the orientation changes. + window.onorientationchange = function() { + var cameraPopoverOptions = new CameraPopoverOptions(0, 0, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY); + cameraPopoverHandle.setPosition(cameraPopoverOptions); + } + + +## CameraPopoverOptions + +iOS 僅指定氣泡框的錨元素的位置和箭頭方向,從 iPad 庫或專輯選擇圖像時的參數。 + + { x : 0, + y : 32, + width : 320, + height : 480, + arrowDir : Camera.PopoverArrowDirection.ARROW_ANY + }; + + +### CameraPopoverOptions + +* **x**: x 螢幕元素到其錨定氣泡框上的圖元座標。*(人數)* + +* **y**: 螢幕元素到其錨定氣泡框上的 y 圖元座標。*(人數)* + +* **width**: 寬度以圖元為單位),到其錨定氣泡框上的螢幕元素。*(人數)* + +* **height**: 高度以圖元為單位),到其錨定氣泡框上的螢幕元素。*(人數)* + +* **arrowDir**: 氣泡框上的箭頭應指向的方向。定義在 `Camera.PopoverArrowDirection` *(人數)* + + Camera.PopoverArrowDirection = { + ARROW_UP : 1, // matches iOS UIPopoverArrowDirection constants + ARROW_DOWN : 2, + ARROW_LEFT : 4, + ARROW_RIGHT : 8, + ARROW_ANY : 15 + }; + + +請注意氣泡框的大小可能會更改箭頭的方向和螢幕的方向進行調整。 請確保帳戶方向更改時指定錨元素位置。 + +## navigator.camera.cleanup + +刪除中間從臨時存儲攝像機所拍攝的照片。 + + navigator.camera.cleanup( cameraSuccess, cameraError ); + + +### 描述 + +刪除保留在臨時存儲在調用 `camera.getPicture` 後的中間的影像檔。 適用只有當 `Camera.sourceType` 的值等於 `Camera.PictureSourceType.CAMERA` 和 `Camera.destinationType` 等於 `Camera.DestinationType.FILE_URI`. + +### 支援的平臺 + +* iOS + +### 示例 + + navigator.camera.cleanup(onSuccess, onFail); + + function onSuccess() { + console.log("Camera cleanup success.") + } + + function onFail(message) { + alert('Failed because: ' + message); + } diff --git a/plugins/cordova-plugin-camera/jsdoc2md/TEMPLATE.md b/plugins/cordova-plugin-camera/jsdoc2md/TEMPLATE.md new file mode 100644 index 0000000..ba9f63a --- /dev/null +++ b/plugins/cordova-plugin-camera/jsdoc2md/TEMPLATE.md @@ -0,0 +1,443 @@ +--- +title: Camera +description: Take pictures with the device camera. +--- +{{>cdv-license~}} + +|Android|iOS| Windows 8.1 Store | Windows 8.1 Phone | Windows 10 Store | Travis CI | +|:-:|:-:|:-:|:-:|:-:|:-:| +|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=android,PLUGIN=cordova-plugin-camera)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=android,PLUGIN=cordova-plugin-camera/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=ios,PLUGIN=cordova-plugin-camera)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=ios,PLUGIN=cordova-plugin-camera/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=windows-8.1-store,PLUGIN=cordova-plugin-camera)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=windows-8.1-store,PLUGIN=cordova-plugin-camera/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=windows-8.1-phone,PLUGIN=cordova-plugin-camera)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=windows-8.1-phone,PLUGIN=cordova-plugin-camera/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=windows-10-store,PLUGIN=cordova-plugin-camera)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=windows-10-store,PLUGIN=cordova-plugin-camera/)|[![Build Status](https://travis-ci.org/apache/cordova-plugin-camera.svg?branch=master)](https://travis-ci.org/apache/cordova-plugin-camera) + +# cordova-plugin-camera + +This plugin defines a global `navigator.camera` object, which provides an API for taking pictures and for choosing images from +the system's image library. + +{{>cdv-header device-ready-warning-obj='navigator.camera' npmName='cordova-plugin-camera' cprName='org.apache.cordova.camera' pluginName='Plugin Camera' repoUrl='https://github.com/apache/cordova-plugin-camera' }} + + +### iOS Quirks + +Since iOS 10 it's mandatory to add a `NSCameraUsageDescription` and `NSPhotoLibraryUsageDescription` in the info.plist. + +- `NSCameraUsageDescription` describes the reason that the app accesses the user’s camera. +- `NSPhotoLibraryUsageDescription` describes the reason the app accesses the user's photo library. + +When the system prompts the user to allow access, this string is displayed as part of the dialog box. + +To add this entry you can pass the following variables on plugin install. + +- `CAMERA_USAGE_DESCRIPTION` for `NSCameraUsageDescription` +- `PHOTOLIBRARY_USAGE_DESCRIPTION` for `NSPhotoLibraryUsageDescription` + +Example: + + cordova plugin add cordova-plugin-camera --variable CAMERA_USAGE_DESCRIPTION="your usage message" --variable PHOTOLIBRARY_USAGE_DESCRIPTION="your usage message" + +If you don't pass the variable, the plugin will add an empty string as value. + +--- + +# API Reference + +{{#orphans~}} +{{>member-index}} +{{/orphans}} +* [CameraPopoverHandle](#module_CameraPopoverHandle) +* [CameraPopoverOptions](#module_CameraPopoverOptions) + +--- + +{{#modules~}} +{{>header~}} +{{>body~}} +{{>members~}} + +--- + +{{/modules}} + +## `camera.getPicture` Errata + +#### Example + +Take a photo and retrieve the image's file location: + + navigator.camera.getPicture(onSuccess, onFail, { quality: 50, + destinationType: Camera.DestinationType.FILE_URI }); + + function onSuccess(imageURI) { + var image = document.getElementById('myImage'); + image.src = imageURI; + } + + function onFail(message) { + alert('Failed because: ' + message); + } + +Take a photo and retrieve it as a Base64-encoded image: + + /** + * Warning: Using DATA_URL is not recommended! The DATA_URL destination + * type is very memory intensive, even with a low quality setting. Using it + * can result in out of memory errors and application crashes. Use FILE_URI + * or NATIVE_URI instead. + */ + navigator.camera.getPicture(onSuccess, onFail, { quality: 25, + destinationType: Camera.DestinationType.DATA_URL + }); + + function onSuccess(imageData) { + var image = document.getElementById('myImage'); + image.src = "data:image/jpeg;base64," + imageData; + } + + function onFail(message) { + alert('Failed because: ' + message); + } + +#### Preferences (iOS) + +- __CameraUsesGeolocation__ (boolean, defaults to false). For capturing JPEGs, set to true to get geolocation data in the EXIF header. This will trigger a request for geolocation permissions if set to true. + + + +#### Amazon Fire OS Quirks + +Amazon Fire OS uses intents to launch the camera activity on the device to capture +images, and on phones with low memory, the Cordova activity may be killed. In this +scenario, the image may not appear when the Cordova activity is restored. + +#### Android Quirks + +Android uses intents to launch the camera activity on the device to capture +images, and on phones with low memory, the Cordova activity may be killed. In this +scenario, the result from the plugin call will be delivered via the resume event. +See [the Android Lifecycle guide][android_lifecycle] +for more information. The `pendingResult.result` value will contain the value that +would be passed to the callbacks (either the URI/URL or an error message). Check +the `pendingResult.pluginStatus` to determine whether or not the call was +successful. + +#### Browser Quirks + +Can only return photos as Base64-encoded image. + +#### Firefox OS Quirks + +Camera plugin is currently implemented using [Web Activities][web_activities]. + +#### iOS Quirks + +Including a JavaScript `alert()` in either of the callback functions +can cause problems. Wrap the alert within a `setTimeout()` to allow +the iOS image picker or popover to fully close before the alert +displays: + + setTimeout(function() { + // do your thing here! + }, 0); + +#### Windows Phone 7 Quirks + +Invoking the native camera application while the device is connected +via Zune does not work, and triggers an error callback. + +#### Windows quirks + +On Windows Phone 8.1 using `SAVEDPHOTOALBUM` or `PHOTOLIBRARY` as a source type causes application to suspend until file picker returns the selected image and +then restore with start page as defined in app's `config.xml`. In case when `camera.getPicture` was called from different page, this will lead to reloading +start page from scratch and success and error callbacks will never be called. + +To avoid this we suggest using SPA pattern or call `camera.getPicture` only from your app's start page. + +More information about Windows Phone 8.1 picker APIs is here: [How to continue your Windows Phone app after calling a file picker](https://msdn.microsoft.com/en-us/library/windows/apps/dn720490.aspx) + +#### Tizen Quirks + +Tizen only supports a `destinationType` of +`Camera.DestinationType.FILE_URI` and a `sourceType` of +`Camera.PictureSourceType.PHOTOLIBRARY`. + + +## `CameraOptions` Errata + +#### Amazon Fire OS Quirks + +- Any `cameraDirection` value results in a back-facing photo. + +- Ignores the `allowEdit` parameter. + +- `Camera.PictureSourceType.PHOTOLIBRARY` and `Camera.PictureSourceType.SAVEDPHOTOALBUM` both display the same photo album. + +#### Android Quirks + +- Any `cameraDirection` value results in a back-facing photo. + +- **`allowEdit` is unpredictable on Android and it should not be used!** The Android implementation of this plugin tries to find and use an application on the user's device to do image cropping. The plugin has no control over what application the user selects to perform the image cropping and it is very possible that the user could choose an incompatible option and cause the plugin to fail. This sometimes works because most devices come with an application that handles cropping in a way that is compatible with this plugin (Google Plus Photos), but it is unwise to rely on that being the case. If image editing is essential to your application, consider seeking a third party library or plugin that provides its own image editing utility for a more robust solution. + +- `Camera.PictureSourceType.PHOTOLIBRARY` and `Camera.PictureSourceType.SAVEDPHOTOALBUM` both display the same photo album. + +- Ignores the `encodingType` parameter if the image is unedited (i.e. `quality` is 100, `correctOrientation` is false, and no `targetHeight` or `targetWidth` are specified). The `CAMERA` source will always return the JPEG file given by the native camera and the `PHOTOLIBRARY` and `SAVEDPHOTOALBUM` sources will return the selected file in its existing encoding. + +#### BlackBerry 10 Quirks + +- Ignores the `quality` parameter. + +- Ignores the `allowEdit` parameter. + +- `Camera.MediaType` is not supported. + +- Ignores the `correctOrientation` parameter. + +- Ignores the `cameraDirection` parameter. + +#### Firefox OS Quirks + +- Ignores the `quality` parameter. + +- `Camera.DestinationType` is ignored and equals `1` (image file URI) + +- Ignores the `allowEdit` parameter. + +- Ignores the `PictureSourceType` parameter (user chooses it in a dialog window) + +- Ignores the `encodingType` + +- Ignores the `targetWidth` and `targetHeight` + +- `Camera.MediaType` is not supported. + +- Ignores the `correctOrientation` parameter. + +- Ignores the `cameraDirection` parameter. + +#### iOS Quirks + +- When using `destinationType.FILE_URI`, photos are saved in the application's temporary directory. The contents of the application's temporary directory is deleted when the application ends. + +- When using `destinationType.NATIVE_URI` and `sourceType.CAMERA`, photos are saved in the saved photo album regardless on the value of `saveToPhotoAlbum` parameter. + +- When using `destinationType.NATIVE_URI` and `sourceType.PHOTOLIBRARY` or `sourceType.SAVEDPHOTOALBUM`, all editing options are ignored and link is returned to original picture. + +#### Tizen Quirks + +- options not supported + +- always returns a FILE URI + +#### Windows Phone 7 and 8 Quirks + +- Ignores the `allowEdit` parameter. + +- Ignores the `correctOrientation` parameter. + +- Ignores the `cameraDirection` parameter. + +- Ignores the `saveToPhotoAlbum` parameter. IMPORTANT: All images taken with the WP8/8 Cordova camera API are always copied to the phone's camera roll. Depending on the user's settings, this could also mean the image is auto-uploaded to their OneDrive. This could potentially mean the image is available to a wider audience than your app intended. If this is a blocker for your application, you will need to implement the CameraCaptureTask as [documented on MSDN][msdn_wp8_docs]. You may also comment or up-vote the related issue in the [issue tracker][wp8_bug]. + +- Ignores the `mediaType` property of `cameraOptions` as the Windows Phone SDK does not provide a way to choose videos from PHOTOLIBRARY. + +[android_lifecycle]: http://cordova.apache.org/docs/en/dev/guide/platforms/android/lifecycle.html +[web_activities]: https://hacks.mozilla.org/2013/01/introducing-web-activities/ +[wp8_bug]: https://issues.apache.org/jira/browse/CB-2083 +[msdn_wp8_docs]: http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh394006.aspx + +## Sample: Take Pictures, Select Pictures from the Picture Library, and Get Thumbnails + +The Camera plugin allows you to do things like open the device's Camera app and take a picture, or open the file picker and select one. The code snippets in this section demonstrate different tasks including: + +* Open the Camera app and [take a Picture](#takePicture) +* Take a picture and [return thumbnails](#getThumbnails) (resized picture) +* Take a picture and [generate a FileEntry object](#convert) +* [Select a file](#selectFile) from the picture library +* Select a JPEG image and [return thumbnails](#getFileThumbnails) (resized image) +* Select an image and [generate a FileEntry object](#convert) + +## Take a Picture + +Before you can take a picture, you need to set some Camera plugin options to pass into the Camera plugin's `getPicture` function. Here is a common set of recommendations. In this example, you create the object that you will use for the Camera options, and set the `sourceType` dynamically to support both the Camera app and the file picker. + +```js +function setOptions(srcType) { + var options = { + // Some common settings are 20, 50, and 100 + quality: 50, + destinationType: Camera.DestinationType.FILE_URI, + // In this app, dynamically set the picture source, Camera or photo gallery + sourceType: srcType, + encodingType: Camera.EncodingType.JPEG, + mediaType: Camera.MediaType.PICTURE, + allowEdit: true, + correctOrientation: true //Corrects Android orientation quirks + } + return options; +} +``` + +Typically, you want to use a FILE_URI instead of a DATA_URL to avoid most memory issues. JPEG is the recommended encoding type for Android. + +You take a picture by passing in the options object to `getPicture`, which takes a CameraOptions object as the third argument. When you call `setOptions`, pass `Camera.PictureSourceType.CAMERA` as the picture source. + +```js +function openCamera(selection) { + + var srcType = Camera.PictureSourceType.CAMERA; + var options = setOptions(srcType); + var func = createNewFileEntry; + + navigator.camera.getPicture(function cameraSuccess(imageUri) { + + displayImage(imageUri); + // You may choose to copy the picture, save it somewhere, or upload. + func(imageUri); + + }, function cameraError(error) { + console.debug("Unable to obtain picture: " + error, "app"); + + }, options); +} +``` + +Once you take the picture, you can display it or do something else. In this example, call the app's `displayImage` function from the preceding code. + +```js +function displayImage(imgUri) { + + var elem = document.getElementById('imageFile'); + elem.src = imgUri; +} +``` + +To display the image on some platforms, you might need to include the main part of the URI in the Content-Security-Policy `` element in index.html. For example, on Windows 10, you can include `ms-appdata:` in your `` element. Here is an example. + +```html + +``` + +## Take a Picture and Return Thumbnails (Resize the Picture) + +To get smaller images, you can return a resized image by passing both `targetHeight` and `targetWidth` values with your CameraOptions object. In this example, you resize the returned image to fit in a 100px by 100px box (the aspect ratio is maintained, so 100px is either the height or width, whichever is greater in the source). + +```js +function openCamera(selection) { + + var srcType = Camera.PictureSourceType.CAMERA; + var options = setOptions(srcType); + var func = createNewFileEntry; + + if (selection == "camera-thmb") { + options.targetHeight = 100; + options.targetWidth = 100; + } + + navigator.camera.getPicture(function cameraSuccess(imageUri) { + + // Do something + + }, function cameraError(error) { + console.debug("Unable to obtain picture: " + error, "app"); + + }, options); +} +``` + +## Select a File from the Picture Library + +When selecting a file using the file picker, you also need to set the CameraOptions object. In this example, set the `sourceType` to `Camera.PictureSourceType.SAVEDPHOTOALBUM`. To open the file picker, call `getPicture` just as you did in the previous example, passing in the success and error callbacks along with CameraOptions object. + +```js +function openFilePicker(selection) { + + var srcType = Camera.PictureSourceType.SAVEDPHOTOALBUM; + var options = setOptions(srcType); + var func = createNewFileEntry; + + navigator.camera.getPicture(function cameraSuccess(imageUri) { + + // Do something + + }, function cameraError(error) { + console.debug("Unable to obtain picture: " + error, "app"); + + }, options); +} +``` + +## Select an Image and Return Thumbnails (resized images) + +Resizing a file selected with the file picker works just like resizing using the Camera app; set the `targetHeight` and `targetWidth` options. + +```js +function openFilePicker(selection) { + + var srcType = Camera.PictureSourceType.SAVEDPHOTOALBUM; + var options = setOptions(srcType); + var func = createNewFileEntry; + + if (selection == "picker-thmb") { + // To downscale a selected image, + // Camera.EncodingType (e.g., JPEG) must match the selected image type. + options.targetHeight = 100; + options.targetWidth = 100; + } + + navigator.camera.getPicture(function cameraSuccess(imageUri) { + + // Do something with image + + }, function cameraError(error) { + console.debug("Unable to obtain picture: " + error, "app"); + + }, options); +} +``` + +## Take a picture and get a FileEntry Object + +If you want to do something like copy the image to another location, or upload it somewhere using the FileTransfer plugin, you need to get a FileEntry object for the returned picture. To do that, call `window.resolveLocalFileSystemURL` on the file URI returned by the Camera app. If you need to use a FileEntry object, set the `destinationType` to `Camera.DestinationType.FILE_URI` in your CameraOptions object (this is also the default value). + +>*Note* You need the [File plugin](https://www.npmjs.com/package/cordova-plugin-file) to call `window.resolveLocalFileSystemURL`. + +Here is the call to `window.resolveLocalFileSystemURL`. The image URI is passed to this function from the success callback of `getPicture`. The success handler of `resolveLocalFileSystemURL` receives the FileEntry object. + +```js +function getFileEntry(imgUri) { + window.resolveLocalFileSystemURL(imgUri, function success(fileEntry) { + + // Do something with the FileEntry object, like write to it, upload it, etc. + // writeFile(fileEntry, imgUri); + console.log("got file: " + fileEntry.fullPath); + // displayFileData(fileEntry.nativeURL, "Native URL"); + + }, function () { + // If don't get the FileEntry (which may happen when testing + // on some emulators), copy to a new FileEntry. + createNewFileEntry(imgUri); + }); +} +``` + +In the example shown in the preceding code, you call the app's `createNewFileEntry` function if you don't get a valid FileEntry object. The image URI returned from the Camera app should result in a valid FileEntry, but platform behavior on some emulators may be different for files returned from the file picker. + +>*Note* To see an example of writing to a FileEntry, see the [File plugin README](https://www.npmjs.com/package/cordova-plugin-file). + +The code shown here creates a file in your app's cache (in sandboxed storage) named `tempFile.jpeg`. With the new FileEntry object, you can copy the image to the file or do something else like upload it. + +```js +function createNewFileEntry(imgUri) { + window.resolveLocalFileSystemURL(cordova.file.cacheDirectory, function success(dirEntry) { + + // JPEG file + dirEntry.getFile("tempFile.jpeg", { create: true, exclusive: false }, function (fileEntry) { + + // Do something with it, like write to it, upload it, etc. + // writeFile(fileEntry, imgUri); + console.log("got file: " + fileEntry.fullPath); + // displayFileData(fileEntry.fullPath, "File copied to"); + + }, onErrorCreateFile); + + }, onErrorResolveUrl); +} +``` diff --git a/plugins/cordova-plugin-camera/package.json b/plugins/cordova-plugin-camera/package.json new file mode 100644 index 0000000..18e18ed --- /dev/null +++ b/plugins/cordova-plugin-camera/package.json @@ -0,0 +1,63 @@ +{ + "name": "cordova-plugin-camera", + "version": "2.4.1", + "description": "Cordova Camera Plugin", + "types": "./types/index.d.ts", + "cordova": { + "id": "cordova-plugin-camera", + "platforms": [ + "firefoxos", + "android", + "amazon-fireos", + "ubuntu", + "ios", + "blackberry10", + "wp7", + "wp8", + "windows8", + "browser", + "windows" + ] + }, + "repository": { + "type": "git", + "url": "https://github.com/apache/cordova-plugin-camera" + }, + "keywords": [ + "cordova", + "camera", + "ecosystem:cordova", + "cordova-firefoxos", + "cordova-android", + "cordova-amazon-fireos", + "cordova-ubuntu", + "cordova-ios", + "cordova-blackberry10", + "cordova-wp7", + "cordova-wp8", + "cordova-windows8", + "cordova-browser", + "cordova-windows" + ], + "scripts": { + "precommit": "npm run gen-docs && git add README.md", + "gen-docs": "jsdoc2md --template \"jsdoc2md/TEMPLATE.md\" \"www/**/*.js\" --plugin \"dmd-plugin-cordova-plugin\" > README.md", + "test": "npm run jshint", + "jshint": "node node_modules/jshint/bin/jshint www && node node_modules/jshint/bin/jshint src && node node_modules/jshint/bin/jshint tests" + }, + "author": "Apache Software Foundation", + "license": "Apache-2.0", + "engines": { + "cordovaDependencies": { + "3.0.0": { + "cordova": ">100" + } + } + }, + "devDependencies": { + "dmd-plugin-cordova-plugin": "^0.1.0", + "husky": "^0.10.1", + "jsdoc-to-markdown": "^1.2.0", + "jshint": "^2.6.0" + } +} diff --git a/plugins/cordova-plugin-camera/plugin.xml b/plugins/cordova-plugin-camera/plugin.xml new file mode 100644 index 0000000..b931110 --- /dev/null +++ b/plugins/cordova-plugin-camera/plugin.xml @@ -0,0 +1,285 @@ + + + + + Camera + Cordova Camera Plugin + Apache 2.0 + cordova,camera + https://git-wip-us.apache.org/repos/asf/cordova-plugin-camera.git + https://issues.apache.org/jira/browse/CB/component/12320645 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + $CAMERA_USAGE_DESCRIPTION + + + + + $PHOTOLIBRARY_USAGE_DESCRIPTION + + + + + + + + + + + + + + + + access_shared + use_camera + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/cordova-plugin-camera/src/android/CameraLauncher.java b/plugins/cordova-plugin-camera/src/android/CameraLauncher.java new file mode 100644 index 0000000..b10f40f --- /dev/null +++ b/plugins/cordova-plugin-camera/src/android/CameraLauncher.java @@ -0,0 +1,1399 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. +*/ +package org.apache.cordova.camera; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.text.SimpleDateFormat; +import java.util.Date; + +import org.apache.cordova.BuildHelper; +import org.apache.cordova.CallbackContext; +import org.apache.cordova.CordovaPlugin; +import org.apache.cordova.CordovaResourceApi; +import org.apache.cordova.LOG; +import org.apache.cordova.PermissionHelper; +import org.apache.cordova.PluginResult; +import org.json.JSONArray; +import org.json.JSONException; + +import android.Manifest; +import android.annotation.TargetApi; +import android.app.Activity; +import android.content.ActivityNotFoundException; +import android.content.ContentValues; +import android.content.Context; +import android.content.Intent; +import android.database.Cursor; +import android.graphics.Bitmap; +import android.graphics.Bitmap.CompressFormat; +import android.graphics.BitmapFactory; +import android.graphics.Matrix; +import android.media.ExifInterface; +import android.media.MediaScannerConnection; +import android.media.MediaScannerConnection.MediaScannerConnectionClient; +import android.net.Uri; +import android.os.Build; +import android.os.Bundle; +import android.os.Environment; +import android.provider.DocumentsContract; +import android.provider.MediaStore; +import android.provider.OpenableColumns; +import android.support.v4.content.FileProvider; +import android.util.Base64; +import android.content.pm.PackageManager; +import android.content.pm.PackageManager.NameNotFoundException; + +/** + * This class launches the camera view, allows the user to take a picture, closes the camera view, + * and returns the captured image. When the camera view is closed, the screen displayed before + * the camera view was shown is redisplayed. + */ +public class CameraLauncher extends CordovaPlugin implements MediaScannerConnectionClient { + + private static final int DATA_URL = 0; // Return base64 encoded string + private static final int FILE_URI = 1; // Return file uri (content://media/external/images/media/2 for Android) + private static final int NATIVE_URI = 2; // On Android, this is the same as FILE_URI + + private static final int PHOTOLIBRARY = 0; // Choose image from picture library (same as SAVEDPHOTOALBUM for Android) + private static final int CAMERA = 1; // Take picture from camera + private static final int SAVEDPHOTOALBUM = 2; // Choose image from picture library (same as PHOTOLIBRARY for Android) + + private static final int PICTURE = 0; // allow selection of still pictures only. DEFAULT. Will return format specified via DestinationType + private static final int VIDEO = 1; // allow selection of video only, ONLY RETURNS URL + private static final int ALLMEDIA = 2; // allow selection from all media types + + private static final int JPEG = 0; // Take a picture of type JPEG + private static final int PNG = 1; // Take a picture of type PNG + private static final String GET_PICTURE = "Get Picture"; + private static final String GET_VIDEO = "Get Video"; + private static final String GET_All = "Get All"; + + public static final int PERMISSION_DENIED_ERROR = 20; + public static final int TAKE_PIC_SEC = 0; + public static final int SAVE_TO_ALBUM_SEC = 1; + + private static final String LOG_TAG = "CameraLauncher"; + + //Where did this come from? + private static final int CROP_CAMERA = 100; + + private int mQuality; // Compression quality hint (0-100: 0=low quality & high compression, 100=compress of max quality) + private int targetWidth; // desired width of the image + private int targetHeight; // desired height of the image + private CordovaUri imageUri; // Uri of captured image + private int encodingType; // Type of encoding to use + private int mediaType; // What type of media to retrieve + private int destType; // Source type (needs to be saved for the permission handling) + private int srcType; // Destination type (needs to be saved for permission handling) + private boolean saveToPhotoAlbum; // Should the picture be saved to the device's photo album + private boolean correctOrientation; // Should the pictures orientation be corrected + private boolean orientationCorrected; // Has the picture's orientation been corrected + private boolean allowEdit; // Should we allow the user to crop the image. + + protected final static String[] permissions = { Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE }; + + public CallbackContext callbackContext; + private int numPics; + + private MediaScannerConnection conn; // Used to update gallery app with newly-written files + private Uri scanMe; // Uri of image to be added to content store + private Uri croppedUri; + private ExifHelper exifData; // Exif data from source + private String applicationId; + + + /** + * Executes the request and returns PluginResult. + * + * @param action The action to execute. + * @param args JSONArry of arguments for the plugin. + * @param callbackContext The callback id used when calling back into JavaScript. + * @return A PluginResult object with a status and message. + */ + public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { + this.callbackContext = callbackContext; + //Adding an API to CoreAndroid to get the BuildConfigValue + //This allows us to not make this a breaking change to embedding + this.applicationId = (String) BuildHelper.getBuildConfigValue(cordova.getActivity(), "APPLICATION_ID"); + this.applicationId = preferences.getString("applicationId", this.applicationId); + + + if (action.equals("takePicture")) { + this.srcType = CAMERA; + this.destType = FILE_URI; + this.saveToPhotoAlbum = false; + this.targetHeight = 0; + this.targetWidth = 0; + this.encodingType = JPEG; + this.mediaType = PICTURE; + this.mQuality = 50; + + //Take the values from the arguments if they're not already defined (this is tricky) + this.destType = args.getInt(1); + this.srcType = args.getInt(2); + this.mQuality = args.getInt(0); + this.targetWidth = args.getInt(3); + this.targetHeight = args.getInt(4); + this.encodingType = args.getInt(5); + this.mediaType = args.getInt(6); + this.allowEdit = args.getBoolean(7); + this.correctOrientation = args.getBoolean(8); + this.saveToPhotoAlbum = args.getBoolean(9); + + // If the user specifies a 0 or smaller width/height + // make it -1 so later comparisons succeed + if (this.targetWidth < 1) { + this.targetWidth = -1; + } + if (this.targetHeight < 1) { + this.targetHeight = -1; + } + + // We don't return full-quality PNG files. The camera outputs a JPEG + // so requesting it as a PNG provides no actual benefit + if (this.targetHeight == -1 && this.targetWidth == -1 && this.mQuality == 100 && + !this.correctOrientation && this.encodingType == PNG && this.srcType == CAMERA) { + this.encodingType = JPEG; + } + + try { + if (this.srcType == CAMERA) { + this.callTakePicture(destType, encodingType); + } + else if ((this.srcType == PHOTOLIBRARY) || (this.srcType == SAVEDPHOTOALBUM)) { + // FIXME: Stop always requesting the permission + if(!PermissionHelper.hasPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)) { + PermissionHelper.requestPermission(this, SAVE_TO_ALBUM_SEC, Manifest.permission.READ_EXTERNAL_STORAGE); + } else { + this.getImage(this.srcType, destType, encodingType); + } + } + } + catch (IllegalArgumentException e) + { + callbackContext.error("Illegal Argument Exception"); + PluginResult r = new PluginResult(PluginResult.Status.ERROR); + callbackContext.sendPluginResult(r); + return true; + } + + PluginResult r = new PluginResult(PluginResult.Status.NO_RESULT); + r.setKeepCallback(true); + callbackContext.sendPluginResult(r); + + return true; + } + return false; + } + + //-------------------------------------------------------------------------- + // LOCAL METHODS + //-------------------------------------------------------------------------- + + private String getTempDirectoryPath() { + File cache = null; + + // SD Card Mounted + if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { + cache = cordova.getActivity().getExternalCacheDir(); + } + // Use internal storage + else { + cache = cordova.getActivity().getCacheDir(); + } + + // Create the cache directory if it doesn't exist + cache.mkdirs(); + return cache.getAbsolutePath(); + } + + /** + * Take a picture with the camera. + * When an image is captured or the camera view is cancelled, the result is returned + * in CordovaActivity.onActivityResult, which forwards the result to this.onActivityResult. + * + * The image can either be returned as a base64 string or a URI that points to the file. + * To display base64 string in an img tag, set the source to: + * img.src="data:image/jpeg;base64,"+result; + * or to display URI in an img tag + * img.src=result; + * + * @param returnType Set the type of image to return. + * @param encodingType Compression quality hint (0-100: 0=low quality & high compression, 100=compress of max quality) + */ + public void callTakePicture(int returnType, int encodingType) { + boolean saveAlbumPermission = PermissionHelper.hasPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE); + boolean takePicturePermission = PermissionHelper.hasPermission(this, Manifest.permission.CAMERA); + + // CB-10120: The CAMERA permission does not need to be requested unless it is declared + // in AndroidManifest.xml. This plugin does not declare it, but others may and so we must + // check the package info to determine if the permission is present. + + if (!takePicturePermission) { + takePicturePermission = true; + try { + PackageManager packageManager = this.cordova.getActivity().getPackageManager(); + String[] permissionsInPackage = packageManager.getPackageInfo(this.cordova.getActivity().getPackageName(), PackageManager.GET_PERMISSIONS).requestedPermissions; + if (permissionsInPackage != null) { + for (String permission : permissionsInPackage) { + if (permission.equals(Manifest.permission.CAMERA)) { + takePicturePermission = false; + break; + } + } + } + } catch (NameNotFoundException e) { + // We are requesting the info for our package, so this should + // never be caught + } + } + + if (takePicturePermission && saveAlbumPermission) { + takePicture(returnType, encodingType); + } else if (saveAlbumPermission && !takePicturePermission) { + PermissionHelper.requestPermission(this, TAKE_PIC_SEC, Manifest.permission.CAMERA); + } else if (!saveAlbumPermission && takePicturePermission) { + PermissionHelper.requestPermission(this, TAKE_PIC_SEC, Manifest.permission.READ_EXTERNAL_STORAGE); + } else { + PermissionHelper.requestPermissions(this, TAKE_PIC_SEC, permissions); + } + } + + public void takePicture(int returnType, int encodingType) + { + // Save the number of images currently on disk for later + this.numPics = queryImgDB(whichContentStore()).getCount(); + + // Let's use the intent and see what happens + Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); + + // Specify file so that large image is captured and returned + File photo = createCaptureFile(encodingType); + this.imageUri = new CordovaUri(FileProvider.getUriForFile(cordova.getActivity(), + applicationId + ".provider", + photo)); + intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageUri.getCorrectUri()); + //We can write to this URI, this will hopefully allow us to write files to get to the next step + intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION); + + if (this.cordova != null) { + // Let's check to make sure the camera is actually installed. (Legacy Nexus 7 code) + PackageManager mPm = this.cordova.getActivity().getPackageManager(); + if(intent.resolveActivity(mPm) != null) + { + + this.cordova.startActivityForResult((CordovaPlugin) this, intent, (CAMERA + 1) * 16 + returnType + 1); + } + else + { + LOG.d(LOG_TAG, "Error: You don't have a default camera. Your device may not be CTS complaint."); + } + } +// else +// LOG.d(LOG_TAG, "ERROR: You must use the CordovaInterface for this to work correctly. Please implement it in your activity"); + } + + /** + * Create a file in the applications temporary directory based upon the supplied encoding. + * + * @param encodingType of the image to be taken + * @return a File object pointing to the temporary picture + */ + private File createCaptureFile(int encodingType) { + return createCaptureFile(encodingType, ""); + } + + /** + * Create a file in the applications temporary directory based upon the supplied encoding. + * + * @param encodingType of the image to be taken + * @param fileName or resultant File object. + * @return a File object pointing to the temporary picture + */ + private File createCaptureFile(int encodingType, String fileName) { + if (fileName.isEmpty()) { + fileName = ".Pic"; + } + + if (encodingType == JPEG) { + fileName = fileName + ".jpg"; + } else if (encodingType == PNG) { + fileName = fileName + ".png"; + } else { + throw new IllegalArgumentException("Invalid Encoding Type: " + encodingType); + } + + return new File(getTempDirectoryPath(), fileName); + } + + + + /** + * Get image from photo library. + * + * @param srcType The album to get image from. + * @param returnType Set the type of image to return. + * @param encodingType + */ + // TODO: Images selected from SDCARD don't display correctly, but from CAMERA ALBUM do! + // TODO: Images from kitkat filechooser not going into crop function + public void getImage(int srcType, int returnType, int encodingType) { + Intent intent = new Intent(); + String title = GET_PICTURE; + croppedUri = null; + if (this.mediaType == PICTURE) { + intent.setType("image/*"); + if (this.allowEdit) { + intent.setAction(Intent.ACTION_PICK); + intent.putExtra("crop", "true"); + if (targetWidth > 0) { + intent.putExtra("outputX", targetWidth); + } + if (targetHeight > 0) { + intent.putExtra("outputY", targetHeight); + } + if (targetHeight > 0 && targetWidth > 0 && targetWidth == targetHeight) { + intent.putExtra("aspectX", 1); + intent.putExtra("aspectY", 1); + } + File photo = createCaptureFile(JPEG); + croppedUri = Uri.fromFile(photo); + intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, croppedUri); + } else { + intent.setAction(Intent.ACTION_GET_CONTENT); + intent.addCategory(Intent.CATEGORY_OPENABLE); + } + } else if (this.mediaType == VIDEO) { + intent.setType("video/*"); + title = GET_VIDEO; + intent.setAction(Intent.ACTION_GET_CONTENT); + intent.addCategory(Intent.CATEGORY_OPENABLE); + } else if (this.mediaType == ALLMEDIA) { + // I wanted to make the type 'image/*, video/*' but this does not work on all versions + // of android so I had to go with the wildcard search. + intent.setType("*/*"); + title = GET_All; + intent.setAction(Intent.ACTION_GET_CONTENT); + intent.addCategory(Intent.CATEGORY_OPENABLE); + } + if (this.cordova != null) { + this.cordova.startActivityForResult((CordovaPlugin) this, Intent.createChooser(intent, + new String(title)), (srcType + 1) * 16 + returnType + 1); + } + } + + + /** + * Brings up the UI to perform crop on passed image URI + * + * @param picUri + */ + private void performCrop(Uri picUri, int destType, Intent cameraIntent) { + try { + Intent cropIntent = new Intent("com.android.camera.action.CROP"); + // indicate image type and Uri + cropIntent.setDataAndType(picUri, "image/*"); + // set crop properties + cropIntent.putExtra("crop", "true"); + + + // indicate output X and Y + if (targetWidth > 0) { + cropIntent.putExtra("outputX", targetWidth); + } + if (targetHeight > 0) { + cropIntent.putExtra("outputY", targetHeight); + } + if (targetHeight > 0 && targetWidth > 0 && targetWidth == targetHeight) { + cropIntent.putExtra("aspectX", 1); + cropIntent.putExtra("aspectY", 1); + } + // create new file handle to get full resolution crop + croppedUri = Uri.fromFile(createCaptureFile(this.encodingType, System.currentTimeMillis() + "")); + cropIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); + cropIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION); + cropIntent.putExtra("output", croppedUri); + + + // start the activity - we handle returning in onActivityResult + + if (this.cordova != null) { + this.cordova.startActivityForResult((CordovaPlugin) this, + cropIntent, CROP_CAMERA + destType); + } + } catch (ActivityNotFoundException anfe) { + LOG.e(LOG_TAG, "Crop operation not supported on this device"); + try { + processResultFromCamera(destType, cameraIntent); + } + catch (IOException e) + { + e.printStackTrace(); + LOG.e(LOG_TAG, "Unable to write to file"); + } + } + } + + /** + * Applies all needed transformation to the image received from the camera. + * + * @param destType In which form should we return the image + * @param intent An Intent, which can return result data to the caller (various data can be attached to Intent "extras"). + */ + private void processResultFromCamera(int destType, Intent intent) throws IOException { + int rotate = 0; + + // Create an ExifHelper to save the exif data that is lost during compression + ExifHelper exif = new ExifHelper(); + + String sourcePath = (this.allowEdit && this.croppedUri != null) ? + FileHelper.stripFileProtocol(this.croppedUri.toString()) : + this.imageUri.getFilePath(); + + + if (this.encodingType == JPEG) { + try { + //We don't support PNG, so let's not pretend we do + exif.createInFile(sourcePath); + exif.readExifData(); + rotate = exif.getOrientation(); + + } catch (IOException e) { + e.printStackTrace(); + } + } + + Bitmap bitmap = null; + Uri galleryUri = null; + + // CB-5479 When this option is given the unchanged image should be saved + // in the gallery and the modified image is saved in the temporary + // directory + if (this.saveToPhotoAlbum) { + galleryUri = Uri.fromFile(new File(getPicturesPath())); + + if (this.allowEdit && this.croppedUri != null) { + writeUncompressedImage(croppedUri, galleryUri); + } else { + Uri imageUri = this.imageUri.getFileUri(); + writeUncompressedImage(imageUri, galleryUri); + } + + refreshGallery(galleryUri); + } + + // If sending base64 image back + if (destType == DATA_URL) { + bitmap = getScaledAndRotatedBitmap(sourcePath); + + if (bitmap == null) { + // Try to get the bitmap from intent. + bitmap = (Bitmap) intent.getExtras().get("data"); + } + + // Double-check the bitmap. + if (bitmap == null) { + LOG.d(LOG_TAG, "I either have a null image path or bitmap"); + this.failPicture("Unable to create bitmap!"); + return; + } + + + this.processPicture(bitmap, this.encodingType); + + if (!this.saveToPhotoAlbum) { + checkForDuplicateImage(DATA_URL); + } + } + + // If sending filename back + else if (destType == FILE_URI || destType == NATIVE_URI) { + // If all this is true we shouldn't compress the image. + if (this.targetHeight == -1 && this.targetWidth == -1 && this.mQuality == 100 && + !this.correctOrientation) { + + // If we saved the uncompressed photo to the album, we can just + // return the URI we already created + if (this.saveToPhotoAlbum) { + this.callbackContext.success(galleryUri.toString()); + } else { + Uri uri = Uri.fromFile(createCaptureFile(this.encodingType, System.currentTimeMillis() + "")); + + if (this.allowEdit && this.croppedUri != null) { + Uri croppedUri = Uri.fromFile(new File(getFileNameFromUri(this.croppedUri))); + writeUncompressedImage(croppedUri, uri); + } else { + Uri imageUri = this.imageUri.getFileUri(); + writeUncompressedImage(imageUri, uri); + } + + this.callbackContext.success(uri.toString()); + } + } else { + Uri uri = Uri.fromFile(createCaptureFile(this.encodingType, System.currentTimeMillis() + "")); + bitmap = getScaledAndRotatedBitmap(sourcePath); + + // Double-check the bitmap. + if (bitmap == null) { + LOG.d(LOG_TAG, "I either have a null image path or bitmap"); + this.failPicture("Unable to create bitmap!"); + return; + } + + + // Add compressed version of captured image to returned media store Uri + OutputStream os = this.cordova.getActivity().getContentResolver().openOutputStream(uri); + CompressFormat compressFormat = encodingType == JPEG ? + CompressFormat.JPEG : + CompressFormat.PNG; + + bitmap.compress(compressFormat, this.mQuality, os); + os.close(); + + // Restore exif data to file + if (this.encodingType == JPEG) { + String exifPath; + exifPath = uri.getPath(); + //We just finished rotating it by an arbitrary orientation, just make sure it's normal + if(rotate != ExifInterface.ORIENTATION_NORMAL) + exif.resetOrientation(); + exif.createOutFile(exifPath); + exif.writeExifData(); + } + + // Send Uri back to JavaScript for viewing image + this.callbackContext.success(uri.toString()); + + } + } else { + throw new IllegalStateException(); + } + + this.cleanup(FILE_URI, this.imageUri.getFileUri(), galleryUri, bitmap); + bitmap = null; + } + + private String getPicturesPath() { + String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); + String imageFileName = "IMG_" + timeStamp + (this.encodingType == JPEG ? ".jpg" : ".png"); + File storageDir = Environment.getExternalStoragePublicDirectory( + Environment.DIRECTORY_PICTURES); + String galleryPath = storageDir.getAbsolutePath() + "/" + imageFileName; + return galleryPath; + } + + private void refreshGallery(Uri contentUri) { + Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); + mediaScanIntent.setData(contentUri); + this.cordova.getActivity().sendBroadcast(mediaScanIntent); + } + + /** + * Converts output image format int value to string value of mime type. + * @param outputFormat int Output format of camera API. + * Must be value of either JPEG or PNG constant + * @return String String value of mime type or empty string if mime type is not supported + */ + private String getMimetypeForFormat(int outputFormat) { + if (outputFormat == PNG) return "image/png"; + if (outputFormat == JPEG) return "image/jpeg"; + return ""; + } + + + private String outputModifiedBitmap(Bitmap bitmap, Uri uri) throws IOException { + // Some content: URIs do not map to file paths (e.g. picasa). + String realPath = FileHelper.getRealPath(uri, this.cordova); + + // Get filename from uri + String fileName = realPath != null ? + realPath.substring(realPath.lastIndexOf('/') + 1) : + "modified." + (this.encodingType == JPEG ? "jpg" : "png"); + + String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); + //String fileName = "IMG_" + timeStamp + (this.encodingType == JPEG ? ".jpg" : ".png"); + String modifiedPath = getTempDirectoryPath() + "/" + fileName; + + OutputStream os = new FileOutputStream(modifiedPath); + CompressFormat compressFormat = this.encodingType == JPEG ? + CompressFormat.JPEG : + CompressFormat.PNG; + + bitmap.compress(compressFormat, this.mQuality, os); + os.close(); + + if (exifData != null && this.encodingType == JPEG) { + try { + if (this.correctOrientation && this.orientationCorrected) { + exifData.resetOrientation(); + } + exifData.createOutFile(modifiedPath); + exifData.writeExifData(); + exifData = null; + } catch (IOException e) { + e.printStackTrace(); + } + } + return modifiedPath; + } + + + /** + * Applies all needed transformation to the image received from the gallery. + * + * @param destType In which form should we return the image + * @param intent An Intent, which can return result data to the caller (various data can be attached to Intent "extras"). + */ + private void processResultFromGallery(int destType, Intent intent) { + Uri uri = intent.getData(); + if (uri == null) { + if (croppedUri != null) { + uri = croppedUri; + } else { + this.failPicture("null data from photo library"); + return; + } + } + int rotate = 0; + + String fileLocation = FileHelper.getRealPath(uri, this.cordova); + LOG.d(LOG_TAG, "File locaton is: " + fileLocation); + + // If you ask for video or all media type you will automatically get back a file URI + // and there will be no attempt to resize any returned data + if (this.mediaType != PICTURE) { + this.callbackContext.success(fileLocation); + } + else { + String uriString = uri.toString(); + // Get the path to the image. Makes loading so much easier. + String mimeType = FileHelper.getMimeType(uriString, this.cordova); + + // This is a special case to just return the path as no scaling, + // rotating, nor compressing needs to be done + if (this.targetHeight == -1 && this.targetWidth == -1 && + (destType == FILE_URI || destType == NATIVE_URI) && !this.correctOrientation && + mimeType.equalsIgnoreCase(getMimetypeForFormat(encodingType))) + { + this.callbackContext.success(uriString); + } else { + // If we don't have a valid image so quit. + if (!("image/jpeg".equalsIgnoreCase(mimeType) || "image/png".equalsIgnoreCase(mimeType))) { + LOG.d(LOG_TAG, "I either have a null image path or bitmap"); + this.failPicture("Unable to retrieve path to picture!"); + return; + } + Bitmap bitmap = null; + try { + bitmap = getScaledAndRotatedBitmap(uriString); + } catch (IOException e) { + e.printStackTrace(); + } + if (bitmap == null) { + LOG.d(LOG_TAG, "I either have a null image path or bitmap"); + this.failPicture("Unable to create bitmap!"); + return; + } + + // If sending base64 image back + if (destType == DATA_URL) { + this.processPicture(bitmap, this.encodingType); + } + + // If sending filename back + else if (destType == FILE_URI || destType == NATIVE_URI) { + // Did we modify the image? + if ( (this.targetHeight > 0 && this.targetWidth > 0) || + (this.correctOrientation && this.orientationCorrected) || + !mimeType.equalsIgnoreCase(getMimetypeForFormat(encodingType))) + { + try { + String modifiedPath = this.outputModifiedBitmap(bitmap, uri); + // The modified image is cached by the app in order to get around this and not have to delete you + // application cache I'm adding the current system time to the end of the file url. + this.callbackContext.success("file://" + modifiedPath + "?" + System.currentTimeMillis()); + + } catch (Exception e) { + e.printStackTrace(); + this.failPicture("Error retrieving image."); + } + } else { + this.callbackContext.success(fileLocation); + } + } + if (bitmap != null) { + bitmap.recycle(); + bitmap = null; + } + System.gc(); + } + } + } + + /** + * Called when the camera view exits. + * + * @param requestCode The request code originally supplied to startActivityForResult(), + * allowing you to identify who this result came from. + * @param resultCode The integer result code returned by the child activity through its setResult(). + * @param intent An Intent, which can return result data to the caller (various data can be attached to Intent "extras"). + */ + public void onActivityResult(int requestCode, int resultCode, Intent intent) { + + // Get src and dest types from request code for a Camera Activity + int srcType = (requestCode / 16) - 1; + int destType = (requestCode % 16) - 1; + + // If Camera Crop + if (requestCode >= CROP_CAMERA) { + if (resultCode == Activity.RESULT_OK) { + + // Because of the inability to pass through multiple intents, this hack will allow us + // to pass arcane codes back. + destType = requestCode - CROP_CAMERA; + try { + processResultFromCamera(destType, intent); + } catch (IOException e) { + e.printStackTrace(); + LOG.e(LOG_TAG, "Unable to write to file"); + } + + }// If cancelled + else if (resultCode == Activity.RESULT_CANCELED) { + this.failPicture("Camera cancelled."); + } + + // If something else + else { + this.failPicture("Did not complete!"); + } + } + // If CAMERA + else if (srcType == CAMERA) { + // If image available + if (resultCode == Activity.RESULT_OK) { + try { + if (this.allowEdit) { + Uri tmpFile = FileProvider.getUriForFile(cordova.getActivity(), + applicationId + ".provider", + createCaptureFile(this.encodingType)); + performCrop(tmpFile, destType, intent); + } else { + this.processResultFromCamera(destType, intent); + } + } catch (IOException e) { + e.printStackTrace(); + this.failPicture("Error capturing image."); + } + } + + // If cancelled + else if (resultCode == Activity.RESULT_CANCELED) { + this.failPicture("Camera cancelled."); + } + + // If something else + else { + this.failPicture("Did not complete!"); + } + } + // If retrieving photo from library + else if ((srcType == PHOTOLIBRARY) || (srcType == SAVEDPHOTOALBUM)) { + if (resultCode == Activity.RESULT_OK && intent != null) { + final Intent i = intent; + final int finalDestType = destType; + cordova.getThreadPool().execute(new Runnable() { + public void run() { + processResultFromGallery(finalDestType, i); + } + }); + } else if (resultCode == Activity.RESULT_CANCELED) { + this.failPicture("Selection cancelled."); + } else { + this.failPicture("Selection did not complete!"); + } + } + } + + private int exifToDegrees(int exifOrientation) { + if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_90) { + return 90; + } else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_180) { + return 180; + } else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_270) { + return 270; + } else { + return 0; + } + } + + /** + * Write an inputstream to local disk + * + * @param fis - The InputStream to write + * @param dest - Destination on disk to write to + * @throws FileNotFoundException + * @throws IOException + */ + private void writeUncompressedImage(InputStream fis, Uri dest) throws FileNotFoundException, + IOException { + OutputStream os = null; + try { + os = this.cordova.getActivity().getContentResolver().openOutputStream(dest); + byte[] buffer = new byte[4096]; + int len; + while ((len = fis.read(buffer)) != -1) { + os.write(buffer, 0, len); + } + os.flush(); + } finally { + if (os != null) { + try { + os.close(); + } catch (IOException e) { + LOG.d(LOG_TAG, "Exception while closing output stream."); + } + } + if (fis != null) { + try { + fis.close(); + } catch (IOException e) { + LOG.d(LOG_TAG, "Exception while closing file input stream."); + } + } + } + } + /** + * In the special case where the default width, height and quality are unchanged + * we just write the file out to disk saving the expensive Bitmap.compress function. + * + * @param src + * @throws FileNotFoundException + * @throws IOException + */ + private void writeUncompressedImage(Uri src, Uri dest) throws FileNotFoundException, + IOException { + + FileInputStream fis = new FileInputStream(FileHelper.stripFileProtocol(src.toString())); + writeUncompressedImage(fis, dest); + + } + + /** + * Create entry in media store for image + * + * @return uri + */ + private Uri getUriFromMediaStore() { + ContentValues values = new ContentValues(); + values.put(android.provider.MediaStore.Images.Media.MIME_TYPE, "image/jpeg"); + Uri uri; + try { + uri = this.cordova.getActivity().getContentResolver().insert(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); + } catch (RuntimeException e) { + LOG.d(LOG_TAG, "Can't write to external media storage."); + try { + uri = this.cordova.getActivity().getContentResolver().insert(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI, values); + } catch (RuntimeException ex) { + LOG.d(LOG_TAG, "Can't write to internal media storage."); + return null; + } + } + return uri; + } + + /** + * Return a scaled and rotated bitmap based on the target width and height + * + * @param imageUrl + * @return + * @throws IOException + */ + private Bitmap getScaledAndRotatedBitmap(String imageUrl) throws IOException { + // If no new width or height were specified, and orientation is not needed return the original bitmap + if (this.targetWidth <= 0 && this.targetHeight <= 0 && !(this.correctOrientation)) { + InputStream fileStream = null; + Bitmap image = null; + try { + fileStream = FileHelper.getInputStreamFromUriString(imageUrl, cordova); + image = BitmapFactory.decodeStream(fileStream); + } finally { + if (fileStream != null) { + try { + fileStream.close(); + } catch (IOException e) { + LOG.d(LOG_TAG, "Exception while closing file input stream."); + } + } + } + return image; + } + + + /* Copy the inputstream to a temporary file on the device. + We then use this temporary file to determine the width/height/orientation. + This is the only way to determine the orientation of the photo coming from 3rd party providers (Google Drive, Dropbox,etc) + This also ensures we create a scaled bitmap with the correct orientation + + We delete the temporary file once we are done + */ + File localFile = null; + Uri galleryUri = null; + int rotate = 0; + try { + InputStream fileStream = FileHelper.getInputStreamFromUriString(imageUrl, cordova); + if (fileStream != null) { + // Generate a temporary file + String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); + String fileName = "IMG_" + timeStamp + (this.encodingType == JPEG ? ".jpg" : ".png"); + localFile = new File(getTempDirectoryPath() + fileName); + galleryUri = Uri.fromFile(localFile); + writeUncompressedImage(fileStream, galleryUri); + try { + String mimeType = FileHelper.getMimeType(imageUrl.toString(), cordova); + if ("image/jpeg".equalsIgnoreCase(mimeType)) { + // ExifInterface doesn't like the file:// prefix + String filePath = galleryUri.toString().replace("file://", ""); + // read exifData of source + exifData = new ExifHelper(); + exifData.createInFile(filePath); + // Use ExifInterface to pull rotation information + if (this.correctOrientation) { + ExifInterface exif = new ExifInterface(filePath); + rotate = exifToDegrees(exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED)); + } + } + } catch (Exception oe) { + LOG.w(LOG_TAG,"Unable to read Exif data: "+ oe.toString()); + rotate = 0; + } + } + } + catch (Exception e) + { + LOG.e(LOG_TAG,"Exception while getting input stream: "+ e.toString()); + return null; + } + + + + try { + // figure out the original width and height of the image + BitmapFactory.Options options = new BitmapFactory.Options(); + options.inJustDecodeBounds = true; + InputStream fileStream = null; + try { + fileStream = FileHelper.getInputStreamFromUriString(galleryUri.toString(), cordova); + BitmapFactory.decodeStream(fileStream, null, options); + } finally { + if (fileStream != null) { + try { + fileStream.close(); + } catch (IOException e) { + LOG.d(LOG_TAG, "Exception while closing file input stream."); + } + } + } + + + //CB-2292: WTF? Why is the width null? + if (options.outWidth == 0 || options.outHeight == 0) { + return null; + } + + // User didn't specify output dimensions, but they need orientation + if (this.targetWidth <= 0 && this.targetHeight <= 0) { + this.targetWidth = options.outWidth; + this.targetHeight = options.outHeight; + } + + // Setup target width/height based on orientation + int rotatedWidth, rotatedHeight; + boolean rotated= false; + if (rotate == 90 || rotate == 270) { + rotatedWidth = options.outHeight; + rotatedHeight = options.outWidth; + rotated = true; + } else { + rotatedWidth = options.outWidth; + rotatedHeight = options.outHeight; + } + + // determine the correct aspect ratio + int[] widthHeight = calculateAspectRatio(rotatedWidth, rotatedHeight); + + + // Load in the smallest bitmap possible that is closest to the size we want + options.inJustDecodeBounds = false; + options.inSampleSize = calculateSampleSize(rotatedWidth, rotatedHeight, widthHeight[0], widthHeight[1]); + Bitmap unscaledBitmap = null; + try { + fileStream = FileHelper.getInputStreamFromUriString(galleryUri.toString(), cordova); + unscaledBitmap = BitmapFactory.decodeStream(fileStream, null, options); + } finally { + if (fileStream != null) { + try { + fileStream.close(); + } catch (IOException e) { + LOG.d(LOG_TAG, "Exception while closing file input stream."); + } + } + } + if (unscaledBitmap == null) { + return null; + } + + int scaledWidth = (!rotated) ? widthHeight[0] : widthHeight[1]; + int scaledHeight = (!rotated) ? widthHeight[1] : widthHeight[0]; + + Bitmap scaledBitmap = Bitmap.createScaledBitmap(unscaledBitmap, scaledWidth, scaledHeight, true); + if (scaledBitmap != unscaledBitmap) { + unscaledBitmap.recycle(); + unscaledBitmap = null; + } + if (this.correctOrientation && (rotate != 0)) { + Matrix matrix = new Matrix(); + matrix.setRotate(rotate); + try { + scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix, true); + this.orientationCorrected = true; + } catch (OutOfMemoryError oom) { + this.orientationCorrected = false; + } + } + return scaledBitmap; + } + finally { + // delete the temporary copy + if (localFile != null) { + localFile.delete(); + } + } + + } + + /** + * Maintain the aspect ratio so the resulting image does not look smooshed + * + * @param origWidth + * @param origHeight + * @return + */ + public int[] calculateAspectRatio(int origWidth, int origHeight) { + int newWidth = this.targetWidth; + int newHeight = this.targetHeight; + + // If no new width or height were specified return the original bitmap + if (newWidth <= 0 && newHeight <= 0) { + newWidth = origWidth; + newHeight = origHeight; + } + // Only the width was specified + else if (newWidth > 0 && newHeight <= 0) { + newHeight = (int)((double)(newWidth / (double)origWidth) * origHeight); + } + // only the height was specified + else if (newWidth <= 0 && newHeight > 0) { + newWidth = (int)((double)(newHeight / (double)origHeight) * origWidth); + } + // If the user specified both a positive width and height + // (potentially different aspect ratio) then the width or height is + // scaled so that the image fits while maintaining aspect ratio. + // Alternatively, the specified width and height could have been + // kept and Bitmap.SCALE_TO_FIT specified when scaling, but this + // would result in whitespace in the new image. + else { + double newRatio = newWidth / (double) newHeight; + double origRatio = origWidth / (double) origHeight; + + if (origRatio > newRatio) { + newHeight = (newWidth * origHeight) / origWidth; + } else if (origRatio < newRatio) { + newWidth = (newHeight * origWidth) / origHeight; + } + } + + int[] retval = new int[2]; + retval[0] = newWidth; + retval[1] = newHeight; + return retval; + } + + /** + * Figure out what ratio we can load our image into memory at while still being bigger than + * our desired width and height + * + * @param srcWidth + * @param srcHeight + * @param dstWidth + * @param dstHeight + * @return + */ + public static int calculateSampleSize(int srcWidth, int srcHeight, int dstWidth, int dstHeight) { + final float srcAspect = (float) srcWidth / (float) srcHeight; + final float dstAspect = (float) dstWidth / (float) dstHeight; + + if (srcAspect > dstAspect) { + return srcWidth / dstWidth; + } else { + return srcHeight / dstHeight; + } + } + + /** + * Creates a cursor that can be used to determine how many images we have. + * + * @return a cursor + */ + private Cursor queryImgDB(Uri contentStore) { + return this.cordova.getActivity().getContentResolver().query( + contentStore, + new String[]{MediaStore.Images.Media._ID}, + null, + null, + null); + } + + /** + * Cleans up after picture taking. Checking for duplicates and that kind of stuff. + * + * @param newImage + */ + private void cleanup(int imageType, Uri oldImage, Uri newImage, Bitmap bitmap) { + if (bitmap != null) { + bitmap.recycle(); + } + + // Clean up initial camera-written image file. + (new File(FileHelper.stripFileProtocol(oldImage.toString()))).delete(); + + checkForDuplicateImage(imageType); + // Scan for the gallery to update pic refs in gallery + if (this.saveToPhotoAlbum && newImage != null) { + this.scanForGallery(newImage); + } + + System.gc(); + } + + /** + * Used to find out if we are in a situation where the Camera Intent adds to images + * to the content store. If we are using a FILE_URI and the number of images in the DB + * increases by 2 we have a duplicate, when using a DATA_URL the number is 1. + * + * @param type FILE_URI or DATA_URL + */ + private void checkForDuplicateImage(int type) { + int diff = 1; + Uri contentStore = whichContentStore(); + Cursor cursor = queryImgDB(contentStore); + int currentNumOfImages = cursor.getCount(); + + if (type == FILE_URI && this.saveToPhotoAlbum) { + diff = 2; + } + + // delete the duplicate file if the difference is 2 for file URI or 1 for Data URL + if ((currentNumOfImages - numPics) == diff) { + cursor.moveToLast(); + int id = Integer.valueOf(cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media._ID))); + if (diff == 2) { + id--; + } + Uri uri = Uri.parse(contentStore + "/" + id); + this.cordova.getActivity().getContentResolver().delete(uri, null, null); + cursor.close(); + } + } + + /** + * Determine if we are storing the images in internal or external storage + * + * @return Uri + */ + private Uri whichContentStore() { + if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { + return android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI; + } else { + return android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI; + } + } + + /** + * Compress bitmap using jpeg, convert to Base64 encoded string, and return to JavaScript. + * + * @param bitmap + */ + public void processPicture(Bitmap bitmap, int encodingType) { + ByteArrayOutputStream jpeg_data = new ByteArrayOutputStream(); + CompressFormat compressFormat = encodingType == JPEG ? + CompressFormat.JPEG : + CompressFormat.PNG; + + try { + if (bitmap.compress(compressFormat, mQuality, jpeg_data)) { + byte[] code = jpeg_data.toByteArray(); + byte[] output = Base64.encode(code, Base64.NO_WRAP); + String js_out = new String(output); + this.callbackContext.success(js_out); + js_out = null; + output = null; + code = null; + } + } catch (Exception e) { + this.failPicture("Error compressing image."); + } + jpeg_data = null; + } + + /** + * Send error message to JavaScript. + * + * @param err + */ + public void failPicture(String err) { + this.callbackContext.error(err); + } + + private void scanForGallery(Uri newImage) { + this.scanMe = newImage; + if (this.conn != null) { + this.conn.disconnect(); + } + this.conn = new MediaScannerConnection(this.cordova.getActivity().getApplicationContext(), this); + conn.connect(); + } + + public void onMediaScannerConnected() { + try { + this.conn.scanFile(this.scanMe.toString(), "image/*"); + } catch (java.lang.IllegalStateException e) { + LOG.e(LOG_TAG, "Can't scan file in MediaScanner after taking picture"); + } + + } + + public void onScanCompleted(String path, Uri uri) { + this.conn.disconnect(); + } + + + public void onRequestPermissionResult(int requestCode, String[] permissions, + int[] grantResults) throws JSONException { + for (int r : grantResults) { + if (r == PackageManager.PERMISSION_DENIED) { + this.callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, PERMISSION_DENIED_ERROR)); + return; + } + } + switch (requestCode) { + case TAKE_PIC_SEC: + takePicture(this.destType, this.encodingType); + break; + case SAVE_TO_ALBUM_SEC: + this.getImage(this.srcType, this.destType, this.encodingType); + break; + } + } + + /** + * Taking or choosing a picture launches another Activity, so we need to implement the + * save/restore APIs to handle the case where the CordovaActivity is killed by the OS + * before we get the launched Activity's result. + */ + public Bundle onSaveInstanceState() { + Bundle state = new Bundle(); + state.putInt("destType", this.destType); + state.putInt("srcType", this.srcType); + state.putInt("mQuality", this.mQuality); + state.putInt("targetWidth", this.targetWidth); + state.putInt("targetHeight", this.targetHeight); + state.putInt("encodingType", this.encodingType); + state.putInt("mediaType", this.mediaType); + state.putInt("numPics", this.numPics); + state.putBoolean("allowEdit", this.allowEdit); + state.putBoolean("correctOrientation", this.correctOrientation); + state.putBoolean("saveToPhotoAlbum", this.saveToPhotoAlbum); + + if (this.croppedUri != null) { + state.putString("croppedUri", this.croppedUri.toString()); + } + + if (this.imageUri != null) { + state.putString("imageUri", this.imageUri.getFileUri().toString()); + } + + return state; + } + + public void onRestoreStateForActivityResult(Bundle state, CallbackContext callbackContext) { + this.destType = state.getInt("destType"); + this.srcType = state.getInt("srcType"); + this.mQuality = state.getInt("mQuality"); + this.targetWidth = state.getInt("targetWidth"); + this.targetHeight = state.getInt("targetHeight"); + this.encodingType = state.getInt("encodingType"); + this.mediaType = state.getInt("mediaType"); + this.numPics = state.getInt("numPics"); + this.allowEdit = state.getBoolean("allowEdit"); + this.correctOrientation = state.getBoolean("correctOrientation"); + this.saveToPhotoAlbum = state.getBoolean("saveToPhotoAlbum"); + + if (state.containsKey("croppedUri")) { + this.croppedUri = Uri.parse(state.getString("croppedUri")); + } + + if (state.containsKey("imageUri")) { + //I have no idea what type of URI is being passed in + this.imageUri = new CordovaUri(Uri.parse(state.getString("imageUri"))); + } + + this.callbackContext = callbackContext; + } + + /* + * This is dirty, but it does the job. + * + * Since the FilesProvider doesn't really provide you a way of getting a URL from the file, + * and since we actually need the Camera to create the file for us most of the time, we don't + * actually write the file, just generate the location based on a timestamp, we need to get it + * back from the Intent. + * + * However, the FilesProvider preserves the path, so we can at least write to it from here, since + * we own the context in this case. + */ + + private String getFileNameFromUri(Uri uri) { + String fullUri = uri.toString(); + String partial_path = fullUri.split("external_files")[1]; + File external_storage = Environment.getExternalStorageDirectory(); + String path = external_storage.getAbsolutePath() + partial_path; + return path; + + } + + +} diff --git a/plugins/cordova-plugin-camera/src/android/CordovaUri.java b/plugins/cordova-plugin-camera/src/android/CordovaUri.java new file mode 100644 index 0000000..5c2224d --- /dev/null +++ b/plugins/cordova-plugin-camera/src/android/CordovaUri.java @@ -0,0 +1,104 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. +*/ + +package org.apache.cordova.camera; + +import android.net.Uri; +import android.os.Build; +import android.os.Environment; +import android.support.v4.content.FileProvider; + +import java.io.File; + +/* + * This class exists because Andorid FilesProvider doesn't work on Android 4.4.4 and below and throws + * weird errors. I'm not sure why writing to shared cache directories is somehow verboten, but it is + * and this error is irritating for a Compatibility library to have. + * + */ + +public class CordovaUri { + + private Uri androidUri; + private String fileName; + private Uri fileUri; + + /* + * We always expect a FileProvider string to be passed in for the file that we create + * + */ + CordovaUri (Uri inputUri) + { + //Determine whether the file is a content or file URI + if(inputUri.getScheme().equals("content")) + { + androidUri = inputUri; + fileName = getFileNameFromUri(androidUri); + fileUri = Uri.parse("file://" + fileName); + } + else + { + fileUri = inputUri; + fileName = FileHelper.stripFileProtocol(inputUri.toString()); + } + } + + public Uri getFileUri() + { + return fileUri; + } + + public String getFilePath() + { + return fileName; + } + + /* + * This only gets called by takePicture + */ + + public Uri getCorrectUri() + { + if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) + return androidUri; + else + return fileUri; + } + + /* + * This is dirty, but it does the job. + * + * Since the FilesProvider doesn't really provide you a way of getting a URL from the file, + * and since we actually need the Camera to create the file for us most of the time, we don't + * actually write the file, just generate the location based on a timestamp, we need to get it + * back from the Intent. + * + * However, the FilesProvider preserves the path, so we can at least write to it from here, since + * we own the context in this case. + */ + + private String getFileNameFromUri(Uri uri) { + String fullUri = uri.toString(); + String partial_path = fullUri.split("external_files")[1]; + File external_storage = Environment.getExternalStorageDirectory(); + String path = external_storage.getAbsolutePath() + partial_path; + return path; + + } +} diff --git a/plugins/cordova-plugin-camera/src/android/ExifHelper.java b/plugins/cordova-plugin-camera/src/android/ExifHelper.java new file mode 100644 index 0000000..5160a2f --- /dev/null +++ b/plugins/cordova-plugin-camera/src/android/ExifHelper.java @@ -0,0 +1,185 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. +*/ +package org.apache.cordova.camera; + +import java.io.IOException; + +import android.media.ExifInterface; + +public class ExifHelper { + private String aperture = null; + private String datetime = null; + private String exposureTime = null; + private String flash = null; + private String focalLength = null; + private String gpsAltitude = null; + private String gpsAltitudeRef = null; + private String gpsDateStamp = null; + private String gpsLatitude = null; + private String gpsLatitudeRef = null; + private String gpsLongitude = null; + private String gpsLongitudeRef = null; + private String gpsProcessingMethod = null; + private String gpsTimestamp = null; + private String iso = null; + private String make = null; + private String model = null; + private String orientation = null; + private String whiteBalance = null; + + private ExifInterface inFile = null; + private ExifInterface outFile = null; + + /** + * The file before it is compressed + * + * @param filePath + * @throws IOException + */ + public void createInFile(String filePath) throws IOException { + this.inFile = new ExifInterface(filePath); + } + + /** + * The file after it has been compressed + * + * @param filePath + * @throws IOException + */ + public void createOutFile(String filePath) throws IOException { + this.outFile = new ExifInterface(filePath); + } + + /** + * Reads all the EXIF data from the input file. + */ + public void readExifData() { + this.aperture = inFile.getAttribute(ExifInterface.TAG_APERTURE); + this.datetime = inFile.getAttribute(ExifInterface.TAG_DATETIME); + this.exposureTime = inFile.getAttribute(ExifInterface.TAG_EXPOSURE_TIME); + this.flash = inFile.getAttribute(ExifInterface.TAG_FLASH); + this.focalLength = inFile.getAttribute(ExifInterface.TAG_FOCAL_LENGTH); + this.gpsAltitude = inFile.getAttribute(ExifInterface.TAG_GPS_ALTITUDE); + this.gpsAltitudeRef = inFile.getAttribute(ExifInterface.TAG_GPS_ALTITUDE_REF); + this.gpsDateStamp = inFile.getAttribute(ExifInterface.TAG_GPS_DATESTAMP); + this.gpsLatitude = inFile.getAttribute(ExifInterface.TAG_GPS_LATITUDE); + this.gpsLatitudeRef = inFile.getAttribute(ExifInterface.TAG_GPS_LATITUDE_REF); + this.gpsLongitude = inFile.getAttribute(ExifInterface.TAG_GPS_LONGITUDE); + this.gpsLongitudeRef = inFile.getAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF); + this.gpsProcessingMethod = inFile.getAttribute(ExifInterface.TAG_GPS_PROCESSING_METHOD); + this.gpsTimestamp = inFile.getAttribute(ExifInterface.TAG_GPS_TIMESTAMP); + this.iso = inFile.getAttribute(ExifInterface.TAG_ISO); + this.make = inFile.getAttribute(ExifInterface.TAG_MAKE); + this.model = inFile.getAttribute(ExifInterface.TAG_MODEL); + this.orientation = inFile.getAttribute(ExifInterface.TAG_ORIENTATION); + this.whiteBalance = inFile.getAttribute(ExifInterface.TAG_WHITE_BALANCE); + } + + /** + * Writes the previously stored EXIF data to the output file. + * + * @throws IOException + */ + public void writeExifData() throws IOException { + // Don't try to write to a null file + if (this.outFile == null) { + return; + } + + if (this.aperture != null) { + this.outFile.setAttribute(ExifInterface.TAG_APERTURE, this.aperture); + } + if (this.datetime != null) { + this.outFile.setAttribute(ExifInterface.TAG_DATETIME, this.datetime); + } + if (this.exposureTime != null) { + this.outFile.setAttribute(ExifInterface.TAG_EXPOSURE_TIME, this.exposureTime); + } + if (this.flash != null) { + this.outFile.setAttribute(ExifInterface.TAG_FLASH, this.flash); + } + if (this.focalLength != null) { + this.outFile.setAttribute(ExifInterface.TAG_FOCAL_LENGTH, this.focalLength); + } + if (this.gpsAltitude != null) { + this.outFile.setAttribute(ExifInterface.TAG_GPS_ALTITUDE, this.gpsAltitude); + } + if (this.gpsAltitudeRef != null) { + this.outFile.setAttribute(ExifInterface.TAG_GPS_ALTITUDE_REF, this.gpsAltitudeRef); + } + if (this.gpsDateStamp != null) { + this.outFile.setAttribute(ExifInterface.TAG_GPS_DATESTAMP, this.gpsDateStamp); + } + if (this.gpsLatitude != null) { + this.outFile.setAttribute(ExifInterface.TAG_GPS_LATITUDE, this.gpsLatitude); + } + if (this.gpsLatitudeRef != null) { + this.outFile.setAttribute(ExifInterface.TAG_GPS_LATITUDE_REF, this.gpsLatitudeRef); + } + if (this.gpsLongitude != null) { + this.outFile.setAttribute(ExifInterface.TAG_GPS_LONGITUDE, this.gpsLongitude); + } + if (this.gpsLongitudeRef != null) { + this.outFile.setAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF, this.gpsLongitudeRef); + } + if (this.gpsProcessingMethod != null) { + this.outFile.setAttribute(ExifInterface.TAG_GPS_PROCESSING_METHOD, this.gpsProcessingMethod); + } + if (this.gpsTimestamp != null) { + this.outFile.setAttribute(ExifInterface.TAG_GPS_TIMESTAMP, this.gpsTimestamp); + } + if (this.iso != null) { + this.outFile.setAttribute(ExifInterface.TAG_ISO, this.iso); + } + if (this.make != null) { + this.outFile.setAttribute(ExifInterface.TAG_MAKE, this.make); + } + if (this.model != null) { + this.outFile.setAttribute(ExifInterface.TAG_MODEL, this.model); + } + if (this.orientation != null) { + this.outFile.setAttribute(ExifInterface.TAG_ORIENTATION, this.orientation); + } + if (this.whiteBalance != null) { + this.outFile.setAttribute(ExifInterface.TAG_WHITE_BALANCE, this.whiteBalance); + } + + this.outFile.saveAttributes(); + } + + public int getOrientation() { + int o = Integer.parseInt(this.orientation); + + if (o == ExifInterface.ORIENTATION_NORMAL) { + return 0; + } else if (o == ExifInterface.ORIENTATION_ROTATE_90) { + return 90; + } else if (o == ExifInterface.ORIENTATION_ROTATE_180) { + return 180; + } else if (o == ExifInterface.ORIENTATION_ROTATE_270) { + return 270; + } else { + return 0; + } + } + + public void resetOrientation() { + this.orientation = "" + ExifInterface.ORIENTATION_NORMAL; + } +} diff --git a/plugins/cordova-plugin-camera/src/android/FileHelper.java b/plugins/cordova-plugin-camera/src/android/FileHelper.java new file mode 100644 index 0000000..ccc5e3e --- /dev/null +++ b/plugins/cordova-plugin-camera/src/android/FileHelper.java @@ -0,0 +1,319 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. + */ +package org.apache.cordova.camera; + +import android.annotation.SuppressLint; +import android.content.ContentUris; +import android.content.Context; +import android.content.CursorLoader; +import android.database.Cursor; +import android.net.Uri; +import android.os.Build; +import android.os.Environment; +import android.provider.DocumentsContract; +import android.provider.MediaStore; +import android.webkit.MimeTypeMap; + +import org.apache.cordova.CordovaInterface; +import org.apache.cordova.LOG; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Locale; + +public class FileHelper { + private static final String LOG_TAG = "FileUtils"; + private static final String _DATA = "_data"; + + /** + * Returns the real path of the given URI string. + * If the given URI string represents a content:// URI, the real path is retrieved from the media store. + * + * @param uriString the URI string of the audio/image/video + * @param cordova the current application context + * @return the full path to the file + */ + @SuppressWarnings("deprecation") + public static String getRealPath(Uri uri, CordovaInterface cordova) { + String realPath = null; + + if (Build.VERSION.SDK_INT < 11) + realPath = FileHelper.getRealPathFromURI_BelowAPI11(cordova.getActivity(), uri); + + // SDK >= 11 + else + realPath = FileHelper.getRealPathFromURI_API11_And_Above(cordova.getActivity(), uri); + + return realPath; + } + + /** + * Returns the real path of the given URI. + * If the given URI is a content:// URI, the real path is retrieved from the media store. + * + * @param uri the URI of the audio/image/video + * @param cordova the current application context + * @return the full path to the file + */ + public static String getRealPath(String uriString, CordovaInterface cordova) { + return FileHelper.getRealPath(Uri.parse(uriString), cordova); + } + + @SuppressLint("NewApi") + public static String getRealPathFromURI_API11_And_Above(final Context context, final Uri uri) { + + final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT; + // DocumentProvider + if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) { + + // ExternalStorageProvider + if (isExternalStorageDocument(uri)) { + final String docId = DocumentsContract.getDocumentId(uri); + final String[] split = docId.split(":"); + final String type = split[0]; + + if ("primary".equalsIgnoreCase(type)) { + return Environment.getExternalStorageDirectory() + "/" + split[1]; + } + + // TODO handle non-primary volumes + } + // DownloadsProvider + else if (isDownloadsDocument(uri)) { + + final String id = DocumentsContract.getDocumentId(uri); + final Uri contentUri = ContentUris.withAppendedId( + Uri.parse("content://downloads/public_downloads"), Long.valueOf(id)); + + return getDataColumn(context, contentUri, null, null); + } + // MediaProvider + else if (isMediaDocument(uri)) { + final String docId = DocumentsContract.getDocumentId(uri); + final String[] split = docId.split(":"); + final String type = split[0]; + + Uri contentUri = null; + if ("image".equals(type)) { + contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; + } else if ("video".equals(type)) { + contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; + } else if ("audio".equals(type)) { + contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; + } + + final String selection = "_id=?"; + final String[] selectionArgs = new String[] { + split[1] + }; + + return getDataColumn(context, contentUri, selection, selectionArgs); + } + } + // MediaStore (and general) + else if ("content".equalsIgnoreCase(uri.getScheme())) { + + // Return the remote address + if (isGooglePhotosUri(uri)) + return uri.getLastPathSegment(); + + return getDataColumn(context, uri, null, null); + } + // File + else if ("file".equalsIgnoreCase(uri.getScheme())) { + return uri.getPath(); + } + + return null; + } + + public static String getRealPathFromURI_BelowAPI11(Context context, Uri contentUri) { + String[] proj = { MediaStore.Images.Media.DATA }; + String result = null; + + try { + Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null); + int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); + cursor.moveToFirst(); + result = cursor.getString(column_index); + + } catch (Exception e) { + result = null; + } + return result; + } + + /** + * Returns an input stream based on given URI string. + * + * @param uriString the URI string from which to obtain the input stream + * @param cordova the current application context + * @return an input stream into the data at the given URI or null if given an invalid URI string + * @throws IOException + */ + public static InputStream getInputStreamFromUriString(String uriString, CordovaInterface cordova) + throws IOException { + InputStream returnValue = null; + if (uriString.startsWith("content")) { + Uri uri = Uri.parse(uriString); + returnValue = cordova.getActivity().getContentResolver().openInputStream(uri); + } else if (uriString.startsWith("file://")) { + int question = uriString.indexOf("?"); + if (question > -1) { + uriString = uriString.substring(0, question); + } + if (uriString.startsWith("file:///android_asset/")) { + Uri uri = Uri.parse(uriString); + String relativePath = uri.getPath().substring(15); + returnValue = cordova.getActivity().getAssets().open(relativePath); + } else { + // might still be content so try that first + try { + returnValue = cordova.getActivity().getContentResolver().openInputStream(Uri.parse(uriString)); + } catch (Exception e) { + returnValue = null; + } + if (returnValue == null) { + returnValue = new FileInputStream(getRealPath(uriString, cordova)); + } + } + } else { + returnValue = new FileInputStream(uriString); + } + return returnValue; + } + + /** + * Removes the "file://" prefix from the given URI string, if applicable. + * If the given URI string doesn't have a "file://" prefix, it is returned unchanged. + * + * @param uriString the URI string to operate on + * @return a path without the "file://" prefix + */ + public static String stripFileProtocol(String uriString) { + if (uriString.startsWith("file://")) { + uriString = uriString.substring(7); + } + return uriString; + } + + public static String getMimeTypeForExtension(String path) { + String extension = path; + int lastDot = extension.lastIndexOf('.'); + if (lastDot != -1) { + extension = extension.substring(lastDot + 1); + } + // Convert the URI string to lower case to ensure compatibility with MimeTypeMap (see CB-2185). + extension = extension.toLowerCase(Locale.getDefault()); + if (extension.equals("3ga")) { + return "audio/3gpp"; + } + return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); + } + + /** + * Returns the mime type of the data specified by the given URI string. + * + * @param uriString the URI string of the data + * @return the mime type of the specified data + */ + public static String getMimeType(String uriString, CordovaInterface cordova) { + String mimeType = null; + + Uri uri = Uri.parse(uriString); + if (uriString.startsWith("content://")) { + mimeType = cordova.getActivity().getContentResolver().getType(uri); + } else { + mimeType = getMimeTypeForExtension(uri.getPath()); + } + + return mimeType; + } + + /** + * Get the value of the data column for this Uri. This is useful for + * MediaStore Uris, and other file-based ContentProviders. + * + * @param context The context. + * @param uri The Uri to query. + * @param selection (Optional) Filter used in the query. + * @param selectionArgs (Optional) Selection arguments used in the query. + * @return The value of the _data column, which is typically a file path. + * @author paulburke + */ + public static String getDataColumn(Context context, Uri uri, String selection, + String[] selectionArgs) { + + Cursor cursor = null; + final String column = "_data"; + final String[] projection = { + column + }; + + try { + cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, + null); + if (cursor != null && cursor.moveToFirst()) { + + final int column_index = cursor.getColumnIndexOrThrow(column); + return cursor.getString(column_index); + } + } catch (Exception e) { + return null; + } finally { + if (cursor != null) + cursor.close(); + } + return null; + } + + /** + * @param uri The Uri to check. + * @return Whether the Uri authority is ExternalStorageProvider. + * @author paulburke + */ + public static boolean isExternalStorageDocument(Uri uri) { + return "com.android.externalstorage.documents".equals(uri.getAuthority()); + } + + /** + * @param uri The Uri to check. + * @return Whether the Uri authority is DownloadsProvider. + * @author paulburke + */ + public static boolean isDownloadsDocument(Uri uri) { + return "com.android.providers.downloads.documents".equals(uri.getAuthority()); + } + + /** + * @param uri The Uri to check. + * @return Whether the Uri authority is MediaProvider. + * @author paulburke + */ + public static boolean isMediaDocument(Uri uri) { + return "com.android.providers.media.documents".equals(uri.getAuthority()); + } + + /** + * @param uri The Uri to check. + * @return Whether the Uri authority is Google Photos. + */ + public static boolean isGooglePhotosUri(Uri uri) { + return "com.google.android.apps.photos.content".equals(uri.getAuthority()); + } +} diff --git a/plugins/cordova-plugin-camera/src/android/xml/provider_paths.xml b/plugins/cordova-plugin-camera/src/android/xml/provider_paths.xml new file mode 100644 index 0000000..2db87bd --- /dev/null +++ b/plugins/cordova-plugin-camera/src/android/xml/provider_paths.xml @@ -0,0 +1,21 @@ + + + + + + \ No newline at end of file diff --git a/plugins/cordova-plugin-camera/src/blackberry10/index.js b/plugins/cordova-plugin-camera/src/blackberry10/index.js new file mode 100644 index 0000000..afc3539 --- /dev/null +++ b/plugins/cordova-plugin-camera/src/blackberry10/index.js @@ -0,0 +1,227 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ + +/* globals qnx, FileError, PluginResult */ + +var PictureSourceType = { + PHOTOLIBRARY : 0, // Choose image from picture library (same as SAVEDPHOTOALBUM for Android) + CAMERA : 1, // Take picture from camera + SAVEDPHOTOALBUM : 2 // Choose image from picture library (same as PHOTOLIBRARY for Android) + }, + DestinationType = { + DATA_URL: 0, // Return base64 encoded string + FILE_URI: 1, // Return file uri (content://media/external/images/media/2 for Android) + NATIVE_URI: 2 // Return native uri (eg. asset-library://... for iOS) + }, + savePath = window.qnx.webplatform.getApplication().getEnv("HOME").replace('/data', '') + '/shared/camera/', + invokeAvailable = true; + +//check for camera card - it isn't currently availble in work perimeter +window.qnx.webplatform.getApplication().invocation.queryTargets( + { + type: 'image/jpeg', + action: 'bb.action.CAPTURE', + target_type: 'CARD' + }, + function (error, targets) { + invokeAvailable = !error && targets && targets instanceof Array && + targets.filter(function (t) { return t.default === 'sys.camera.card'; }).length > 0; + } +); + +//open a webview with getUserMedia camera card implementation when camera card not available +function showCameraDialog (done, cancel, fail) { + var wv = qnx.webplatform.createWebView(function () { + wv.url = 'local:///chrome/camera.html'; + wv.allowQnxObject = true; + wv.allowRpc = true; + wv.zOrder = 1; + wv.setGeometry(0, 0, screen.width, screen.height); + wv.backgroundColor = 0x00000000; + wv.active = true; + wv.visible = true; + wv.on('UserMediaRequest', function (evt, args) { + wv.allowUserMedia(JSON.parse(args).id, 'CAMERA_UNIT_REAR'); + }); + wv.on('JavaScriptCallback', function (evt, data) { + var args = JSON.parse(data).args; + if (args[0] === 'cordova-plugin-camera') { + if (args[1] === 'cancel') { + cancel('User canceled'); + } else if (args[1] === 'error') { + fail(args[2]); + } else { + saveImage(args[1], done, fail); + } + wv.un('JavaScriptCallback', arguments.callee); + wv.visible = false; + wv.destroy(); + qnx.webplatform.getApplication().unlockRotation(); + } + }); + wv.on('Destroyed', function () { + wv.delete(); + }); + qnx.webplatform.getApplication().lockRotation(); + qnx.webplatform.getController().dispatchEvent('webview.initialized', [wv]); + }); +} + +//create unique name for saved file (same pattern as BB10 camera app) +function imgName() { + var date = new Date(), + pad = function (n) { return n < 10 ? '0' + n : n; }; + return 'IMG_' + date.getFullYear() + pad(date.getMonth() + 1) + pad(date.getDate()) + '_' + + pad(date.getHours()) + pad(date.getMinutes()) + pad(date.getSeconds()) + '.png'; +} + +//convert dataURI to Blob +function dataURItoBlob(dataURI) { + var byteString = atob(dataURI.split(',')[1]), + mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0], + arrayBuffer = new ArrayBuffer(byteString.length), + ia = new Uint8Array(arrayBuffer), + i; + for (i = 0; i < byteString.length; i++) { + ia[i] = byteString.charCodeAt(i); + } + return new Blob([new DataView(arrayBuffer)], { type: mimeString }); +} + +//save dataURI to file system and call success with path +function saveImage(data, success, fail) { + var name = savePath + imgName(); + require('lib/webview').setSandbox(false); + window.webkitRequestFileSystem(window.PERSISTENT, 0, function (fs) { + fs.root.getFile(name, { create: true }, function (entry) { + entry.createWriter(function (writer) { + writer.onwriteend = function () { + success(name); + }; + writer.onerror = fail; + writer.write(dataURItoBlob(data)); + }); + }, fail); + }, fail); +} + +function encodeBase64(filePath, callback) { + var sandbox = window.qnx.webplatform.getController().setFileSystemSandbox, // save original sandbox value + errorHandler = function (err) { + var msg = "An error occured: "; + + switch (err.code) { + case FileError.NOT_FOUND_ERR: + msg += "File or directory not found"; + break; + + case FileError.NOT_READABLE_ERR: + msg += "File or directory not readable"; + break; + + case FileError.PATH_EXISTS_ERR: + msg += "File or directory already exists"; + break; + + case FileError.TYPE_MISMATCH_ERR: + msg += "Invalid file type"; + break; + + default: + msg += "Unknown Error"; + break; + } + + // set it back to original value + window.qnx.webplatform.getController().setFileSystemSandbox = sandbox; + callback(msg); + }, + gotFile = function (fileEntry) { + fileEntry.file(function (file) { + var reader = new FileReader(); + + reader.onloadend = function (e) { + // set it back to original value + window.qnx.webplatform.getController().setFileSystemSandbox = sandbox; + callback(this.result); + }; + + reader.readAsDataURL(file); + }, errorHandler); + }, + onInitFs = function (fs) { + window.qnx.webplatform.getController().setFileSystemSandbox = false; + fs.root.getFile(filePath, {create: false}, gotFile, errorHandler); + }; + + window.webkitRequestFileSystem(window.TEMPORARY, 10 * 1024 * 1024, onInitFs, errorHandler); // set size to 10MB max +} + +module.exports = { + takePicture: function (success, fail, args, env) { + var destinationType = JSON.parse(decodeURIComponent(args[1])), + sourceType = JSON.parse(decodeURIComponent(args[2])), + result = new PluginResult(args, env), + done = function (data) { + if (destinationType === DestinationType.FILE_URI) { + data = "file://" + data; + result.callbackOk(data, false); + } else { + encodeBase64(data, function (data) { + if (/^data:/.test(data)) { + data = data.slice(data.indexOf(",") + 1); + result.callbackOk(data, false); + } else { + result.callbackError(data, false); + } + }); + } + }, + cancel = function (reason) { + result.callbackError(reason, false); + }, + invoked = function (error) { + if (error) { + result.callbackError(error, false); + } + }; + + switch(sourceType) { + case PictureSourceType.CAMERA: + if (invokeAvailable) { + window.qnx.webplatform.getApplication().cards.camera.open("photo", done, cancel, invoked); + } else { + showCameraDialog(done, cancel, fail); + } + break; + + case PictureSourceType.PHOTOLIBRARY: + case PictureSourceType.SAVEDPHOTOALBUM: + window.qnx.webplatform.getApplication().cards.filePicker.open({ + mode: "Picker", + type: ["picture"] + }, done, cancel, invoked); + break; + } + + result.noResult(true); + } +}; diff --git a/plugins/cordova-plugin-camera/src/browser/CameraProxy.js b/plugins/cordova-plugin-camera/src/browser/CameraProxy.js new file mode 100644 index 0000000..635a9fb --- /dev/null +++ b/plugins/cordova-plugin-camera/src/browser/CameraProxy.js @@ -0,0 +1,123 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +var HIGHEST_POSSIBLE_Z_INDEX = 2147483647; + +function takePicture(success, error, opts) { + if (opts && opts[2] === 1) { + capture(success, error, opts); + } else { + var input = document.createElement('input'); + input.style.position = 'relative'; + input.style.zIndex = HIGHEST_POSSIBLE_Z_INDEX; + input.className = 'cordova-camera-select'; + input.type = 'file'; + input.name = 'files[]'; + + input.onchange = function(inputEvent) { + var reader = new FileReader(); + reader.onload = function(readerEvent) { + input.parentNode.removeChild(input); + + var imageData = readerEvent.target.result; + + return success(imageData.substr(imageData.indexOf(',') + 1)); + }; + + reader.readAsDataURL(inputEvent.target.files[0]); + }; + + document.body.appendChild(input); + } +} + +function capture(success, errorCallback, opts) { + var localMediaStream; + var targetWidth = opts[3]; + var targetHeight = opts[4]; + + targetWidth = targetWidth == -1?320:targetWidth; + targetHeight = targetHeight == -1?240:targetHeight; + + var video = document.createElement('video'); + var button = document.createElement('button'); + var parent = document.createElement('div'); + parent.style.position = 'relative'; + parent.style.zIndex = HIGHEST_POSSIBLE_Z_INDEX; + parent.className = 'cordova-camera-capture'; + parent.appendChild(video); + parent.appendChild(button); + + video.width = targetWidth; + video.height = targetHeight; + button.innerHTML = 'Capture!'; + + button.onclick = function() { + // create a canvas and capture a frame from video stream + var canvas = document.createElement('canvas'); + canvas.width = targetWidth; + canvas.height = targetHeight; + canvas.getContext('2d').drawImage(video, 0, 0, targetWidth, targetHeight); + + // convert image stored in canvas to base64 encoded image + var imageData = canvas.toDataURL('image/png'); + imageData = imageData.replace('data:image/png;base64,', ''); + + // stop video stream, remove video and button. + // Note that MediaStream.stop() is deprecated as of Chrome 47. + if (localMediaStream.stop) { + localMediaStream.stop(); + } else { + localMediaStream.getTracks().forEach(function (track) { + track.stop(); + }); + } + parent.parentNode.removeChild(parent); + + return success(imageData); + }; + + navigator.getUserMedia = navigator.getUserMedia || + navigator.webkitGetUserMedia || + navigator.mozGetUserMedia || + navigator.msGetUserMedia; + + var successCallback = function(stream) { + localMediaStream = stream; + video.src = window.URL.createObjectURL(localMediaStream); + video.play(); + + document.body.appendChild(parent); + }; + + if (navigator.getUserMedia) { + navigator.getUserMedia({video: true, audio: true}, successCallback, errorCallback); + } else { + alert('Browser does not support camera :('); + } +} + +module.exports = { + takePicture: takePicture, + cleanup: function(){} +}; + +require("cordova/exec/proxy").add("Camera",module.exports); diff --git a/plugins/cordova-plugin-camera/src/firefoxos/CameraProxy.js b/plugins/cordova-plugin-camera/src/firefoxos/CameraProxy.js new file mode 100644 index 0000000..1e3018e --- /dev/null +++ b/plugins/cordova-plugin-camera/src/firefoxos/CameraProxy.js @@ -0,0 +1,53 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +/* globals MozActivity */ + +function takePicture(success, error, opts) { + var pick = new MozActivity({ + name: "pick", + data: { + type: ["image/*"] + } + }); + + pick.onerror = error || function() {}; + + pick.onsuccess = function() { + // image is returned as Blob in this.result.blob + // we need to call success with url or base64 encoded image + if (opts && opts.destinationType === 0) { + // TODO: base64 + return; + } + if (!opts || !opts.destinationType || opts.destinationType > 0) { + // url + return success(window.URL.createObjectURL(this.result.blob)); + } + }; +} + +module.exports = { + takePicture: takePicture, + cleanup: function(){} +}; + +require("cordova/exec/proxy").add("Camera", module.exports); diff --git a/plugins/cordova-plugin-camera/src/ios/CDVCamera.h b/plugins/cordova-plugin-camera/src/ios/CDVCamera.h new file mode 100644 index 0000000..f64f66c --- /dev/null +++ b/plugins/cordova-plugin-camera/src/ios/CDVCamera.h @@ -0,0 +1,116 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. + */ + +#import +#import +#import +#import + +enum CDVDestinationType { + DestinationTypeDataUrl = 0, + DestinationTypeFileUri, + DestinationTypeNativeUri +}; +typedef NSUInteger CDVDestinationType; + +enum CDVEncodingType { + EncodingTypeJPEG = 0, + EncodingTypePNG +}; +typedef NSUInteger CDVEncodingType; + +enum CDVMediaType { + MediaTypePicture = 0, + MediaTypeVideo, + MediaTypeAll +}; +typedef NSUInteger CDVMediaType; + +@interface CDVPictureOptions : NSObject + +@property (strong) NSNumber* quality; +@property (assign) CDVDestinationType destinationType; +@property (assign) UIImagePickerControllerSourceType sourceType; +@property (assign) CGSize targetSize; +@property (assign) CDVEncodingType encodingType; +@property (assign) CDVMediaType mediaType; +@property (assign) BOOL allowsEditing; +@property (assign) BOOL correctOrientation; +@property (assign) BOOL saveToPhotoAlbum; +@property (strong) NSDictionary* popoverOptions; +@property (assign) UIImagePickerControllerCameraDevice cameraDirection; + +@property (assign) BOOL popoverSupported; +@property (assign) BOOL usesGeolocation; +@property (assign) BOOL cropToSize; + ++ (instancetype) createFromTakePictureArguments:(CDVInvokedUrlCommand*)command; + +@end + +@interface CDVCameraPicker : UIImagePickerController + +@property (strong) CDVPictureOptions* pictureOptions; + +@property (copy) NSString* callbackId; +@property (copy) NSString* postUrl; +@property (strong) UIPopoverController* pickerPopoverController; +@property (assign) BOOL cropToSize; +@property (strong) UIView* webView; + ++ (instancetype) createFromPictureOptions:(CDVPictureOptions*)options; + +@end + +// ======================================================================= // + +@interface CDVCamera : CDVPlugin +{} + +@property (strong) CDVCameraPicker* pickerController; +@property (strong) NSMutableDictionary *metadata; +@property (strong, nonatomic) CLLocationManager *locationManager; +@property (strong) NSData* data; + +/* + * getPicture + * + * arguments: + * 1: this is the javascript function that will be called with the results, the first parameter passed to the + * javascript function is the picture as a Base64 encoded string + * 2: this is the javascript function to be called if there was an error + * options: + * quality: integer between 1 and 100 + */ +- (void)takePicture:(CDVInvokedUrlCommand*)command; +- (void)cleanup:(CDVInvokedUrlCommand*)command; +- (void)repositionPopover:(CDVInvokedUrlCommand*)command; + +- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary*)info; +- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingImage:(UIImage*)image editingInfo:(NSDictionary*)editingInfo; +- (void)imagePickerControllerDidCancel:(UIImagePickerController*)picker; +- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated; + +- (void)locationManager:(CLLocationManager*)manager didUpdateToLocation:(CLLocation*)newLocation fromLocation:(CLLocation*)oldLocation; +- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error; + +@end diff --git a/plugins/cordova-plugin-camera/src/ios/CDVCamera.m b/plugins/cordova-plugin-camera/src/ios/CDVCamera.m new file mode 100644 index 0000000..019141b --- /dev/null +++ b/plugins/cordova-plugin-camera/src/ios/CDVCamera.m @@ -0,0 +1,771 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. + */ + +#import "CDVCamera.h" +#import "CDVJpegHeaderWriter.h" +#import "UIImage+CropScaleOrientation.h" +#import +#import +#import +#import +#import +#import +#import +#import +#import + +#ifndef __CORDOVA_4_0_0 + #import +#endif + +#define CDV_PHOTO_PREFIX @"cdv_photo_" + +static NSSet* org_apache_cordova_validArrowDirections; + +static NSString* toBase64(NSData* data) { + SEL s1 = NSSelectorFromString(@"cdv_base64EncodedString"); + SEL s2 = NSSelectorFromString(@"base64EncodedString"); + SEL s3 = NSSelectorFromString(@"base64EncodedStringWithOptions:"); + + if ([data respondsToSelector:s1]) { + NSString* (*func)(id, SEL) = (void *)[data methodForSelector:s1]; + return func(data, s1); + } else if ([data respondsToSelector:s2]) { + NSString* (*func)(id, SEL) = (void *)[data methodForSelector:s2]; + return func(data, s2); + } else if ([data respondsToSelector:s3]) { + NSString* (*func)(id, SEL, NSUInteger) = (void *)[data methodForSelector:s3]; + return func(data, s3, 0); + } else { + return nil; + } +} + +@implementation CDVPictureOptions + ++ (instancetype) createFromTakePictureArguments:(CDVInvokedUrlCommand*)command +{ + CDVPictureOptions* pictureOptions = [[CDVPictureOptions alloc] init]; + + pictureOptions.quality = [command argumentAtIndex:0 withDefault:@(50)]; + pictureOptions.destinationType = [[command argumentAtIndex:1 withDefault:@(DestinationTypeFileUri)] unsignedIntegerValue]; + pictureOptions.sourceType = [[command argumentAtIndex:2 withDefault:@(UIImagePickerControllerSourceTypeCamera)] unsignedIntegerValue]; + + NSNumber* targetWidth = [command argumentAtIndex:3 withDefault:nil]; + NSNumber* targetHeight = [command argumentAtIndex:4 withDefault:nil]; + pictureOptions.targetSize = CGSizeMake(0, 0); + if ((targetWidth != nil) && (targetHeight != nil)) { + pictureOptions.targetSize = CGSizeMake([targetWidth floatValue], [targetHeight floatValue]); + } + + pictureOptions.encodingType = [[command argumentAtIndex:5 withDefault:@(EncodingTypeJPEG)] unsignedIntegerValue]; + pictureOptions.mediaType = [[command argumentAtIndex:6 withDefault:@(MediaTypePicture)] unsignedIntegerValue]; + pictureOptions.allowsEditing = [[command argumentAtIndex:7 withDefault:@(NO)] boolValue]; + pictureOptions.correctOrientation = [[command argumentAtIndex:8 withDefault:@(NO)] boolValue]; + pictureOptions.saveToPhotoAlbum = [[command argumentAtIndex:9 withDefault:@(NO)] boolValue]; + pictureOptions.popoverOptions = [command argumentAtIndex:10 withDefault:nil]; + pictureOptions.cameraDirection = [[command argumentAtIndex:11 withDefault:@(UIImagePickerControllerCameraDeviceRear)] unsignedIntegerValue]; + + pictureOptions.popoverSupported = NO; + pictureOptions.usesGeolocation = NO; + + return pictureOptions; +} + +@end + + +@interface CDVCamera () + +@property (readwrite, assign) BOOL hasPendingOperation; + +@end + +@implementation CDVCamera + ++ (void)initialize +{ + org_apache_cordova_validArrowDirections = [[NSSet alloc] initWithObjects:[NSNumber numberWithInt:UIPopoverArrowDirectionUp], [NSNumber numberWithInt:UIPopoverArrowDirectionDown], [NSNumber numberWithInt:UIPopoverArrowDirectionLeft], [NSNumber numberWithInt:UIPopoverArrowDirectionRight], [NSNumber numberWithInt:UIPopoverArrowDirectionAny], nil]; +} + +@synthesize hasPendingOperation, pickerController, locationManager; + +- (NSURL*) urlTransformer:(NSURL*)url +{ + NSURL* urlToTransform = url; + + // for backwards compatibility - we check if this property is there + SEL sel = NSSelectorFromString(@"urlTransformer"); + if ([self.commandDelegate respondsToSelector:sel]) { + // grab the block from the commandDelegate + NSURL* (^urlTransformer)(NSURL*) = ((id(*)(id, SEL))objc_msgSend)(self.commandDelegate, sel); + // if block is not null, we call it + if (urlTransformer) { + urlToTransform = urlTransformer(url); + } + } + + return urlToTransform; +} + +- (BOOL)usesGeolocation +{ + id useGeo = [self.commandDelegate.settings objectForKey:[@"CameraUsesGeolocation" lowercaseString]]; + return [(NSNumber*)useGeo boolValue]; +} + +- (BOOL)popoverSupported +{ + return (NSClassFromString(@"UIPopoverController") != nil) && + (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad); +} + +- (void)takePicture:(CDVInvokedUrlCommand*)command +{ + self.hasPendingOperation = YES; + + __weak CDVCamera* weakSelf = self; + + [self.commandDelegate runInBackground:^{ + + CDVPictureOptions* pictureOptions = [CDVPictureOptions createFromTakePictureArguments:command]; + pictureOptions.popoverSupported = [weakSelf popoverSupported]; + pictureOptions.usesGeolocation = [weakSelf usesGeolocation]; + pictureOptions.cropToSize = NO; + + BOOL hasCamera = [UIImagePickerController isSourceTypeAvailable:pictureOptions.sourceType]; + if (!hasCamera) { + NSLog(@"Camera.getPicture: source type %lu not available.", (unsigned long)pictureOptions.sourceType); + CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"No camera available"]; + [weakSelf.commandDelegate sendPluginResult:result callbackId:command.callbackId]; + return; + } + + // Validate the app has permission to access the camera + if (pictureOptions.sourceType == UIImagePickerControllerSourceTypeCamera && [AVCaptureDevice respondsToSelector:@selector(authorizationStatusForMediaType:)]) { + AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo]; + if (authStatus == AVAuthorizationStatusDenied || + authStatus == AVAuthorizationStatusRestricted) { + // If iOS 8+, offer a link to the Settings app +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wtautological-pointer-compare" + NSString* settingsButton = (&UIApplicationOpenSettingsURLString != NULL) + ? NSLocalizedString(@"Settings", nil) + : nil; +#pragma clang diagnostic pop + + // Denied; show an alert + dispatch_async(dispatch_get_main_queue(), ^{ + [[[UIAlertView alloc] initWithTitle:[[NSBundle mainBundle] + objectForInfoDictionaryKey:@"CFBundleDisplayName"] + message:NSLocalizedString(@"Access to the camera has been prohibited; please enable it in the Settings app to continue.", nil) + delegate:weakSelf + cancelButtonTitle:NSLocalizedString(@"OK", nil) + otherButtonTitles:settingsButton, nil] show]; + }); + } + } + + CDVCameraPicker* cameraPicker = [CDVCameraPicker createFromPictureOptions:pictureOptions]; + weakSelf.pickerController = cameraPicker; + + cameraPicker.delegate = weakSelf; + cameraPicker.callbackId = command.callbackId; + // we need to capture this state for memory warnings that dealloc this object + cameraPicker.webView = weakSelf.webView; + + // Perform UI operations on the main thread + dispatch_async(dispatch_get_main_queue(), ^{ + // If a popover is already open, close it; we only want one at a time. + if (([[weakSelf pickerController] pickerPopoverController] != nil) && [[[weakSelf pickerController] pickerPopoverController] isPopoverVisible]) { + [[[weakSelf pickerController] pickerPopoverController] dismissPopoverAnimated:YES]; + [[[weakSelf pickerController] pickerPopoverController] setDelegate:nil]; + [[weakSelf pickerController] setPickerPopoverController:nil]; + } + + if ([weakSelf popoverSupported] && (pictureOptions.sourceType != UIImagePickerControllerSourceTypeCamera)) { + if (cameraPicker.pickerPopoverController == nil) { + cameraPicker.pickerPopoverController = [[NSClassFromString(@"UIPopoverController") alloc] initWithContentViewController:cameraPicker]; + } + [weakSelf displayPopover:pictureOptions.popoverOptions]; + weakSelf.hasPendingOperation = NO; + } else { + [weakSelf.viewController presentViewController:cameraPicker animated:YES completion:^{ + weakSelf.hasPendingOperation = NO; + }]; + } + }); + }]; +} + +// Delegate for camera permission UIAlertView +- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex +{ + // If Settings button (on iOS 8), open the settings app + if (buttonIndex == 1) { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wtautological-pointer-compare" + if (&UIApplicationOpenSettingsURLString != NULL) { + [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]]; + } +#pragma clang diagnostic pop + } + + // Dismiss the view + [[self.pickerController presentingViewController] dismissViewControllerAnimated:YES completion:nil]; + + CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"has no access to camera"]; // error callback expects string ATM + + [self.commandDelegate sendPluginResult:result callbackId:self.pickerController.callbackId]; + + self.hasPendingOperation = NO; + self.pickerController = nil; +} + +- (void)repositionPopover:(CDVInvokedUrlCommand*)command +{ + if (([[self pickerController] pickerPopoverController] != nil) && [[[self pickerController] pickerPopoverController] isPopoverVisible]) { + + [[[self pickerController] pickerPopoverController] dismissPopoverAnimated:NO]; + + NSDictionary* options = [command argumentAtIndex:0 withDefault:nil]; + [self displayPopover:options]; + } +} + +- (NSInteger)integerValueForKey:(NSDictionary*)dict key:(NSString*)key defaultValue:(NSInteger)defaultValue +{ + NSInteger value = defaultValue; + + NSNumber* val = [dict valueForKey:key]; // value is an NSNumber + + if (val != nil) { + value = [val integerValue]; + } + return value; +} + +- (void)displayPopover:(NSDictionary*)options +{ + NSInteger x = 0; + NSInteger y = 32; + NSInteger width = 320; + NSInteger height = 480; + UIPopoverArrowDirection arrowDirection = UIPopoverArrowDirectionAny; + + if (options) { + x = [self integerValueForKey:options key:@"x" defaultValue:0]; + y = [self integerValueForKey:options key:@"y" defaultValue:32]; + width = [self integerValueForKey:options key:@"width" defaultValue:320]; + height = [self integerValueForKey:options key:@"height" defaultValue:480]; + arrowDirection = [self integerValueForKey:options key:@"arrowDir" defaultValue:UIPopoverArrowDirectionAny]; + if (![org_apache_cordova_validArrowDirections containsObject:[NSNumber numberWithUnsignedInteger:arrowDirection]]) { + arrowDirection = UIPopoverArrowDirectionAny; + } + } + + [[[self pickerController] pickerPopoverController] setDelegate:self]; + [[[self pickerController] pickerPopoverController] presentPopoverFromRect:CGRectMake(x, y, width, height) + inView:[self.webView superview] + permittedArrowDirections:arrowDirection + animated:YES]; +} + +- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated +{ + if([navigationController isKindOfClass:[UIImagePickerController class]]){ + UIImagePickerController* cameraPicker = (UIImagePickerController*)navigationController; + + if(![cameraPicker.mediaTypes containsObject:(NSString*)kUTTypeImage]){ + [viewController.navigationItem setTitle:NSLocalizedString(@"Videos", nil)]; + } + } +} + +- (void)cleanup:(CDVInvokedUrlCommand*)command +{ + // empty the tmp directory + NSFileManager* fileMgr = [[NSFileManager alloc] init]; + NSError* err = nil; + BOOL hasErrors = NO; + + // clear contents of NSTemporaryDirectory + NSString* tempDirectoryPath = NSTemporaryDirectory(); + NSDirectoryEnumerator* directoryEnumerator = [fileMgr enumeratorAtPath:tempDirectoryPath]; + NSString* fileName = nil; + BOOL result; + + while ((fileName = [directoryEnumerator nextObject])) { + // only delete the files we created + if (![fileName hasPrefix:CDV_PHOTO_PREFIX]) { + continue; + } + NSString* filePath = [tempDirectoryPath stringByAppendingPathComponent:fileName]; + result = [fileMgr removeItemAtPath:filePath error:&err]; + if (!result && err) { + NSLog(@"Failed to delete: %@ (error: %@)", filePath, err); + hasErrors = YES; + } + } + + CDVPluginResult* pluginResult; + if (hasErrors) { + pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsString:@"One or more files failed to be deleted."]; + } else { + pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; + } + [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; +} + +- (void)popoverControllerDidDismissPopover:(id)popoverController +{ + UIPopoverController* pc = (UIPopoverController*)popoverController; + + [pc dismissPopoverAnimated:YES]; + pc.delegate = nil; + if (self.pickerController && self.pickerController.callbackId && self.pickerController.pickerPopoverController) { + self.pickerController.pickerPopoverController = nil; + NSString* callbackId = self.pickerController.callbackId; + CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"no image selected"]; // error callback expects string ATM + [self.commandDelegate sendPluginResult:result callbackId:callbackId]; + } + self.hasPendingOperation = NO; +} + +- (NSData*)processImage:(UIImage*)image info:(NSDictionary*)info options:(CDVPictureOptions*)options +{ + NSData* data = nil; + + switch (options.encodingType) { + case EncodingTypePNG: + data = UIImagePNGRepresentation(image); + break; + case EncodingTypeJPEG: + { + if ((options.allowsEditing == NO) && (options.targetSize.width <= 0) && (options.targetSize.height <= 0) && (options.correctOrientation == NO) && (([options.quality integerValue] == 100) || (options.sourceType != UIImagePickerControllerSourceTypeCamera))){ + // use image unedited as requested , don't resize + data = UIImageJPEGRepresentation(image, 1.0); + } else { + data = UIImageJPEGRepresentation(image, [options.quality floatValue] / 100.0f); + } + + if (options.usesGeolocation) { + NSDictionary* controllerMetadata = [info objectForKey:@"UIImagePickerControllerMediaMetadata"]; + if (controllerMetadata) { + self.data = data; + self.metadata = [[NSMutableDictionary alloc] init]; + + NSMutableDictionary* EXIFDictionary = [[controllerMetadata objectForKey:(NSString*)kCGImagePropertyExifDictionary]mutableCopy]; + if (EXIFDictionary) { + [self.metadata setObject:EXIFDictionary forKey:(NSString*)kCGImagePropertyExifDictionary]; + } + + if (IsAtLeastiOSVersion(@"8.0")) { + [[self locationManager] performSelector:NSSelectorFromString(@"requestWhenInUseAuthorization") withObject:nil afterDelay:0]; + } + [[self locationManager] startUpdatingLocation]; + } + } + } + break; + default: + break; + }; + + return data; +} + +- (NSString*)tempFilePath:(NSString*)extension +{ + NSString* docsPath = [NSTemporaryDirectory()stringByStandardizingPath]; + NSFileManager* fileMgr = [[NSFileManager alloc] init]; // recommended by Apple (vs [NSFileManager defaultManager]) to be threadsafe + NSString* filePath; + + // generate unique file name + int i = 1; + do { + filePath = [NSString stringWithFormat:@"%@/%@%03d.%@", docsPath, CDV_PHOTO_PREFIX, i++, extension]; + } while ([fileMgr fileExistsAtPath:filePath]); + + return filePath; +} + +- (UIImage*)retrieveImage:(NSDictionary*)info options:(CDVPictureOptions*)options +{ + // get the image + UIImage* image = nil; + if (options.allowsEditing && [info objectForKey:UIImagePickerControllerEditedImage]) { + image = [info objectForKey:UIImagePickerControllerEditedImage]; + } else { + image = [info objectForKey:UIImagePickerControllerOriginalImage]; + } + + if (options.correctOrientation) { + image = [image imageCorrectedForCaptureOrientation]; + } + + UIImage* scaledImage = nil; + + if ((options.targetSize.width > 0) && (options.targetSize.height > 0)) { + // if cropToSize, resize image and crop to target size, otherwise resize to fit target without cropping + if (options.cropToSize) { + scaledImage = [image imageByScalingAndCroppingForSize:options.targetSize]; + } else { + scaledImage = [image imageByScalingNotCroppingForSize:options.targetSize]; + } + } + + return (scaledImage == nil ? image : scaledImage); +} + +- (void)resultForImage:(CDVPictureOptions*)options info:(NSDictionary*)info completion:(void (^)(CDVPluginResult* res))completion +{ + CDVPluginResult* result = nil; + BOOL saveToPhotoAlbum = options.saveToPhotoAlbum; + UIImage* image = nil; + + switch (options.destinationType) { + case DestinationTypeNativeUri: + { + NSURL* url = [info objectForKey:UIImagePickerControllerReferenceURL]; + saveToPhotoAlbum = NO; + // If, for example, we use sourceType = Camera, URL might be nil because image is stored in memory. + // In this case we must save image to device before obtaining an URI. + if (url == nil) { + image = [self retrieveImage:info options:options]; + ALAssetsLibrary* library = [ALAssetsLibrary new]; + [library writeImageToSavedPhotosAlbum:image.CGImage orientation:(ALAssetOrientation)(image.imageOrientation) completionBlock:^(NSURL *assetURL, NSError *error) { + CDVPluginResult* resultToReturn = nil; + if (error) { + resultToReturn = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsString:[error localizedDescription]]; + } else { + NSString* nativeUri = [[self urlTransformer:assetURL] absoluteString]; + resultToReturn = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:nativeUri]; + } + completion(resultToReturn); + }]; + return; + } else { + NSString* nativeUri = [[self urlTransformer:url] absoluteString]; + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:nativeUri]; + } + } + break; + case DestinationTypeFileUri: + { + image = [self retrieveImage:info options:options]; + NSData* data = [self processImage:image info:info options:options]; + if (data) { + + NSString* extension = options.encodingType == EncodingTypePNG? @"png" : @"jpg"; + NSString* filePath = [self tempFilePath:extension]; + NSError* err = nil; + + // save file + if (![data writeToFile:filePath options:NSAtomicWrite error:&err]) { + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsString:[err localizedDescription]]; + } else { + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:[[self urlTransformer:[NSURL fileURLWithPath:filePath]] absoluteString]]; + } + } + } + break; + case DestinationTypeDataUrl: + { + image = [self retrieveImage:info options:options]; + NSData* data = [self processImage:image info:info options:options]; + if (data) { + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:toBase64(data)]; + } + } + break; + default: + break; + }; + + if (saveToPhotoAlbum && image) { + ALAssetsLibrary* library = [ALAssetsLibrary new]; + [library writeImageToSavedPhotosAlbum:image.CGImage orientation:(ALAssetOrientation)(image.imageOrientation) completionBlock:nil]; + } + + completion(result); +} + +- (CDVPluginResult*)resultForVideo:(NSDictionary*)info +{ + NSString* moviePath = [[info objectForKey:UIImagePickerControllerMediaURL] absoluteString]; + return [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:moviePath]; +} + +- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary*)info +{ + __weak CDVCameraPicker* cameraPicker = (CDVCameraPicker*)picker; + __weak CDVCamera* weakSelf = self; + + dispatch_block_t invoke = ^(void) { + __block CDVPluginResult* result = nil; + + NSString* mediaType = [info objectForKey:UIImagePickerControllerMediaType]; + if ([mediaType isEqualToString:(NSString*)kUTTypeImage]) { + [weakSelf resultForImage:cameraPicker.pictureOptions info:info completion:^(CDVPluginResult* res) { + if (![self usesGeolocation] || picker.sourceType != UIImagePickerControllerSourceTypeCamera) { + [weakSelf.commandDelegate sendPluginResult:res callbackId:cameraPicker.callbackId]; + weakSelf.hasPendingOperation = NO; + weakSelf.pickerController = nil; + } + }]; + } + else { + result = [weakSelf resultForVideo:info]; + [weakSelf.commandDelegate sendPluginResult:result callbackId:cameraPicker.callbackId]; + weakSelf.hasPendingOperation = NO; + weakSelf.pickerController = nil; + } + }; + + if (cameraPicker.pictureOptions.popoverSupported && (cameraPicker.pickerPopoverController != nil)) { + [cameraPicker.pickerPopoverController dismissPopoverAnimated:YES]; + cameraPicker.pickerPopoverController.delegate = nil; + cameraPicker.pickerPopoverController = nil; + invoke(); + } else { + [[cameraPicker presentingViewController] dismissViewControllerAnimated:YES completion:invoke]; + } +} + +// older api calls newer didFinishPickingMediaWithInfo +- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingImage:(UIImage*)image editingInfo:(NSDictionary*)editingInfo +{ + NSDictionary* imageInfo = [NSDictionary dictionaryWithObject:image forKey:UIImagePickerControllerOriginalImage]; + + [self imagePickerController:picker didFinishPickingMediaWithInfo:imageInfo]; +} + +- (void)imagePickerControllerDidCancel:(UIImagePickerController*)picker +{ + __weak CDVCameraPicker* cameraPicker = (CDVCameraPicker*)picker; + __weak CDVCamera* weakSelf = self; + + dispatch_block_t invoke = ^ (void) { + CDVPluginResult* result; + if (picker.sourceType == UIImagePickerControllerSourceTypeCamera && [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo] != ALAuthorizationStatusAuthorized) { + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"has no access to camera"]; + } else if (picker.sourceType != UIImagePickerControllerSourceTypeCamera && [ALAssetsLibrary authorizationStatus] != ALAuthorizationStatusAuthorized) { + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"has no access to assets"]; + } else { + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"no image selected"]; + } + + + [weakSelf.commandDelegate sendPluginResult:result callbackId:cameraPicker.callbackId]; + + weakSelf.hasPendingOperation = NO; + weakSelf.pickerController = nil; + }; + + [[cameraPicker presentingViewController] dismissViewControllerAnimated:YES completion:invoke]; +} + +- (CLLocationManager*)locationManager +{ + if (locationManager != nil) { + return locationManager; + } + + locationManager = [[CLLocationManager alloc] init]; + [locationManager setDesiredAccuracy:kCLLocationAccuracyNearestTenMeters]; + [locationManager setDelegate:self]; + + return locationManager; +} + +- (void)locationManager:(CLLocationManager*)manager didUpdateToLocation:(CLLocation*)newLocation fromLocation:(CLLocation*)oldLocation +{ + if (locationManager == nil) { + return; + } + + [self.locationManager stopUpdatingLocation]; + self.locationManager = nil; + + NSMutableDictionary *GPSDictionary = [[NSMutableDictionary dictionary] init]; + + CLLocationDegrees latitude = newLocation.coordinate.latitude; + CLLocationDegrees longitude = newLocation.coordinate.longitude; + + // latitude + if (latitude < 0.0) { + latitude = latitude * -1.0f; + [GPSDictionary setObject:@"S" forKey:(NSString*)kCGImagePropertyGPSLatitudeRef]; + } else { + [GPSDictionary setObject:@"N" forKey:(NSString*)kCGImagePropertyGPSLatitudeRef]; + } + [GPSDictionary setObject:[NSNumber numberWithFloat:latitude] forKey:(NSString*)kCGImagePropertyGPSLatitude]; + + // longitude + if (longitude < 0.0) { + longitude = longitude * -1.0f; + [GPSDictionary setObject:@"W" forKey:(NSString*)kCGImagePropertyGPSLongitudeRef]; + } + else { + [GPSDictionary setObject:@"E" forKey:(NSString*)kCGImagePropertyGPSLongitudeRef]; + } + [GPSDictionary setObject:[NSNumber numberWithFloat:longitude] forKey:(NSString*)kCGImagePropertyGPSLongitude]; + + // altitude + CGFloat altitude = newLocation.altitude; + if (!isnan(altitude)){ + if (altitude < 0) { + altitude = -altitude; + [GPSDictionary setObject:@"1" forKey:(NSString *)kCGImagePropertyGPSAltitudeRef]; + } else { + [GPSDictionary setObject:@"0" forKey:(NSString *)kCGImagePropertyGPSAltitudeRef]; + } + [GPSDictionary setObject:[NSNumber numberWithFloat:altitude] forKey:(NSString *)kCGImagePropertyGPSAltitude]; + } + + // Time and date + NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; + [formatter setDateFormat:@"HH:mm:ss.SSSSSS"]; + [formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]]; + [GPSDictionary setObject:[formatter stringFromDate:newLocation.timestamp] forKey:(NSString *)kCGImagePropertyGPSTimeStamp]; + [formatter setDateFormat:@"yyyy:MM:dd"]; + [GPSDictionary setObject:[formatter stringFromDate:newLocation.timestamp] forKey:(NSString *)kCGImagePropertyGPSDateStamp]; + + [self.metadata setObject:GPSDictionary forKey:(NSString *)kCGImagePropertyGPSDictionary]; + [self imagePickerControllerReturnImageResult]; +} + +- (void)locationManager:(CLLocationManager*)manager didFailWithError:(NSError*)error +{ + if (locationManager == nil) { + return; + } + + [self.locationManager stopUpdatingLocation]; + self.locationManager = nil; + + [self imagePickerControllerReturnImageResult]; +} + +- (void)imagePickerControllerReturnImageResult +{ + CDVPictureOptions* options = self.pickerController.pictureOptions; + CDVPluginResult* result = nil; + + if (self.metadata) { + CGImageSourceRef sourceImage = CGImageSourceCreateWithData((__bridge CFDataRef)self.data, NULL); + CFStringRef sourceType = CGImageSourceGetType(sourceImage); + + CGImageDestinationRef destinationImage = CGImageDestinationCreateWithData((__bridge CFMutableDataRef)self.data, sourceType, 1, NULL); + CGImageDestinationAddImageFromSource(destinationImage, sourceImage, 0, (__bridge CFDictionaryRef)self.metadata); + CGImageDestinationFinalize(destinationImage); + + CFRelease(sourceImage); + CFRelease(destinationImage); + } + + switch (options.destinationType) { + case DestinationTypeFileUri: + { + NSError* err = nil; + NSString* extension = self.pickerController.pictureOptions.encodingType == EncodingTypePNG ? @"png":@"jpg"; + NSString* filePath = [self tempFilePath:extension]; + + // save file + if (![self.data writeToFile:filePath options:NSAtomicWrite error:&err]) { + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsString:[err localizedDescription]]; + } + else { + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:[[self urlTransformer:[NSURL fileURLWithPath:filePath]] absoluteString]]; + } + } + break; + case DestinationTypeDataUrl: + { + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:toBase64(self.data)]; + } + break; + case DestinationTypeNativeUri: + default: + break; + }; + + if (result) { + [self.commandDelegate sendPluginResult:result callbackId:self.pickerController.callbackId]; + } + + self.hasPendingOperation = NO; + self.pickerController = nil; + self.data = nil; + self.metadata = nil; + + if (options.saveToPhotoAlbum) { + ALAssetsLibrary *library = [ALAssetsLibrary new]; + [library writeImageDataToSavedPhotosAlbum:self.data metadata:self.metadata completionBlock:nil]; + } +} + +@end + +@implementation CDVCameraPicker + +- (BOOL)prefersStatusBarHidden +{ + return YES; +} + +- (UIViewController*)childViewControllerForStatusBarHidden +{ + return nil; +} + +- (void)viewWillAppear:(BOOL)animated +{ + SEL sel = NSSelectorFromString(@"setNeedsStatusBarAppearanceUpdate"); + if ([self respondsToSelector:sel]) { + [self performSelector:sel withObject:nil afterDelay:0]; + } + + [super viewWillAppear:animated]; +} + ++ (instancetype) createFromPictureOptions:(CDVPictureOptions*)pictureOptions; +{ + CDVCameraPicker* cameraPicker = [[CDVCameraPicker alloc] init]; + cameraPicker.pictureOptions = pictureOptions; + cameraPicker.sourceType = pictureOptions.sourceType; + cameraPicker.allowsEditing = pictureOptions.allowsEditing; + + if (cameraPicker.sourceType == UIImagePickerControllerSourceTypeCamera) { + // We only allow taking pictures (no video) in this API. + cameraPicker.mediaTypes = @[(NSString*)kUTTypeImage]; + // We can only set the camera device if we're actually using the camera. + cameraPicker.cameraDevice = pictureOptions.cameraDirection; + } else if (pictureOptions.mediaType == MediaTypeAll) { + cameraPicker.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:cameraPicker.sourceType]; + } else { + NSArray* mediaArray = @[(NSString*)(pictureOptions.mediaType == MediaTypeVideo ? kUTTypeMovie : kUTTypeImage)]; + cameraPicker.mediaTypes = mediaArray; + } + + return cameraPicker; +} + +@end \ No newline at end of file diff --git a/plugins/cordova-plugin-camera/src/ios/CDVExif.h b/plugins/cordova-plugin-camera/src/ios/CDVExif.h new file mode 100644 index 0000000..3e8adbd --- /dev/null +++ b/plugins/cordova-plugin-camera/src/ios/CDVExif.h @@ -0,0 +1,43 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. + */ + +#ifndef CordovaLib_ExifData_h +#define CordovaLib_ExifData_h + +// exif data types +typedef enum exifDataTypes { + EDT_UBYTE = 1, // 8 bit unsigned integer + EDT_ASCII_STRING, // 8 bits containing 7 bit ASCII code, null terminated + EDT_USHORT, // 16 bit unsigned integer + EDT_ULONG, // 32 bit unsigned integer + EDT_URATIONAL, // 2 longs, first is numerator and second is denominator + EDT_SBYTE, + EDT_UNDEFINED, // 8 bits + EDT_SSHORT, + EDT_SLONG, // 32bit signed integer (2's complement) + EDT_SRATIONAL, // 2 SLONGS, first long is numerator, second is denominator + EDT_SINGLEFLOAT, + EDT_DOUBLEFLOAT +} ExifDataTypes; + +// maps integer code for exif data types to width in bytes +static const int DataTypeToWidth[] = {1,1,2,4,8,1,1,2,4,8,4,8}; + +static const int RECURSE_HORIZON = 8; +#endif diff --git a/plugins/cordova-plugin-camera/src/ios/CDVJpegHeaderWriter.h b/plugins/cordova-plugin-camera/src/ios/CDVJpegHeaderWriter.h new file mode 100644 index 0000000..3b43ef0 --- /dev/null +++ b/plugins/cordova-plugin-camera/src/ios/CDVJpegHeaderWriter.h @@ -0,0 +1,62 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. + */ + +#import + +@interface CDVJpegHeaderWriter : NSObject { + NSDictionary * SubIFDTagFormatDict; + NSDictionary * IFD0TagFormatDict; +} + +- (NSData*) spliceExifBlockIntoJpeg: (NSData*) jpegdata + withExifBlock: (NSString*) exifstr; +- (NSString*) createExifAPP1 : (NSDictionary*) datadict; +- (NSString*) formattedHexStringFromDecimalNumber: (NSNumber*) numb + withPlaces: (NSNumber*) width; +- (NSString*) formatNumberWithLeadingZeroes: (NSNumber*) numb + withPlaces: (NSNumber*) places; +- (NSString*) decimalToUnsignedRational: (NSNumber*) numb + withResultNumerator: (NSNumber**) numerator + withResultDenominator: (NSNumber**) denominator; +- (void) continuedFraction: (double) val + withFractionList: (NSMutableArray*) fractionlist + withHorizon: (int) horizon; +//- (void) expandContinuedFraction: (NSArray*) fractionlist; +- (void) splitDouble: (double) val + withIntComponent: (int*) rightside + withFloatRemainder: (double*) leftside; +- (NSString*) formatRationalWithNumerator: (NSNumber*) numerator + withDenominator: (NSNumber*) denominator + asSigned: (Boolean) signedFlag; +- (NSString*) hexStringFromData : (NSData*) data; +- (NSNumber*) numericFromHexString : (NSString *) hexstring; + +/* +- (void) readExifMetaData : (NSData*) imgdata; +- (void) spliceImageData : (NSData*) imgdata withExifData: (NSDictionary*) exifdata; +- (void) locateExifMetaData : (NSData*) imgdata; +- (NSString*) createExifAPP1 : (NSDictionary*) datadict; +- (void) createExifDataString : (NSDictionary*) datadict; +- (NSString*) createDataElement : (NSString*) element + withElementData: (NSString*) data + withExternalDataBlock: (NSDictionary*) memblock; +- (NSString*) hexStringFromData : (NSData*) data; +- (NSNumber*) numericFromHexString : (NSString *) hexstring; +*/ +@end diff --git a/plugins/cordova-plugin-camera/src/ios/CDVJpegHeaderWriter.m b/plugins/cordova-plugin-camera/src/ios/CDVJpegHeaderWriter.m new file mode 100644 index 0000000..4d3ea24 --- /dev/null +++ b/plugins/cordova-plugin-camera/src/ios/CDVJpegHeaderWriter.m @@ -0,0 +1,547 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. + */ + +#import "CDVJpegHeaderWriter.h" +#include "CDVExif.h" + +/* macros for tag info shorthand: + tagno : tag number + typecode : data type + components : number of components + appendString (TAGINF_W_APPEND only) : string to append to data + Exif date data format include an extra 0x00 to the end of the data + */ +#define TAGINF(tagno, typecode, components) [NSArray arrayWithObjects: tagno, typecode, components, nil] +#define TAGINF_W_APPEND(tagno, typecode, components, appendString) [NSArray arrayWithObjects: tagno, typecode, components, appendString, nil] + +const uint mJpegId = 0xffd8; // JPEG format marker +const uint mExifMarker = 0xffe1; // APP1 jpeg header marker +const uint mExif = 0x45786966; // ASCII 'Exif', first characters of valid exif header after size +const uint mMotorallaByteAlign = 0x4d4d; // 'MM', motorola byte align, msb first or 'sane' +const uint mIntelByteAlgin = 0x4949; // 'II', Intel byte align, lsb first or 'batshit crazy reverso world' +const uint mTiffLength = 0x2a; // after byte align bits, next to bits are 0x002a(MM) or 0x2a00(II), tiff version number + + +@implementation CDVJpegHeaderWriter + +- (id) init { + self = [super init]; + // supported tags for exif IFD + IFD0TagFormatDict = [[NSDictionary alloc] initWithObjectsAndKeys: + // TAGINF(@"010e", [NSNumber numberWithInt:EDT_ASCII_STRING], @0), @"ImageDescription", + TAGINF_W_APPEND(@"0132", [NSNumber numberWithInt:EDT_ASCII_STRING], @20, @"00"), @"DateTime", + TAGINF(@"010f", [NSNumber numberWithInt:EDT_ASCII_STRING], @0), @"Make", + TAGINF(@"0110", [NSNumber numberWithInt:EDT_ASCII_STRING], @0), @"Model", + TAGINF(@"0131", [NSNumber numberWithInt:EDT_ASCII_STRING], @0), @"Software", + TAGINF(@"011a", [NSNumber numberWithInt:EDT_URATIONAL], @1), @"XResolution", + TAGINF(@"011b", [NSNumber numberWithInt:EDT_URATIONAL], @1), @"YResolution", + // currently supplied outside of Exif data block by UIImagePickerControllerMediaMetadata, this is set manually in CDVCamera.m + /* TAGINF(@"0112", [NSNumber numberWithInt:EDT_USHORT], @1), @"Orientation", + + // rest of the tags are supported by exif spec, but are not specified by UIImagePickerControllerMediaMedadata + // should camera hardware supply these values in future versions, or if they can be derived, ImageHeaderWriter will include them gracefully + TAGINF(@"0128", [NSNumber numberWithInt:EDT_USHORT], @1), @"ResolutionUnit", + TAGINF(@"013e", [NSNumber numberWithInt:EDT_URATIONAL], @2), @"WhitePoint", + TAGINF(@"013f", [NSNumber numberWithInt:EDT_URATIONAL], @6), @"PrimaryChromaticities", + TAGINF(@"0211", [NSNumber numberWithInt:EDT_URATIONAL], @3), @"YCbCrCoefficients", + TAGINF(@"0213", [NSNumber numberWithInt:EDT_USHORT], @1), @"YCbCrPositioning", + TAGINF(@"0214", [NSNumber numberWithInt:EDT_URATIONAL], @6), @"ReferenceBlackWhite", + TAGINF(@"8298", [NSNumber numberWithInt:EDT_URATIONAL], @0), @"Copyright", + + // offset to exif subifd, we determine this dynamically based on the size of the main exif IFD + TAGINF(@"8769", [NSNumber numberWithInt:EDT_ULONG], @1), @"ExifOffset",*/ + nil]; + + + // supported tages for exif subIFD + SubIFDTagFormatDict = [[NSDictionary alloc] initWithObjectsAndKeys: + //TAGINF(@"9000", [NSNumber numberWithInt:], @), @"ExifVersion", + //TAGINF(@"9202",[NSNumber numberWithInt:EDT_URATIONAL],@1), @"ApertureValue", + //TAGINF(@"9203",[NSNumber numberWithInt:EDT_SRATIONAL],@1), @"BrightnessValue", + TAGINF(@"a001",[NSNumber numberWithInt:EDT_USHORT],@1), @"ColorSpace", + TAGINF_W_APPEND(@"9004",[NSNumber numberWithInt:EDT_ASCII_STRING],@20,@"00"), @"DateTimeDigitized", + TAGINF_W_APPEND(@"9003",[NSNumber numberWithInt:EDT_ASCII_STRING],@20,@"00"), @"DateTimeOriginal", + TAGINF(@"a402", [NSNumber numberWithInt:EDT_USHORT], @1), @"ExposureMode", + TAGINF(@"8822", [NSNumber numberWithInt:EDT_USHORT], @1), @"ExposureProgram", + //TAGINF(@"829a", [NSNumber numberWithInt:EDT_URATIONAL], @1), @"ExposureTime", + //TAGINF(@"829d", [NSNumber numberWithInt:EDT_URATIONAL], @1), @"FNumber", + TAGINF(@"9209", [NSNumber numberWithInt:EDT_USHORT], @1), @"Flash", + // FocalLengthIn35mmFilm + TAGINF(@"a405", [NSNumber numberWithInt:EDT_USHORT], @1), @"FocalLenIn35mmFilm", + //TAGINF(@"920a", [NSNumber numberWithInt:EDT_URATIONAL], @1), @"FocalLength", + //TAGINF(@"8827", [NSNumber numberWithInt:EDT_USHORT], @2), @"ISOSpeedRatings", + TAGINF(@"9207", [NSNumber numberWithInt:EDT_USHORT],@1), @"MeteringMode", + // specific to compressed data + TAGINF(@"a002", [NSNumber numberWithInt:EDT_ULONG],@1), @"PixelXDimension", + TAGINF(@"a003", [NSNumber numberWithInt:EDT_ULONG],@1), @"PixelYDimension", + // data type undefined, but this is a DSC camera, so value is always 1, treat as ushort + TAGINF(@"a301", [NSNumber numberWithInt:EDT_USHORT],@1), @"SceneType", + TAGINF(@"a217",[NSNumber numberWithInt:EDT_USHORT],@1), @"SensingMethod", + //TAGINF(@"9201", [NSNumber numberWithInt:EDT_SRATIONAL], @1), @"ShutterSpeedValue", + // specifies location of main subject in scene (x,y,wdith,height) expressed before rotation processing + //TAGINF(@"9214", [NSNumber numberWithInt:EDT_USHORT], @4), @"SubjectArea", + TAGINF(@"a403", [NSNumber numberWithInt:EDT_USHORT], @1), @"WhiteBalance", + nil]; + return self; +} + +- (NSData*) spliceExifBlockIntoJpeg: (NSData*) jpegdata withExifBlock: (NSString*) exifstr { + + CDVJpegHeaderWriter * exifWriter = [[CDVJpegHeaderWriter alloc] init]; + + NSMutableData * exifdata = [NSMutableData dataWithCapacity: [exifstr length]/2]; + int idx; + for (idx = 0; idx+1 < [exifstr length]; idx+=2) { + NSRange range = NSMakeRange(idx, 2); + NSString* hexStr = [exifstr substringWithRange:range]; + NSScanner* scanner = [NSScanner scannerWithString:hexStr]; + unsigned int intValue; + [scanner scanHexInt:&intValue]; + [exifdata appendBytes:&intValue length:1]; + } + + NSMutableData * ddata = [NSMutableData dataWithCapacity: [jpegdata length]]; + NSMakeRange(0,4); + int loc = 0; + bool done = false; + // read the jpeg data until we encounter the app1==0xFFE1 marker + while (loc+1 < [jpegdata length]) { + NSData * blag = [jpegdata subdataWithRange: NSMakeRange(loc,2)]; + if( [[blag description] isEqualToString : @""]) { + // read the APP1 block size bits + NSString * the = [exifWriter hexStringFromData:[jpegdata subdataWithRange: NSMakeRange(loc+2,2)]]; + NSNumber * app1width = [exifWriter numericFromHexString:the]; + //consume the original app1 block + [ddata appendData:exifdata]; + // advance our loc marker past app1 + loc += [app1width intValue] + 2; + done = true; + } else { + if(!done) { + [ddata appendData:blag]; + loc += 2; + } else { + break; + } + } + } + // copy the remaining data + [ddata appendData:[jpegdata subdataWithRange: NSMakeRange(loc,[jpegdata length]-loc)]]; + return ddata; +} + + + +/** + * Create the Exif data block as a hex string + * jpeg uses Application Markers (APP's) as markers for application data + * APP1 is the application marker reserved for exif data + * + * (NSDictionary*) datadict - with subdictionaries marked '{TIFF}' and '{EXIF}' as returned by imagePickerController with a valid + * didFinishPickingMediaWithInfo data dict, under key @"UIImagePickerControllerMediaMetadata" + * + * the following constructs a hex string to Exif specifications, and is therefore brittle + * altering the order of arguments to the string constructors, modifying field sizes or formats, + * and any other minor change will likely prevent the exif data from being read + */ +- (NSString*) createExifAPP1 : (NSDictionary*) datadict { + NSMutableString * app1; // holds finalized product + NSString * exifIFD; // exif information file directory + NSString * subExifIFD; // subexif information file directory + + // FFE1 is the hex APP1 marker code, and will allow client apps to read the data + NSString * app1marker = @"ffe1"; + // SSSS size, to be determined + // EXIF ascii characters followed by 2bytes of zeros + NSString * exifmarker = @"457869660000"; + // Tiff header: 4d4d is motorolla byte align (big endian), 002a is hex for 42 + NSString * tiffheader = @"4d4d002a"; + //first IFD offset from the Tiff header to IFD0. Since we are writing it, we know it's address 0x08 + NSString * ifd0offset = @"00000008"; + // current offset to next data area + int currentDataOffset = 0; + + //data labeled as TIFF in UIImagePickerControllerMediaMetaData is part of the EXIF IFD0 portion of APP1 + exifIFD = [self createExifIFDFromDict: [datadict objectForKey:@"{TIFF}"] withFormatDict: IFD0TagFormatDict isIFD0:YES currentDataOffset:¤tDataOffset]; + + //data labeled as EXIF in UIImagePickerControllerMediaMetaData is part of the EXIF Sub IFD portion of APP1 + subExifIFD = [self createExifIFDFromDict: [datadict objectForKey:@"{Exif}"] withFormatDict: SubIFDTagFormatDict isIFD0:NO currentDataOffset:¤tDataOffset]; + /* + NSLog(@"SUB EXIF IFD %@ WITH SIZE: %d",exifIFD,[exifIFD length]); + + NSLog(@"SUB EXIF IFD %@ WITH SIZE: %d",subExifIFD,[subExifIFD length]); + */ + // construct the complete app1 data block + app1 = [[NSMutableString alloc] initWithFormat: @"%@%04x%@%@%@%@%@", + app1marker, + (unsigned int)(16 + ([exifIFD length]/2) + ([subExifIFD length]/2)) /*16+[exifIFD length]/2*/, + exifmarker, + tiffheader, + ifd0offset, + exifIFD, + subExifIFD]; + + return app1; +} + +// returns hex string representing a valid exif information file directory constructed from the datadict and formatdict +- (NSString*) createExifIFDFromDict : (NSDictionary*) datadict + withFormatDict : (NSDictionary*) formatdict + isIFD0 : (BOOL) ifd0flag + currentDataOffset : (int*) dataoffset { + NSArray * datakeys = [datadict allKeys]; // all known data keys + NSArray * knownkeys = [formatdict allKeys]; // only keys in knowkeys are considered for entry in this IFD + NSMutableArray * ifdblock = [[NSMutableArray alloc] initWithCapacity: [datadict count]]; // all ifd entries + NSMutableArray * ifddatablock = [[NSMutableArray alloc] initWithCapacity: [datadict count]]; // data block entries + // ifd0flag = NO; // ifd0 requires a special flag and has offset to next ifd appended to end + + // iterate through known provided data keys + for (int i = 0; i < [datakeys count]; i++) { + NSString * key = [datakeys objectAtIndex:i]; + // don't muck about with unknown keys + if ([knownkeys indexOfObject: key] != NSNotFound) { + // create new IFD entry + NSString * entry = [self createIFDElement: key + withFormat: [formatdict objectForKey:key] + withElementData: [datadict objectForKey:key]]; + // create the IFD entry's data block + NSString * data = [self createIFDElementDataWithFormat: [formatdict objectForKey:key] + withData: [datadict objectForKey:key]]; + if (entry) { + [ifdblock addObject:entry]; + if(!data) { + [ifdblock addObject:@""]; + } else { + [ifddatablock addObject:data]; + } + } + } + } + + NSMutableString * exifstr = [[NSMutableString alloc] initWithCapacity: [ifdblock count] * 24]; + NSMutableString * dbstr = [[NSMutableString alloc] initWithCapacity: 100]; + + int addr=*dataoffset; // current offset/address in datablock + if (ifd0flag) { + // calculate offset to datablock based on ifd file entry count + addr += 14+(12*([ifddatablock count]+1)); // +1 for tag 0x8769, exifsubifd offset + } else { + // current offset + numSubIFDs (2-bytes) + 12*numSubIFDs + endMarker (4-bytes) + addr += 2+(12*[ifddatablock count])+4; + } + + for (int i = 0; i < [ifdblock count]; i++) { + NSString * entry = [ifdblock objectAtIndex:i]; + NSString * data = [ifddatablock objectAtIndex:i]; + + // check if the data fits into 4 bytes + if( [data length] <= 8) { + // concatenate the entry and the (4byte) data entry into the final IFD entry and append to exif ifd string + [exifstr appendFormat : @"%@%@", entry, data]; + } else { + [exifstr appendFormat : @"%@%08x", entry, addr]; + [dbstr appendFormat: @"%@", data]; + addr+= [data length] / 2; + /* + NSLog(@"=====data-length[%i]=======",[data length]); + NSLog(@"addr-offset[%i]",addr); + NSLog(@"entry[%@]",entry); + NSLog(@"data[%@]",data); + */ + } + } + + // calculate IFD0 terminal offset tags, currently ExifSubIFD + unsigned int entrycount = (unsigned int)[ifdblock count]; + if (ifd0flag) { + // 18 accounts for 8769's width + offset to next ifd, 8 accounts for start of header + NSNumber * offset = [NSNumber numberWithUnsignedInteger:[exifstr length] / 2 + [dbstr length] / 2 + 18+8]; + + [self appendExifOffsetTagTo: exifstr + withOffset : offset]; + entrycount++; + } + *dataoffset = addr; + return [[NSString alloc] initWithFormat: @"%04x%@%@%@", + entrycount, + exifstr, + @"00000000", // offset to next IFD, 0 since there is none + dbstr]; // lastly, the datablock +} + +// Creates an exif formatted exif information file directory entry +- (NSString*) createIFDElement: (NSString*) elementName withFormat: (NSArray*) formtemplate withElementData: (NSString*) data { + //NSArray * fielddata = [formatdict objectForKey: elementName];// format data of desired field + if (formtemplate) { + // format string @"%@%@%@%@", tag number, data format, components, value + NSNumber * dataformat = [formtemplate objectAtIndex:1]; + NSNumber * components = [formtemplate objectAtIndex:2]; + if([components intValue] == 0) { + components = [NSNumber numberWithUnsignedInteger:[data length] * DataTypeToWidth[[dataformat intValue]-1]]; + } + + return [[NSString alloc] initWithFormat: @"%@%@%08x", + [formtemplate objectAtIndex:0], // the field code + [self formatNumberWithLeadingZeroes: dataformat withPlaces: @4], // the data type code + [components intValue]]; // number of components + } + return NULL; +} + +/** + * appends exif IFD0 tag 8769 "ExifOffset" to the string provided + * (NSMutableString*) str - string you wish to append the 8769 tag to: APP1 or IFD0 hex data string + * // TAGINF(@"8769", [NSNumber numberWithInt:EDT_ULONG], @1), @"ExifOffset", + */ +- (void) appendExifOffsetTagTo: (NSMutableString*) str withOffset : (NSNumber*) offset { + NSArray * format = TAGINF(@"8769", [NSNumber numberWithInt:EDT_ULONG], @1); + + NSString * entry = [self createIFDElement: @"ExifOffset" + withFormat: format + withElementData: [offset stringValue]]; + + NSString * data = [self createIFDElementDataWithFormat: format + withData: [offset stringValue]]; + [str appendFormat:@"%@%@", entry, data]; +} + +// formats the Information File Directory Data to exif format +- (NSString*) createIFDElementDataWithFormat: (NSArray*) dataformat withData: (NSString*) data { + NSMutableString * datastr = nil; + NSNumber * tmp = nil; + NSNumber * formatcode = [dataformat objectAtIndex:1]; + NSUInteger formatItemsCount = [dataformat count]; + NSNumber * num = @0; + NSNumber * denom = @0; + + switch ([formatcode intValue]) { + case EDT_UBYTE: + break; + case EDT_ASCII_STRING: + datastr = [[NSMutableString alloc] init]; + for (int i = 0; i < [data length]; i++) { + [datastr appendFormat:@"%02x",[data characterAtIndex:i]]; + } + if (formatItemsCount > 3) { + // We have additional data to append. + // currently used by Date format to append final 0x00 but can be used by other data types as well in the future + [datastr appendString:[dataformat objectAtIndex:3]]; + } + if ([datastr length] < 8) { + NSString * format = [NSString stringWithFormat:@"%%0%dd", (int)(8 - [datastr length])]; + [datastr appendFormat:format,0]; + } + return datastr; + case EDT_USHORT: + return [[NSString alloc] initWithFormat : @"%@%@", + [self formattedHexStringFromDecimalNumber: [NSNumber numberWithInt: [data intValue]] withPlaces: @4], + @"0000"]; + case EDT_ULONG: + tmp = [NSNumber numberWithUnsignedLong:[data intValue]]; + return [NSString stringWithFormat : @"%@", + [self formattedHexStringFromDecimalNumber: tmp withPlaces: @8]]; + case EDT_URATIONAL: + return [self decimalToUnsignedRational: [NSNumber numberWithDouble:[data doubleValue]] + withResultNumerator: &num + withResultDenominator: &denom]; + case EDT_SBYTE: + + break; + case EDT_UNDEFINED: + break; // 8 bits + case EDT_SSHORT: + break; + case EDT_SLONG: + break; // 32bit signed integer (2's complement) + case EDT_SRATIONAL: + break; // 2 SLONGS, first long is numerator, second is denominator + case EDT_SINGLEFLOAT: + break; + case EDT_DOUBLEFLOAT: + break; + } + return datastr; +} + +//====================================================================================================================== +// Utility Methods +//====================================================================================================================== + +// creates a formatted little endian hex string from a number and width specifier +- (NSString*) formattedHexStringFromDecimalNumber: (NSNumber*) numb withPlaces: (NSNumber*) width { + NSMutableString * str = [[NSMutableString alloc] initWithCapacity:[width intValue]]; + NSString * formatstr = [[NSString alloc] initWithFormat: @"%%%@%dx", @"0", [width intValue]]; + [str appendFormat:formatstr, [numb intValue]]; + return str; +} + +// format number as string with leading 0's +- (NSString*) formatNumberWithLeadingZeroes: (NSNumber *) numb withPlaces: (NSNumber *) places { + NSNumberFormatter * formatter = [[NSNumberFormatter alloc] init]; + NSString *formatstr = [@"" stringByPaddingToLength:[places unsignedIntegerValue] withString:@"0" startingAtIndex:0]; + [formatter setPositiveFormat:formatstr]; + return [formatter stringFromNumber:numb]; +} + +// approximate a decimal with a rational by method of continued fraction +// can be collasped into decimalToUnsignedRational after testing +- (void) decimalToRational: (NSNumber *) numb + withResultNumerator: (NSNumber**) numerator + withResultDenominator: (NSNumber**) denominator { + NSMutableArray * fractionlist = [[NSMutableArray alloc] initWithCapacity:8]; + + [self continuedFraction: [numb doubleValue] + withFractionList: fractionlist + withHorizon: 8]; + + // simplify complex fraction represented by partial fraction list + [self expandContinuedFraction: fractionlist + withResultNumerator: numerator + withResultDenominator: denominator]; + +} + +// approximate a decimal with an unsigned rational by method of continued fraction +- (NSString*) decimalToUnsignedRational: (NSNumber *) numb + withResultNumerator: (NSNumber**) numerator + withResultDenominator: (NSNumber**) denominator { + NSMutableArray * fractionlist = [[NSMutableArray alloc] initWithCapacity:8]; + + // generate partial fraction list + [self continuedFraction: [numb doubleValue] + withFractionList: fractionlist + withHorizon: 8]; + + // simplify complex fraction represented by partial fraction list + [self expandContinuedFraction: fractionlist + withResultNumerator: numerator + withResultDenominator: denominator]; + + return [self formatFractionList: fractionlist]; +} + +// recursive implementation of decimal approximation by continued fraction +- (void) continuedFraction: (double) val + withFractionList: (NSMutableArray*) fractionlist + withHorizon: (int) horizon { + int whole; + double remainder; + // 1. split term + [self splitDouble: val withIntComponent: &whole withFloatRemainder: &remainder]; + [fractionlist addObject: [NSNumber numberWithInt:whole]]; + + // 2. calculate reciprocal of remainder + if (!remainder) return; // early exit, exact fraction found, avoids recip/0 + double recip = 1 / remainder; + + // 3. exit condition + if ([fractionlist count] > horizon) { + return; + } + + // 4. recurse + [self continuedFraction:recip withFractionList: fractionlist withHorizon: horizon]; + +} + +// expand continued fraction list, creating a single level rational approximation +-(void) expandContinuedFraction: (NSArray*) fractionlist + withResultNumerator: (NSNumber**) numerator + withResultDenominator: (NSNumber**) denominator { + NSUInteger i = 0; + int den = 0; + int num = 0; + if ([fractionlist count] == 1) { + *numerator = [NSNumber numberWithInt:[[fractionlist objectAtIndex:0] intValue]]; + *denominator = @1; + return; + } + + //begin at the end of the list + i = [fractionlist count] - 1; + num = 1; + den = [[fractionlist objectAtIndex:i] intValue]; + + while (i > 0) { + int t = [[fractionlist objectAtIndex: i-1] intValue]; + num = t * den + num; + if (i==1) { + break; + } else { + t = num; + num = den; + den = t; + } + i--; + } + // set result parameters values + *numerator = [NSNumber numberWithInt: num]; + *denominator = [NSNumber numberWithInt: den]; +} + +// formats expanded fraction list to string matching exif specification +- (NSString*) formatFractionList: (NSArray *) fractionlist { + NSMutableString * str = [[NSMutableString alloc] initWithCapacity:16]; + + if ([fractionlist count] == 1){ + [str appendFormat: @"%08x00000001", [[fractionlist objectAtIndex:0] intValue]]; + } + return str; +} + +// format rational as +- (NSString*) formatRationalWithNumerator: (NSNumber*) numerator withDenominator: (NSNumber*) denominator asSigned: (Boolean) signedFlag { + NSMutableString * str = [[NSMutableString alloc] initWithCapacity:16]; + if (signedFlag) { + long num = [numerator longValue]; + long den = [denominator longValue]; + [str appendFormat: @"%08lx%08lx", num >= 0 ? num : ~ABS(num) + 1, num >= 0 ? den : ~ABS(den) + 1]; + } else { + [str appendFormat: @"%08lx%08lx", [numerator unsignedLongValue], [denominator unsignedLongValue]]; + } + return str; +} + +// split a floating point number into two integer values representing the left and right side of the decimal +- (void) splitDouble: (double) val withIntComponent: (int*) rightside withFloatRemainder: (double*) leftside { + *rightside = val; // convert numb to int representation, which truncates the decimal portion + *leftside = val - *rightside; +} + + +// +- (NSString*) hexStringFromData : (NSData*) data { + //overflow detection + const unsigned char *dataBuffer = [data bytes]; + return [[NSString alloc] initWithFormat: @"%02x%02x", + (unsigned char)dataBuffer[0], + (unsigned char)dataBuffer[1]]; +} + +// convert a hex string to a number +- (NSNumber*) numericFromHexString : (NSString *) hexstring { + NSScanner * scan = NULL; + unsigned int numbuf= 0; + + scan = [NSScanner scannerWithString:hexstring]; + [scan scanHexInt:&numbuf]; + return [NSNumber numberWithInt:numbuf]; +} + +@end diff --git a/plugins/cordova-plugin-camera/src/ios/UIImage+CropScaleOrientation.h b/plugins/cordova-plugin-camera/src/ios/UIImage+CropScaleOrientation.h new file mode 100644 index 0000000..31bc42f --- /dev/null +++ b/plugins/cordova-plugin-camera/src/ios/UIImage+CropScaleOrientation.h @@ -0,0 +1,29 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. + */ + +#import + +@interface UIImage (CropScaleOrientation) + +- (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize; +- (UIImage*)imageCorrectedForCaptureOrientation; +- (UIImage*)imageCorrectedForCaptureOrientation:(UIImageOrientation)imageOrientation; +- (UIImage*)imageByScalingNotCroppingForSize:(CGSize)targetSize; + +@end \ No newline at end of file diff --git a/plugins/cordova-plugin-camera/src/ios/UIImage+CropScaleOrientation.m b/plugins/cordova-plugin-camera/src/ios/UIImage+CropScaleOrientation.m new file mode 100644 index 0000000..a66a5d8 --- /dev/null +++ b/plugins/cordova-plugin-camera/src/ios/UIImage+CropScaleOrientation.m @@ -0,0 +1,175 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. + */ + +#import "UIImage+CropScaleOrientation.h" + +@implementation UIImage (CropScaleOrientation) + +- (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize +{ + UIImage* sourceImage = self; + UIImage* newImage = nil; + CGSize imageSize = sourceImage.size; + CGFloat width = imageSize.width; + CGFloat height = imageSize.height; + CGFloat targetWidth = targetSize.width; + CGFloat targetHeight = targetSize.height; + CGFloat scaleFactor = 0.0; + CGFloat scaledWidth = targetWidth; + CGFloat scaledHeight = targetHeight; + CGPoint thumbnailPoint = CGPointMake(0.0, 0.0); + + if (CGSizeEqualToSize(imageSize, targetSize) == NO) { + CGFloat widthFactor = targetWidth / width; + CGFloat heightFactor = targetHeight / height; + + if (widthFactor > heightFactor) { + scaleFactor = widthFactor; // scale to fit height + } else { + scaleFactor = heightFactor; // scale to fit width + } + scaledWidth = width * scaleFactor; + scaledHeight = height * scaleFactor; + + // center the image + if (widthFactor > heightFactor) { + thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5; + } else if (widthFactor < heightFactor) { + thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5; + } + } + + UIGraphicsBeginImageContext(targetSize); // this will crop + + CGRect thumbnailRect = CGRectZero; + thumbnailRect.origin = thumbnailPoint; + thumbnailRect.size.width = scaledWidth; + thumbnailRect.size.height = scaledHeight; + + [sourceImage drawInRect:thumbnailRect]; + + newImage = UIGraphicsGetImageFromCurrentImageContext(); + if (newImage == nil) { + NSLog(@"could not scale image"); + } + + // pop the context to get back to the default + UIGraphicsEndImageContext(); + return newImage; +} + +- (UIImage*)imageCorrectedForCaptureOrientation:(UIImageOrientation)imageOrientation +{ + float rotation_radians = 0; + bool perpendicular = false; + + switch (imageOrientation) { + case UIImageOrientationUp : + rotation_radians = 0.0; + break; + + case UIImageOrientationDown: + rotation_radians = M_PI; // don't be scared of radians, if you're reading this, you're good at math + break; + + case UIImageOrientationRight: + rotation_radians = M_PI_2; + perpendicular = true; + break; + + case UIImageOrientationLeft: + rotation_radians = -M_PI_2; + perpendicular = true; + break; + + default: + break; + } + + UIGraphicsBeginImageContext(CGSizeMake(self.size.width, self.size.height)); + CGContextRef context = UIGraphicsGetCurrentContext(); + + // Rotate around the center point + CGContextTranslateCTM(context, self.size.width / 2, self.size.height / 2); + CGContextRotateCTM(context, rotation_radians); + + CGContextScaleCTM(context, 1.0, -1.0); + float width = perpendicular ? self.size.height : self.size.width; + float height = perpendicular ? self.size.width : self.size.height; + CGContextDrawImage(context, CGRectMake(-width / 2, -height / 2, width, height), [self CGImage]); + + // Move the origin back since the rotation might've change it (if its 90 degrees) + if (perpendicular) { + CGContextTranslateCTM(context, -self.size.height / 2, -self.size.width / 2); + } + + UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext(); + UIGraphicsEndImageContext(); + return newImage; +} + +- (UIImage*)imageCorrectedForCaptureOrientation +{ + return [self imageCorrectedForCaptureOrientation:[self imageOrientation]]; +} + +- (UIImage*)imageByScalingNotCroppingForSize:(CGSize)targetSize +{ + UIImage* sourceImage = self; + UIImage* newImage = nil; + CGSize imageSize = sourceImage.size; + CGFloat width = imageSize.width; + CGFloat height = imageSize.height; + CGFloat targetWidth = targetSize.width; + CGFloat targetHeight = targetSize.height; + CGFloat scaleFactor = 0.0; + CGSize scaledSize = targetSize; + + if (CGSizeEqualToSize(imageSize, targetSize) == NO) { + CGFloat widthFactor = targetWidth / width; + CGFloat heightFactor = targetHeight / height; + + // opposite comparison to imageByScalingAndCroppingForSize in order to contain the image within the given bounds + if (widthFactor > heightFactor) { + scaleFactor = heightFactor; // scale to fit height + } else { + scaleFactor = widthFactor; // scale to fit width + } + scaledSize = CGSizeMake(MIN(width * scaleFactor, targetWidth), MIN(height * scaleFactor, targetHeight)); + } + + // If the pixels are floats, it causes a white line in iOS8 and probably other versions too + scaledSize.width = (int)scaledSize.width; + scaledSize.height = (int)scaledSize.height; + + UIGraphicsBeginImageContext(scaledSize); // this will resize + + [sourceImage drawInRect:CGRectMake(0, 0, scaledSize.width, scaledSize.height)]; + + newImage = UIGraphicsGetImageFromCurrentImageContext(); + if (newImage == nil) { + NSLog(@"could not scale image"); + } + + // pop the context to get back to the default + UIGraphicsEndImageContext(); + return newImage; +} + +@end diff --git a/plugins/cordova-plugin-camera/src/ubuntu/CaptureWidget.qml b/plugins/cordova-plugin-camera/src/ubuntu/CaptureWidget.qml new file mode 100644 index 0000000..0a332e2 --- /dev/null +++ b/plugins/cordova-plugin-camera/src/ubuntu/CaptureWidget.qml @@ -0,0 +1,118 @@ +/* + * + * Copyright 2013 Canonical Ltd. + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ +import QtQuick 2.0 +import QtMultimedia 5.0 + +Rectangle { + property string shootImagePath: "shoot.png" + function isSuffix(str, suffix) { + return String(str).substr(String(str).length - suffix.length) == suffix + } + + id: ui + color: "#252423" + anchors.fill: parent + + Camera { + objectName: "camera" + id: camera + onError: { + console.log(errorString); + } + videoRecorder.audioBitRate: 128000 + imageCapture { + onImageSaved: { + root.exec("Camera", "onImageSaved", [path]); + ui.destroy(); + } + } + } + VideoOutput { + id: output + source: camera + width: parent.width + height: parent.height + } + + Item { + anchors.bottom: parent.bottom + width: parent.width + height: shootButton.height + BorderImage { + id: leftBackground + anchors.left: parent.left + anchors.top: parent.top + anchors.bottom: parent.bottom + anchors.right: middle.left + anchors.topMargin: units.dp(2) + anchors.bottomMargin: units.dp(2) + source: "toolbar-left.png" + Image { + anchors.verticalCenter: parent.verticalCenter + anchors.left: parent.left + anchors.leftMargin: parent.iconSpacing + source: "back.png" + width: units.gu(6) + height: units.gu(5) + MouseArea { + anchors.fill: parent + onClicked: { + root.exec("Camera", "cancel"); + } + } + } + } + BorderImage { + id: middle + anchors.top: parent.top + anchors.bottom: parent.bottom + anchors.horizontalCenter: parent.horizontalCenter + height: shootButton.height + units.gu(1) + width: shootButton.width + source: "toolbar-middle.png" + Image { + id: shootButton + width: units.gu(8) + height: width + anchors.horizontalCenter: parent.horizontalCenter + source: shootImagePath + MouseArea { + anchors.fill: parent + onClicked: { + camera.imageCapture.captureToLocation(ui.parent.plugin('Camera').generateLocation("jpg")); + } + } + } + } + BorderImage { + id: rightBackground + anchors.right: parent.right + anchors.top: parent.top + anchors.bottom: parent.bottom + anchors.left: middle.right + anchors.topMargin: units.dp(2) + anchors.bottomMargin: units.dp(2) + source: "toolbar-right.png" + } + } +} diff --git a/plugins/cordova-plugin-camera/src/ubuntu/back.png b/plugins/cordova-plugin-camera/src/ubuntu/back.png new file mode 100644 index 0000000000000000000000000000000000000000..af78faa837ce940e2818f5a8fcd2f88e1de27bda GIT binary patch literal 12428 zcmZ8{byytF@9-Ti#ogWADQ?9JEnZw&+`Z`G4#nYGq`)D?-QA13yBBvka6(14F(ne*X4)pB>sEp=`3vpgP{L)?kyfL0KiqRBqy!qy?omKJ;iXrf8(+F zzFpT>Th}X}>=0>^8h}ebW%yO2&QlZj!*G(KVhsUH1Kr@xVzmD*`GK&7FYivZ_-C=5 z9XzJ&U&*_wN$<1!5*-+-DTeXBkVX~AmD5W*11I&O9CL|o*6X>Pn!R3|Zd?A8mioXe z{xE+V|6cTGUFW=gRYAKTK9jO6D@Az6PzPqTsCnle7OXsSnd=iwfiUE2CyiU z2yX-0tVC_i{-k4ad>plY0U#FVX}~IfWswO`X36q2ikl{7L6|B=IQ^)jYy5P3dH#AL z1VY<{i#DPLIGF-svx#GDDg5M7j=fUNI}cc%d??OD(&)3&Qk0{Ux$sfo;&LSG*5zD46rA&|+He-;W{|7EMD z-}WUiel1%HzQT@Br3V^N7J;75Dt1}^Ew3d1JgU&?&9&XTIX)3Uxw-Mrw`J}oJP|NR zCHaCUGxU}#z+@}1_wFR>0*{JpcP5A2d?PpHAV>pb{ZGIk*g_@yeWrpklm1A%d$UfH zFcy9gYb(I}MFj-o!@UxF{w?@Nj;GNFdfM*`qP2e8ea3gE^(70xb&#h_{f@UEoiC(f zUtdvTVk#7G#J$CYZWp-VNWcwUKbML9*5FKU`t;DsUuk4sEwK+%j#=U<(`P^we`kOw~BAWOe>$iFJK z7Y-FTNIY#xNL&n2CZPryY^*=tVSV_1h8Rg7em}rFh-4QQV?({%^d?kK>TLvsAz#F) zd-@pqTy|h1bv-F7{``P^@4V~$t`W0dU$!r%{ILoSB_;7{T8&}H-|4*`o1qvwJpj4* zno$S768(RRAaAY`@TO-obv{pkj4Aj1Ip6m&v9SPHtOEenoGyOas5C&Oz)3oJn_AIj ze03vLgi9PSZUr=HyFXW_Zy-J0<6O1hw$PF$`&~>0P`-3g)_g%+n%e&4jbkeE2~Vk+U? z#iT*)qM%mkM~X_D$QL9cFVfceW%g+``Xu;sVZ*Vk_p&pX-ZL#Bl`MdG$-8NPndLyh zwycLPPBjCT3oTo8c3y5+w4`S=$GU0jGkXQ*)f6kY`nhY`rauKYo{W@`~?{y!H@QsK&sI%%-=>BHx-qLTNon}-u|hq(Te~=H$N6jg2uy~DAqC{- z<1>7jkaM9oG50lnc+oA9rEfnM2dvnU0#`BFXZ4LH|F#xtztqilN1GUAG+o^k5pqX_j*z7}vcg0Y@FXjv_oijH{;wta>)-9I z2h%4~qO1Vj|;35v4ADXL~fzfY)Gnq(uPR zoHKG*35lNGP01WV17g316z6$9fvV~}vo3sv+8j%opKBP%Z>mT`doc}|z<`*>fc>yg zcgIxcnuD?WoE-F1G;nVvCp+&;$U_TaAI5*%Sx@eG^Bm30-+wX1+vLp|Z82Ye(2{N}?>(FRTE zEwc5xkr%;K@ov`nzn%8;HCc5Pl*ZIVQJ_>QtKQ&^^BQ46&??-gfhb^wPSjVJxTU)DyXX^8aHDei(VYemgk2+ODl% zKqqd%08Qap^k&qQO+0oqq)x}KCvW+mZ}cYSyF6F%BG1R|dg6306`OdC3SxA9gvbyL zI3Y#q%xw!J;p-h6GmnA z(h;kquuj3Jz-g^D6E~%7zvDFFD^|=U#si~nA6aX0sC`(?HBX)_G zT5yR`^mO4{`w3k9MJod}DNhnD%I4FrK}ZzohF@XVFdxAH)3Krob{q=(?~x$g=Rdkx zuQNwPfycx8uYM3<_<|OzJu1vT`94b1l)q8*AsgwMtt3UP&yPTwd z%mere8&5jN;Sb@GvUmehUDk-#(83)zyNV;`b^tU#4?M{uMF!&a3{kzWkP$olYliNP znKhYNXyd83QM5jZ?`c=QU9K)ty{2!UXnt4y^iLqOwTcEHuO8bUw1Fr=h9Gj>5-l1J z@xGA_Ar}Wr*?bB>pAm%bVpQFjgkS73UQ8U?fZJ&;iO@Ns7A5aQ!sqx$>qzz`aNj(R zDe%)Kn>tYww{fovLUp7Za%!#Px2uhbEGSW+G1yn+ULWwA?SK1K6J~Rh z*Kv0WXYy*9ZDmrCo5D!w0B80r8hD_dV#3)8meNE1Z=IlS<^VfSzLSmwL(h)45*3ga zMZd~4wLtvL>HIs-?sb5Z4dwaBlbixA+yN98qCE9v`34Iygy*>BP4S-4QXb!r*DJw-&BW^7PQ zou^H5oJq1iCt_nkoz})sbSC0#xt&bie;>y<*i-GDH?qZ<60Kuzgl z)W5R6KDhC;();c_Vapf0uGzCZb`=%SKn7Rn@bhu^CFf!@>bFF)vWcY^QB3RvMXF9ur&6(Do`k@iiX-6@1^V( zupGp&Qjt%9Km({lGLfDO$*$|~b((PA{S@q$Udqnt+lT9aZxv4EpH4As%*o{!SON^D zfd7pOYL&QWyKRxU%6B^6%Z6%{CUXfQNI?&s;QQjd0b4;rz3_{p*sHUci>hJnrq+XR z|2#X80Cj@YpO)n`k2?}k6y#~eoK2$rKD&I+i{9&tz!mqB#8o2CU>z412)X3+D!|o= zv9A-XW$LkCidS3>eQ8w$>v+_TW1qN!b)u$D14SK(PN8)s>c<{+>CDIVP%m z!I?*__2A)rr@msct@_1Hv2t96DvxHy<+O6c+`}pv`CzG4~=#8 zd3cm4N89u8Om_G-e+!$TLwxkb(S?l)PIRrh>g0)U6{NZr4Rq3t=OMa$A0wR$N%?Fm zfUF`T!hu~A^43WLSnj(HS9Mx5vA^8dduv4;s)m{pcH~bYLaY(;p`ftjdhmpJ=6H!&x@adq(--r6M+O@<^Bdpx~%8jj6 zyStSx_(P;%9imT-ilE$XZ^-=X9htFAIp$GWe^4U6l^Rj;LN)G^DCJFQZ4t}`XT!j@ zXGPTkZl*EbWUmCiDul+ap0@xqRa3M?WU6yBax|@Tixg;OZ6=4CY%JUrY^tV;oyab; zYJ!gASL7&GtB@z9Y3ud@EpUHcevuW2cw$joCjz8boJ=wqK7G2*WwJ{?i*mh`!GUDS z(fU4*Z?870AsKhXWDD+tu=+|oQqXZe;BU5tO$iP%J5ZQp582dQm|a! z`!i8qzaqe*qKLa0x6!;43v$(PbeVXY#@A?MGVAIxFrZG2$`xxBJ=*7ALbVYfV7pO~<_s-Q|`EwuVUV7vqYg30);d zTKXi+y&B5^wcl_f#9HNeq*g4ZsQy7z@%)cb{fB3*z6e*859ICgoZ;u2z^#K^9BCMD{TTV;aQ=;hC znv~)n(mshEz3N~|HIjnXW~Fv!?94hUsZsd#d%M<|bve^Zbn0UZu`nxD{Vqu+Q{$wn zkN`pHMQ?`_Yi#9*vH%UVuf3#f__pkoT2b;G(?=-vq@%{V-r0;GobJYTPh zPFEHi5_KofkQ#F6_+RInK&Nz_Ybf@K2+Cvx*a)N>Gm0v>2;fpY?O)a{gXL-o3s(nL zLAde+Wr=XdjH~g1_g0mxd)a7-OHu49+uwl;73I#4S7Poq+D*`5UA43u>)!(v> zf+<<@`adbAf^$52T`;Ki1YAXMrVGR~)kw=^S09SWD z!-$w7_-C`LTX@Ns41z7*OBF!G4Y)Ba?5S+7Q{$_EuLC1|QqFJ9l|rGzP=<);8fRL0 z3PxZ@Q)3&pVLM+H3|>VKRIl{ySkgDt{ej+LimrIN%_lfyYLq#*==B9D_LVgje32uQ zS|M3ROA%nr!@xI^CayTAzw)k!L*f1f1 zjKR&p`?W{T-&rqQ16fY{)a@Mpt(0Ss{#CZ=d+Cu0Qicqyw|~KnVt#Df-&IPWi{Ox# zr?1YCs;@Ua{NrRmY5btth>(r>RjJAEql>?>#mN49WFN$8m?2j>R6?~Mi9E5_H(l9p zO^G{+w&#rwuV&K+6PEp{#~j00_IP6jEf44%>m7?ct=t6QA+!MB307=_D z+j*%k{67{BGE$~%u@234iN+IH<@g0zs{ESER-_=4(@ImHgBhb|eV+}wK*sV#;DROi7AK&DH8B|tn;oIPeb?M}*ZDSNc?t_bljJmF{E?!HJ#U9VAXJF^>Av z;k3u}OV$}j9kRYhr!BI4goAaQ&hHjSkW^+7fx2GG2rzACX2vuCZHBZGxN=4z6I^l- z_;RzEl>>$PD@a^daxl3KUE@oel5)yfxXRM0C`X+mvvUv>FBtJ=;wMJ-j(XrpwVYP< zZ{eV?2)_6=(xdj^v_{Dt9)97Mf1X-#sA-4W5c*SYj84_o<1r=z`K_UYAfd%ZDhZgF zLFgDB);$LIldFzq&~U-#m?jnb-B(0pBt&Fn1n3iDyG`{U&lJZfaCq#(&&a0+htj2< zG%&Cn>@@#;;Ew-nLJDxRojyk(4ZwhH=C!@i;6tH;c z4kgmCa2Oy` z`oW3_<}T8_42Q$Y(avjm`NLyg&P)f25Mxk}ys!QUp68Lq{N5 zezsEcT`tG#Mm91EhJ@tgLx9C4ezp_+;uV2qfD;Qs z7aBJfeghmxn+2rAq9dJ-zR(%aQRDZo-`bV_wC_HinL)0+(Ag*s59Wo|AR>GO)CK7N z9mEnVz!r{=J4UmtU_<-x(L@J3A zy1Jmb&=sSQkbfde_g6<=hDlH{-B5w*Z7LOiW}7^2-9B8MJYt<9VD1M12_*o4e(iB( z2dtWf19-6ktPz7ET&P%$Z=YNpuPTkT0xtF0-EMyD71VZAmZbQ>A`1xyix|g61ORhw zQpM0ogrLl8Yn7-Uglyl(Zoh=hPyS35zI)nEJ`Dvy_`_F95kcjk9)JwCI!cm~690TG zPwsEMAT~ZQ5vQP5Xt?{|lO1G?l1ai>0TL;TOK1?|g@ADk0=ImrAYcee12FC?1~s3; z<=%ex&M4DBEY{LB&K_3}+#_M)p{E;$Z$z~bt+$n`x1E(?cN7R#JOx+>$bbeupanTB zc~g##+qi!JNDIt#=cBD#qy3=^y{hR;E5$rs8|>@^zoI!b~6JR!*_~# ziTfYy=dkMvO0rrP0bLgX=y8^|HS!V%`6<+&z&=KwE7@pqVytJsO33zBX5tc+p3RQ| zLc2nXEqJCLCJMnL>8dxbK58_f)T#K?2B1mjN3aq#-@o1oZ2)@()}&f<5Et2zJEwqutM`mtrhj(_4dy*R+Vf5<`#L;*b)tqd8xaj zVW5)ZXy3CM;W`sq`m7HRgy#M6bPvZ|V;8G@Y{K!>KjW~YhP3ZXiUw(L6Bpx6H#&r6 zP>_)Fy==7!}(J+ z0c7g%;3Ys*MM`HKg=)W5<5-|=j}oc@k3x{!GKq8aW?|@GEgN0kI zfbxeN|6U#+Upl)!Ck19jEEVQDPwbxGpJx5e-{+K&4Eqmq`0xc&kFwdP-P*No`i;-> z2*(%b-OP&>K>DBliAC~p9gzJSQ2e7hK$BXd1aWwR=6|ild3wsH*Tfty_?RJtN}BfQ zc{BJ&3!8EIpDY|?PK+Gy_KZU65sQV`uY32`#_Pj=IdA2rGvkFxG%nWuy97Q@{;{cO6cUG zC&h@)L$>Uu3S%L@TMT&0BB?cAUl>ES1aF}gF}zHkxwY*f1iinxs1i*M^h0@>g(;h2 ztu(dhR!}81I3K67HNG32a<@bwHjW`aj68Z?? zLx(ZP!ZIc?fcA6HDat>AkL8YVpVKQ5*x6YeMa>h(GYSp$Bi>;_K*p(RX6rk12vTg= ze&9Q40_Hud4)DZ;pNIX1_}h%dQV7*siaT#RI>v_kSNiUC|IY>O-2}El4#>hdVFx0S z;J9O3wGR8)9)oy;cNnBD)5~Br_m&nxS2n&di0*5STZU^%)mK)rFho5WJ>PG+M~MOZ1K-`RI0pUDY;B!G^F+1 zzi-MzXjZwFooRZ9EUJs&`z~9(0lTxM-Q4ULK#s~Fj^~N7GeSx@>N>2yQf7Cf=Wj); zyXo0$LQlt%$%lc5gK#E`y2dQkO?n3xTL}IyQ)jln&A9vVB&zkK>bE!N8EUV=PV7)} zio~{WvxQ7^Kae=Q9F&-K`1k${Lk(&mlX4>b6;7BL{c?lBNY@TsQzBI(F%xaUsQKYB z@WPic@pzxV$im>O_0wVi8&BIpl6Z;6aPni@2wNq7lpH$}Qa-tG#`ffI{PyLu z4QL27)Y;gJoU?XdsqWc=Lc?%z_m_@MOkFR%I!xzzD0++eR-x9rDM7R&Mu2EXk<=h_fvP? ziZ-`gx46mJJ)s^$>e&9!>B=f48_`rFYwfp^3OuCQWKi9c4#zRrK*)xjK`A& zy3n=mKfvHg#j@Eeiv?JU?YUXeHB{03A@|3Wo@2j-%~VP%WJZlI5`O?wKSW6eH_kQ* zbuE$=%~l`-JU7b4@<(9COqQj|_2cFC`!JmS)Sq*r8m9A)=+dciQ9xa>Km2@2#{;%JTc1bEl#2w!A z;6xQBgB8DigN#3TN7*eX&)P+MuhM3^&i7LZl74}!vabe9+=&-2AU5D_LP-|{98KFR z^bFlyj6Qhm&3e1smBhpyXW6YDq{(y(h0O2blS(lYRR-=D3fy1COzj4#^1tWb_K9p> zB8BN@UYkVKB?{WeI6avi8u}z`^^8H>hhRgT!UKMyK>~|(f*noEf&#u^y2ceb+Ta8A z3Sd_=(#`?tC`OUSW85)@iGYb6``o~7BOLvPuqOnOoDF8r4Pm^j3|2Yej(jKf}(xr1bU!Rx{IZMX^DOm08IJ7); z82Ui$y9)&rTFe5zABz06wtq_g6(BB^Z5~oEBCvCGm)rvMtl2*Z2E^H;?CO9*EAuL+ z`56ru2GD+>ukM9yuL@0YnLMgb$R#0r(E2VIr7>KHjh)!19+lt*brU#i5gqH6MYUIPXa9uJZ^esRQfH%HnF5S)_&HndP`mf= zhIv+G)DtxT-(W);@1iQ8X1U+Lk*$Q$c1d_N-gI=x8 z&zxs6b+7w4lymrW;3;CbRoM1mXQpwx}5HONnbW;;e>21&+)4JS!CB1 zp);4ekWUG8;e<=~?h$Gp;>_`Q_M$l(LFb(EQVlqf`|t>5dtG3PPA(sJVn*!#gnZ*| z-J@>0R9pOK;x{3_Z4Q;p}c%GGA8 zrgPkN)E5Hrcr=-cx$Y!_sK{%|sFML$XnY!1T^^=wX_9aM8R>h4nWBK}#`Y^VD+dE^ zN!^1er_t+ECk_o(AGtg-qGC^m>i*xitgEGXWNk!p^psBWg{t4P3K}P9C>x#0huJE3 zzuzI(G8T4*m0}$5SeGjmB?~vSA3b=BD}n^DB5rB+%!xH9Th0St1{(=>)EAgs6MejSjsiCr5bo7%ZNy_giow}nqo^51q_B+_YA~J(zRW6rYP{E)PLD! z?4h@@8U$$g_Rqq8y3cs67ykW_m}U->ZBMQ3V-f&O7{r=DHN^q9sY&d$=y0#_;0s%8A#E%tFk+>fTW zRDS=I?P-I#f2+IwbIlhkO|B0pnqOc!1(@zoQK`qUvaF|SC1}xh0cB0LECLT*UGAdL zQ}X*PbdINA!C`-4lwm6DNNrcsXI-Le0d?OVsy+qkQLVfc>X{`gx=QE4;Z4Dl^* zTvVd&_tXN=chrd28S2eT)r4M(!RcZtp%zf+BlJ#PN3%truEHZ?k8B^IF~2EJ`Qwri}op4_4SEVsswRp@nXA{L7rx`%bMepixHlka=4uBz4K z3X$Pw)#Y=HryHK|yX{Yndh;XM@!TiF%C~@~{FIJMd<&!A+=&Y9uNIwQWH@m+eHd7! zWJf35XCrSHZ{6GJX$F&h7jxnVgw9fGaKiV8#k?_g@?Q2IAe}v>CeZtw2bLxaJ1dsR z8KOZ}uTq!7O5biruO5gv&4@dt`1tnEZe#@WU#48P+pmo`*f9oLb}PO5 zLxalSV~V>K6MWYArn}hYT2Jrg5dr)b%Vq|%BA@Qo_MUIk--h8X>aG7>L{^!%>wll} zxpYP3`^&~}2k4RcQQqr@QeUXHk(Nmk79b2*Zz#KF8QQ7|T575cMv6KDF5WDcBPwRA%pFyg+ zy8W-9h@F%Ce>CB23cY}+V&oCA#1;pK98mq#H7n0!A1%|WO0JGh<1)kX4TMwAD@!Hc z>8EM4T=XIU^b8>6E%9s_Q&iy!J%+Czzay@|%4G`XyDemfCVVK*iDcX!tYJs3vB_kY zVx165rWC69%>D}U&}U7j2YOk zL_v~w;+LEw;ae{}XU#&rzgLnTI`Z^U9ocmuHmZ*r@6OeySIBxd%z11ibosQ0*8Rpy z$HLDUFws2&nYE>aeCqw6C>ICHmtBb~nqn98?6SQ)b>X%Qi>}oN^1CgCDXR^LUK?vp zuEakT@n}?~53g#DcJz!}_={4BklK14$t3GoHwEa*Lk5j>#V$5wzfg+ugdW?n5@^PI z^pe;DZ+%QHACbUQzE32pWP{g&UQ`?^yyB@$IhAHg?v7WTSw&yMbs=Lr-|0ewP15PH zofLXIeiNrLIIoSVGzp4Z_4ZY!!T-|^J7>8&SLg9je@olPL7};L0bNFsQx~T*S;Ar{ zJaN@wXeV%+`-#)b(F64U{)so!7f9IeWiA zx6X;AVDqWHX~?%w?54d^w-LNRPgFbxBO7*t2A4W^-%BxDBWo(-W6Dz2I){>{!WWSYe7 zlInc$O`N;!=%58qD7SX2bS?|NUt!T7cJ`(w4?HGCdiHpV5m&#u1nbfDH0dK@!gQ{3 z=gVi>=_Ht^oxEW3v}VPVIF6_~G`y)2s{E|LEpl`1eLDZZ%q^+_BGx z*2e9|I^4qR?#I}`g?~GPE*5ES4ZUvV{(E0fpbaXVQ?u~xvy)g!us%-jvyEyG+b^^R zbdYXLDEB*|tYU)HXmiiPfmyB8$48O=V0G+_f9o(c`CHZo=5nd13r3^eq*=m+(L+0gwV0QSBq{a+!^}~Mk+)YR?_)e zSmW**zEA(tj`+pIJS2316X2;9#IQBpj|2jJZmmy2K zlNBN>YhmdIAsO|A5PUeuXn}gA*_>1QrCCDH-X5uyvGG^iKeODgb^4TVJ$wu5Z|f|o zxmLj5o6@pxuZ3?-=%B1*=VPFgFO+iq#R7hoOxsI3-^pomy3?r@U$CT18*V(yVE+n2 zUJp)iP-*)&y1lw6`Q{k##HMSb_A9gJ@R|Axwb^u5{6&c z)!yQ_r*1s{(f>O+-Z1*ek`+&^Nmt}E>(4gE4zg1?(};ppFE#zou56r+MmRA}tB?3# z)dkYO3^_-cxI4Phs_LniVsk@y#ko4dlJ#P*Vd<{PCg9x6aSVkQcKP$lNp{ehi^C2~ zV2aZIN6m_?d-Jx^yUX>wg9^3BNkXM@ci(Ts%SsG&x?UN!_iQ~b z!!GxtBt;E=LFeDuT|c1nCyR{mTk)+qf4DBUO}Yp#Qgo&FfkHc;+ohJUV3CDgrhqGK zlptGv>ol29B@Zbh5}KL>mR78zV{^>A$IK2l9n>go%eQ;aHyg2gOr3rZ(HlSZFoW=yU_`q zFM4IQZCZmK@O7|!0E;&EtY!K&-$thftXO&uR*J>PPo@+`CvhUwr0Vu+9`|$T;fE(f z*SHeB&&IUq)!o~%%CuUi0ZTjh1$~1CyTwC)?w{l1vbo3J-qH4|CLV{X)2M49$m~XW zM5AD-@2QY4;Fi(xR?`nY8IUKAOexCie3Bk0nY8$Zvgk6YUkW~MW$XX<_oxJRjyJb? zg~8Wn-mwN3v&N|(m+!%J;=ii#$G`h&6L0w7wbr@SfZTn~eb3L{UrebRcs_Y=rd!na zJf_0DlHY9?A@2#a*!UG%jtCY{81=ij+k(w}tQSv*ASsF? z;#?k!OvV}6YU2U!wt;0#hRT1|=W?y`n{l5PI|?Tsj0O+S5$u4UZ2iLDd3{;=d6*_3 zx|#|Qiso zH+a2^YjntgQzERApTYfup8Hob_irK=uHRq)z{}0U&B4vf!NaY^%_G7iEW!sP->0wv0HqIVauqVB!T%4k C%sA`- literal 0 HcmV?d00001 diff --git a/plugins/cordova-plugin-camera/src/ubuntu/camera.cpp b/plugins/cordova-plugin-camera/src/ubuntu/camera.cpp new file mode 100644 index 0000000..c58af32 --- /dev/null +++ b/plugins/cordova-plugin-camera/src/ubuntu/camera.cpp @@ -0,0 +1,140 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ + +#include "camera.h" +#include + +#include +#include +#include +#include +#include + +const char code[] = "\ +var component, object; \ +function createObject() { \ + component = Qt.createComponent(%1); \ + if (component.status == Component.Ready) \ + finishCreation(); \ + else \ + component.statusChanged.connect(finishCreation); \ +} \ +function finishCreation() { \ + CordovaWrapper.global.cameraPluginWidget = component.createObject(root, \ + {root: root, cordova: cordova}); \ +} \ +createObject()"; + + +Camera::Camera(Cordova *cordova): + CPlugin(cordova), + _lastScId(0), + _lastEcId(0) { +} + +bool Camera::preprocessImage(QString &path) { + bool convertToPNG = (*_options.find("encodingType")).toInt() == Camera::PNG; + int quality = (*_options.find("quality")).toInt(); + int width = (*_options.find("targetWidth")).toInt(); + int height = (*_options.find("targetHeight")).toInt(); + + QImage image(path); + if (width <= 0) + width = image.width(); + if (height <= 0) + height = image.height(); + image = image.scaled(width, height, Qt::KeepAspectRatio, Qt::SmoothTransformation); + + QFile oldImage(path); + QTemporaryFile newImage; + + const char *type; + if (convertToPNG) { + path = generateLocation("png"); + type = "png"; + } else { + path = generateLocation("jpg"); + type = "jpg"; + } + + image.save(path, type, quality); + + oldImage.remove(); + + return true; +} + +void Camera::onImageSaved(QString path) { + bool dataURL = _options.find("destinationType")->toInt() == Camera::DATA_URL; + + QString cbParams; + if (preprocessImage(path)) { + QString absolutePath = QFileInfo(path).absoluteFilePath(); + if (dataURL) { + QFile image(absolutePath); + image.open(QIODevice::ReadOnly); + QByteArray content = image.readAll().toBase64(); + cbParams = QString("\"%1\"").arg(content.data()); + image.remove(); + } else { + cbParams = CordovaInternal::format(QString("file://localhost") + absolutePath); + } + } + + this->callback(_lastScId, cbParams); + + _lastEcId = _lastScId = 0; +} + +void Camera::takePicture(int scId, int ecId, int quality, int destinationType, int/*sourceType*/, int targetWidth, int targetHeight, int encodingType, + int/*mediaType*/, bool/*allowEdit*/, bool/*correctOrientation*/, bool/*saveToPhotoAlbum*/, const QVariantMap &/*popoverOptions*/, int/*cameraDirection*/) { + if (_camera.isNull()) { + _camera = QSharedPointer(new QCamera()); + } + + if (((_lastScId || _lastEcId) && (_lastScId != scId && _lastEcId != ecId)) || !_camera->isAvailable() || _camera->lockStatus() != QCamera::Unlocked) { + this->cb(_lastEcId, "Device is busy"); + return; + } + + _options.clear(); + _options.insert("quality", quality); + _options.insert("destinationType", destinationType); + _options.insert("targetWidth", targetWidth); + _options.insert("targetHeight", targetHeight); + _options.insert("encodingType", encodingType); + + _lastScId = scId; + _lastEcId = ecId; + + QString path = m_cordova->get_app_dir() + "/../qml/CaptureWidget.qml"; + + // TODO: relative url + QString qml = QString(code).arg(CordovaInternal::format(path)); + m_cordova->execQML(qml); +} + +void Camera::cancel() { + m_cordova->execQML("CordovaWrapper.global.cameraPluginWidget.destroy()"); + this->cb(_lastEcId, "canceled"); + + _lastEcId = _lastScId = 0; +} diff --git a/plugins/cordova-plugin-camera/src/ubuntu/camera.h b/plugins/cordova-plugin-camera/src/ubuntu/camera.h new file mode 100644 index 0000000..6d96038 --- /dev/null +++ b/plugins/cordova-plugin-camera/src/ubuntu/camera.h @@ -0,0 +1,86 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ + +#ifndef CAMERA_H +#define CAMERA_H + +#include + +#include +#include +#include +#include +#include + +class Camera: public CPlugin { + Q_OBJECT +public: + explicit Camera(Cordova *cordova); + + virtual const QString fullName() override { + return Camera::fullID(); + } + + virtual const QString shortName() override { + return "Camera"; + } + + static const QString fullID() { + return "Camera"; + } + +public slots: + void takePicture(int scId, int ecId, int quality, int destinationType, int/*sourceType*/, int targetWidth, int targetHeight, int encodingType, + int/*mediaType*/, bool/*allowEdit*/, bool/*correctOrientation*/, bool/*saveToPhotoAlbum*/, const QVariantMap &popoverOptions, int cameraDirection); + void cancel(); + + void onImageSaved(QString path); + + QString generateLocation(const QString &extension) { + int i = 1; + for (;;++i) { + QString path = QString("%1/.local/share/%2/persistent/%3.%4").arg(QDir::homePath()) + .arg(QCoreApplication::applicationName()).arg(i).arg(extension); + + if (!QFileInfo(path).exists()) + return path; + } + } +private: + bool preprocessImage(QString &path); + + int _lastScId; + int _lastEcId; + QSharedPointer _camera; + + QVariantMap _options; +protected: + enum DestinationType { + DATA_URL = 0, + FILE_URI = 1 + }; + enum EncodingType { + JPEG = 0, + PNG = 1 + }; +}; + +#endif // CAMERA_H diff --git a/plugins/cordova-plugin-camera/src/ubuntu/shoot.png b/plugins/cordova-plugin-camera/src/ubuntu/shoot.png new file mode 100644 index 0000000000000000000000000000000000000000..c093b633c886b1ebd03925113c66c49ac53f50b0 GIT binary patch literal 14430 zcmajG1ymeC)HOJ`1$Wor?(QzZ-Q6X)I{|__3BldnT@xfoaCe6=xWjfn+ud`%{kIQ{ z^i)+>SG}rt-+i~ERX)ieBN8BjKpAy0}-i|InZ4gLM z#M{Nx+}_fi%*@i-)=7xsqO+HR%+^APLYqs8Rmnxd(#BTS*VR(p_mhUXue~{+1%-$( znV>g6(14?*yD6Esql1$hzqb&@f3(XFeExTug@Wuqin!YgQT%78bd*%cB%EC>$+(y~ zn9Nz(*vPoKnb|nGxVhOF$=F%h*jZSCKW-*APJS+Kes&(R|2imutGQZO@vBKn|JSvE zZ$cC{?(Q!9EG%ALUd&z`%+9XXENpyyeE-^DXJ-ORFuD0Sxtn@3Ik{2(cMFo1ZsxAG zF7CF@PGtXDG&OVfa2KKgditNY;OL^H^gj(dx&7Bb0Yk>(ZR*0p#>~p%==krx{-d;; zyPD}m^4im8L7v$=<( zrIWjyq!0!03$ul-1;3OuhoqD^yA&HcJ1aLY8yhb>yO@-;loXp3uM{tjIQxIM@xRuU z5NBuQkm6$F7Uy7NlL9L8a7c=?vWfF?a!80v^89yQIVU%FQzvuF|Guv6zw7>IUC#ew zU498yOH+4eR}E)phyS(!6&q)FXEz&X7cvQTZZcXWQ*&FVe<$evP0)YducW1`t*51h zw5zit*?){MzwQ6h18J`RzdQfWx)%S-sIiLi0=CD)$;$KpF={M8XITE3$N$4z{`(YQ zga1DMkMRRv{%84EIst3O6<8eN!jgp`5NE8Mq?m^H%9$aYj)u%)&;8#9Mp+gdXnRG* zyn3^KCq^C7xUwi}JK@55Dmz8Cbmh1iZ)JYk?__Ddr9@FRKl{!>+@L3H5@6T|p8a>#{LP!n zp@AO!yv0J)rs#m8xZtt$s|%h!ZI>)t%38CF;-?A3jYf=%VI$-5XtE%se(HV;=y&S7 z)+LKP$>6+9=_#@f0*$+oQY^p?LT^OaCpoVGimtF~dQj#4(1PsV3r--uoG%TQEi zg0^RKjZ zbgV#FyFgEx=;v%ohhOfGXXv8<1IkZDwU-o(+NFjf+Dk!4Gy44poc~6bkJ0W(T-JwR zRJc$p!!a={QX$`)9bo>HnT>m1cGlY6=<4h1ZOhBcPcW8RH2NYV5KQLl&1I~Ojg4Ea zet&QG1CF^W-9~zEm|_AR705?#NJdgNGwAOiJ50gQAQ*5_Dj{g2Qk$jJ<8(pk?&jtN z4|d+74`OcO;o;#qDJkjwY`O7}P1Z9cinN9)#BvrRMU4?fG=w@44hF{O;rV&-3xX;t zb)-5Sbugk}sHWTDq+yTm?MVg&X5K(iZXk@BQPCgt$9BM4o|Uq=Uq{BqD!$Vh!$M_v zoGsP&wmPnQKKF${O~Jf1NrNk}RjaGu!D>#0OALH;OTodQd(}c|uA_x&eF;`0};2vk9#RntU88@iC8B)!!cewjw|lx8ODJ= zpa~<1C57gG1|>Hrxl?6Ob&?o%=w#hdnv_W+)%#XuEScS!Wa9Y#TsQ(|mvjQj`Sst< z3vQ6Q<_-vAir07VS5i3?9E!in%pYZKw4<)95xK`=g$!}gvBLt|?=w*dshdIXul$P1 z3Z=@qpMHjg*^#SmJL@6uRxQvdH{k?!%g#$k=rAzA6szdWfaMv|78F(ewF>h!D*UyI z$IOusk!Dg2P5Am#gxK0@PhmqMf51I^Kj zeJ`VqzBP;U@=5wAD+t^VH=oX=-vWJB5QI>nLWqg!=6Et!j=kL7s!fkY&VA*xeKMm>wHqGFeT?VlnYGRI>bNVFw- zgX@R;Jb8~lVzXz{d3gksGVu=kySuXmfE77I^>H7NlvPz#9VU>9^uSv&b@)J zdb84aWU<4LxVRa^>5#egSVtrzB%UUe8H7;8{29oeL7RDEVV?$`i5_S)`g@BxOcdR* z-&$I!b^(ZELa?tHcN zr}J`G`#14?(bw(%sexC?weXcLA2)WF>sKig=tFN?JpYI+S(Z3dtSLg+P}(Zx0?0R^F3g`_uD}DBY%e{tJai> zBjCbc5jnh`5~&S&f+gMRpXxtQM0(W@n+mcyoXq~L)@y2Re*H!o^isdNmOPaT+2Y}044Lj&5dI2 zZt>|4c)IQ(;C;5L-3Yh?U5-`2Z*dVce^_yV$s3zt2zG+m(!Y$<2p*c(Z?G68ns(|3 z`u6AOX;dlLVZxk~6-Cj-1q=gzMg>)B$GoE0^lZppt+qNVhZ-}-j{yB*C-~`@8609v z@$r~Gtpa3F^BRN8(xY3nB8Dic)4&S}cY*;sdT1a%aIf^8la1ha*s{po(F|oFTg-vi zs!NY>*`x;OoeUg9G!9iO_A2vT24Nod2{Jss2J*e86$)NaZxQKmYS19Z81+5_P6V|z z>+x>Y`2uPaVLX!J-*-~Uk(H;ye?BDff`$ds( zyC6ApI33pql5)E0pIHV)PE;x2|TCJ+^vr-Bqu|Z9MOgxc~d~iJf#PU^qHvh6=Z=ktT7PsSz z!s-KwkS{c;AR2o3YT*b*c#iDxbp={HCYsd$}p2onuMtAoAnX>Sqt5Q1wIsxwO2;c!5tBWZPuAeTm$}*C0*^}qWAqR zP(>AT8a>2ZV^{cXiQx*oeNmxV`J|-_*Q;G?B!Ma!jyj^2o1jTc;cXlAdb>!e5Q^G2 zoBFmP>PHN=E4=gpdlCfy&JprF)6s@_h`O2CD(-?-V<^89Ypj82d~)*XvmPtkX`d9| zt%$>8+rh1mBBF3Dlu3y1OU{uAj(^#Bfk8Up(QS6!4^q-RACbS<=nkV87=**vvPR#c z(M9x6pLa7)<25m_U9gc~Ye9MS)a~><*LHh<-t2&W@G060x|xyj8-^#{!R#aStkG*8 zYp$Ztr3-7i_FM|VBl{1-5-GtS26FFS=D}Ra=Hqq6e^YimrfT8!2J=6WBs0GJ4VpkFS{E*pD z@c>|#I2SLk3#R?jlrv%&F4<`sz?!j}!k6!RyiOOmz&aBbl(DjbO?>^hrR zOCUhItR5$GqYCLRTh>U+Z=o30W=u^@v?btldYz(IxKeW4{pa5aTTr>v-oW~6Kkq@|=OF^5Wj|j4B2NJj`UlxI1v9j`qjSX^2eo2sfsWt{STaIf zRr7(oDH;;*0AH}phck{xak`10o}M1>vAWidjO}3%p+#B#%^dV@V+ln%a#~$h_6y`h z6r(9@eIfF&75327)Z~t?z70`w;}&|9Cbtv8;EZUJV|05mPsng*+T;d%=Eq#TO4Z-} z2g|U|W~RW(F(Ba8_*T@Dp4wlJQS6siLBGOqvhyeK?*^j{08ANe20ov!zIdCZDMK7# zC7#;UTc4eui@?11QdoHLJ&C}nL_qVLmTZjf|o#2XH|@7Sko{!2Au zJ56V_1erg7kB{-GUdUFE1$?ejQ+VexBMo^hc9A52!zjX#N9*O~OuOgsc^Wa^lWN^i%g868tw>umC}%t2WeNyo2ZoU>g0Ux4};^VTw3m3(2Gkq)n%&IpHD`yZ?Gg)$MO2%m%wcq8vUmLF-3b&v)zE{=LNoWNnBjaI=9WV zNz);+6h%^M9yW_tnG@j9uLLoO_l>)KJ!T4xqNAf#&sV&bf`1|kMc%GoT@xh?C<={eZ-_CSo^&8 zDe#$_W`9}IBDQ}hTClaG+vmEZ#EbMD9@H!Huy9waxHkh@S=Mx(uSh!swxD*6OQV3{ za`n;%v_UxLX%#dW2lwZ@^A=2T5qLg!AzNbXuv{NpaOd`HM->qX3V{_qI zj-r*#Aqp(`-#NTI0dY=2H!^cL+UH#aZv)+WGbxE}4gf{}O3lu{K{b_67MSdjpmD6w zs$P+JusrhTU&`vl`n(fyFxj9Q!O7pO=TDt2a+DcU%z&8{!D*nbpzA|8v20p)7*-Z@ig zm2EZw#Z>$yjVyNRn~$q{MJ&b-p`V!Li6DlUM2!s^8ZLPP2ybdl|FRIc?%+QnX;}(i z+!2tkDTK+l|4y3@zGWdxB5^^ZOOAmBJMrhAmysP;n>WMbLkA!1+^u0_Rz|a^Z&q&r z4CEXg5E&B_(~H-cp};t%6Y~9nwgK;&oq}SAPDG`N`5C&?ZvJFpy~D$?)KXU(suA_K zXw$7u;mlYQquCW>tHvn7cWkX#?;};3zin7bYw|sQc14K~J-WqjL!&AB zes^csU&9fzv3Gx9;qXaf@qaXkYN$YeO#=cL7MKYa{yPdPza_1}TVj;Kx7@Wh#s-`^N zS3FK$pa&%1xZMC&YgNeaZccz5MXx;2-`{_|#c_3mB3wxs2CMibI5J?E01F%2BiCe< zplQFav^)XICb9$@+4s|@zq88JpMHRM$I_-~1H^5s5U(dOFvBgQFUXY;lodG;+%8?m z7pm_CJWskp*cFX5YFq(UWgYb7jECxU$Q(C8t+ZM|xvk&oU}#jSRgDAnbno@?X&3^4 zy*|cg0;h|$7c^ULuzT_5H#s>u)#0dxg07~frX56%Cib-1>-i|ug^h|8Y$jC(AlA_h2 z?yCG4%qSs#zByKx$$%5}3cd+L6$Wq1dR!J2di`B{gjNjJq6%M~q;iF`D)6h9+DPr!3kLC{avvWb=Ql|@9NE6T@ax9cj&J0~Z64;5vbd z$7*6|X0}5NailBR)|}X&Lc(ji_K^ls8B%j3_-CH;PxBhA;J+SJ{1sjRim1r^L*ei| zD*2nJ1Qhrk+{pfIBBn@qz?~pgJl_RJwRIU%AQDfAzsPuAEibI7R#~y@SLMBXNYSA> z&g6@ZJV_qzjVazYY5DGZ+LmK~b{LEsBT&a^1|=^*GkzUnOuSF|*kWR?I6vEmgZvA+ zV?Kn6)j-@N0=rs+{+tQ=sTLQY(P9H&xW?gp5*;lq*xPf4ehv>4LsGP+m|RdDX}#jM=jI}4PKD$IrWv7Cc1`-ibRL|`}@cj=FsSzaeUA@%-#KHU)+7R zVy@0Z7Um#jmS^kL56?4)5SBYj`9xVzji{Gx-MKO%#Db#44lkUfFxBvJ2?hFBJLOo% z$mEVUH%l^}3RBheU1KMqtH~3+UCCvzF)bD}qLHIJt^4(=Y0 zxYJCl{ga;6eHukX>NiCrnlU`|B3z}EwGc34{h6Yleh74WK3A+;=+&Ub?x1%yy>E#AN#~(rlQSK#SS!~#7(gGiv9V;n{3F0JCnGgm(9DH?+bG(I6r3Jqbgbx^FoV68`ph>6q0y;}0>MD3-gedJn&+`*zQ_kY(nDRcY#t|Q@Pr)}ws zSEuh=el;_jX&0>|->oI*nQujGpu{+hV?hY(kBzwX;o{&}rGf-A*5Kp>9}?QFQg7(t zC@8+%o-NOAr80dYmEO2kn^Uz_pHMT)+K3xxHN=?Y%&~{XWr~J~7rSr3I_leKL_|VD z4)$_!sYAyf)L`3+fy4ln^q<6MWn~c;2eA;wec@tYU??WaOOdRRmy~>%-stx8KyNnh zxG_E8jW9<+SX6+OIyQFu8w(+Gy7xC7nm8>sHr8Scj3L?d#f$}_E2m;nUt#k1?*Iz_ zGQ0VT_|#vHF~|7$be5oO>kFx55_A%hxl*r-$z&^?adwJ4Z3{A)8)}r$dI2-KLlBK< zE3KchlG4Wz7XCiS&=ZOm#>{c5{8?@4O6L||K6TRAh4KjrE)tvla_3r=~;PXUL-vB28oR`MR4EP659F1hnt9`ch$ zI(q^>TJaay@|AkOV^M6<>H~UyJz_(Myuz!){c*VtdzF~hX^-PS!@8l+!f58VQhmk% z>%>wIx7uX8JL&Pm@)EUvj`U~3CRf21w4+lNBgU`4j_bWXb!UM(qJ}sid-|i6+Fg}E zJ4iz{f;7e1a3q?CBXNX&dDk~3HKiG?;pZCxxoxk>9IKA2Egl(Y1E)o+lPaNUC4e(u z7sow8AicS~ESGmDS#OlTKtWP~)UvI^2=^RBfrmH9&h)+vA)~M!4ndKuvA8uV$i_Ch zVOUH!nz7V+r$Blsay$%a9p0iObiUZ#HAK!X4nwI%tbwbcvRtdCD1p~2`Q4b7=7y!&@|@bd)=U(nl2KoV=! zc~3wuGMn_CJSc~JMa5l?tvHBQT{`Xh4i%QvxV!HD5 z#4jZ!9Z075-Q?I6VD{`8XHd=pMg;{0E09Ex^d5;mCgF))xE}%JBQsvr0qX~1EUdlq zQ{M4PKRX~ZOS=o%f&4g{Sx*{(gXwlgqS+-?A^WEl>PSrD%MCNlshO-tr3&p=4JNJ5 zy?Te5xTd6FlHV9eLSNpe@XCq8{w`Ek?gBA7b;zbc{^Ls`ol%d&qo#i`AF7~$|APza z_Y!3BWk9K79kDRpH&W<(bEG;W*)BSAa@A;fxKMwS&XhH?T+xV0qx9tc{`Lw06k-lN zMq=*O)<{?seD)$`zJX(LkMa7GCG}G3@bFlh;L$Y78c*m4NrT*UNX@S-vX^i*av>oQ zpZxC6zMUT(9U09e75z*g-E0eZ)(RmjE55zIuVuJC?XRAK=UH35F9y{o^Y)7K>$hWDug;vCWLW^m@qtLtTP62O=`&R5FfoY= zeRa21wLvp8CFM1efBGjWSpgq;StV6p2JhIYNYUsa=pl)obA4tLDm4nl?3b=!o2jcgOV|fKHAlfNVnWK-l z_XC%IkkBSI$^#Iv@t`5Bt-+K88Pi@4#NkPe$BM3)0Xak=akLH(czAelR8*9xok2(- z(aIQ`|Mydd@%FW&%|wka5$7aWcxcm$iV8MG6^AP*J>`(uB+4SbR%$2qB@l4Q z-|!N8FC>}SYr>vh`WOC;Cnkhzp)$+_mHXZQy$F8dgJ2Gg*KDl9kRwn_pcUDOOK%Xq{CSxK@{NMQRrp$D#ME|xwA8Hd@D`BU;jHU_$pbR z+Pr~Wyk_#j?daOTN`9~VtA_GR5XpnvJecEeTSrp9J|;u0=??@md872$CR#KaXkN=< zjC!aFZ)eDV$zwfHc4Dcymk=P5!d9bTn2oJp#w8@|)ONTLc>xcWgb(F?Ss4i9&O@&7 zIGQ$9gsDpYOf6M8LvY3k5O*H&@Tl)aK*WX&4>p8`8n-^!8LVN(>pH>Hfp%pwu*bZJ zND2M{Z&^McjWCpj)nyqoycHVWC_A7_rDHK69`aK>>=I3XXjxj$K@M%zO}prCKZ_!O zvHJ{7^=5IH^ycobuiX-2Vi@}JDn-XD&CQkf^U30~vkg6v{5U(1$*Ue-osMiSL!zP( zj`}Rk%qYq~y4H7Ci%Yb2FIL+xqRZOb%-OXwD`ZH2;SR|AT8mZ~-5GS$aOAR!IJPS{Si`om0FO-pp}+!4bl z_-a5syCG2Mq^BrGMpSa-t+-@V78c?L4h}Kgj(VsCMq!Y<9qFvv3*PMZhZEms#T^1I zEiD}jVjV=yI!PQjCOr z@r|jw7i7?W@HlHDCbp)kJR6e`{LFPNzb@+K1 zCW$EXPx}Oti*tS;8-J08{~#5Ea}HXZPfzqL>TY7tu5m!37GuUJSQoS$OZ_nRi%+5i z8aGV+9t?HbH;EM`8;}B!A{{4ISBzC3;AS&K$Lv7@OCr%G{%{T_reAWbQC|aY|Hh5f`l9> zC@56cO21>)@A02C4toEs_LL!52Q2)1H1jLgzx3eM-cm)``mt0r0V}!kUayM{SOmhk z-+(R(N9M}GBi~@*WSph9D>X3@O*6XRi%diK`&K&yM2M-XYAwkNptO>l%H}vk5y^QW zh=_?nYIfNcpV@abxe^I2z0G7NSCEzanfQyy`4P~U=t5CZ>P~p90J%>;ML`Fj0yqwp zjaKL0^Ql~sUUj+t+K4dT1?UGph!FUfGHuv5fZ}xmF#R)#Cw}-8@`u$*gQbFg{cX_n zh;mP)`0?Rj{upEztB04EgM-7<FMd7W5Gre5G2#%z|linHYg`zPwYp}?FJ-n-j%DhD(MLy;6lLo zaJ@Tofu^SUC$q{ThCYAS__#C`k9b=fwW{?#)IA4s_L#*m0^E@d0E!06)b{2q6+wo| zC#ri$1mL)(ZTY%uPjqzj?hr?Mwj;rZuO7Ws&(@>KAIFDkh8dS_3+cwhb*m-&v`@lF z+d3)WNeMD8dY+x;0br~C@Of7W4eK^vBGOj?(5ywFb({e}Jy1H0T_mwwChoR~z zpa5V-dnR+u;C9|vLqRpcHl)!(0dzx$2KwE;w_pE+DrfO&T9$tlA#>4ocfUbU2<`EI z{Hh5okj@0LT5(?@Kw#i}zPn55i|yy?dKGKb?JJZg|4nRFL(@5Ns25O+tr~ZEllx}h z{z{?@=zTh=l-AK)7PCI{2A6)yPS?=`Uve1}jG5ure&}n(4bBxHBXham9*j)Thja&L zY6V;l$M$;cYBX7+Eqj~;Dz?*5mQB^O<*u%-SAf0R)Jw0YiyK1H4BQxs#_R<>Q~2&7 zMoBB%xG+^UoXw<@W4yeJiE;lfl0IRV!ci-r8(=~a9#nYi6AK%>J6ksAzQ_8U1K0{n z7F!rp_9m0VI9$58xcC~N>sVDj(`9W&?MwMCnZ^cVVB07U-f~kz4FeO+P5)%IM+T*i z?>7Lq2NO(C5n|1XDy;Ut05Etxcgxo5hu;S7*uWGS$lu<7SjZ)dP*_+z3Aphzdiqw)x(l)Iss zH?+-AY18C~fp`%P=y&56(JQf6`!tdF7tD^XdwUltC&Fh_|KAy`LDe`}pz)B+fxd&n z%_$N#ioMp&z*X%7O(CpB?~CsH1E?egOj&-!(T1%-fnXIFU5O;{HBF1d^3~K;W^aRR zmk|-EoY`uN;~=n8HyWHlxDOFX+oGlWL;6qNtqx_!kJ~QQ%?P@fQYe6OluP=I74u5) zSIi#mJp$kQ*#HR}n97maX>feIzu$CwYasQ`Z+CaM5FowUZh&qRu-(Q}5s%oHF=5po zagq^ljcKs-=LJ0q0&;^T3z!>(eO&{?E3Mn3!Tb5KAcHXU~ z2fn{jkTD)pSV4KHdCQrE#F{du2cgPPWrJScn}DPc1t+4gQ7604)j71Yj#m>*W(y@Ibl*hj$V$d`$g*YGmVdWHX zw6(QM!{8`{kEip6g3P|~2++!>1wuc>Sb z0NtxlnGdmikhvZf9(sLu0JM$RYJ7t%Iz&qRFnKroVFmIh&OmVaB}1v@o-0EPRKiza z>wG&F@^$y3TX1z?Zu*F1CtbVI&GSPzV8!HG&d%;c#Mu9GSR5~9TEEq4R7FHpjh;e< zN@BZdSv_Y3US_RT$T6whxjzWoEIOCT=-$dJ2Dduodll zVW2Pi%AH&gmj4iIB3!W8AwkuVT?g>ycoClXg;OEf8zN3?ZAe=U^q0agfoXA@v~qqv zKBItyc@2~LNnfounu=JI6zPYk)VE7DShoiWSRU2FNr(qefQB?s`={?!LoF#SwGMhZ zE|uwn7A*SeHgNJOxeq$eBOFB;`g>;u(YjuBXJ4ikHMLRZLX+(*1UCMrOljy0gsRQ8 zd8#UMHrW7;{&YD-7RtH69H;=%8#gf+3H5UWY2brtGw{-H%=kfJ#ogpx9dzSAHo@~b za~vH9h7=jL?)4ZDXy-E9a^!(7JE5Jnbu;0+kPn?bCTBFKA)5eb?%rAOca4Fm^W`u% z*VoSvP6gXQ6p<8=N}3L|OgplGRW0B0!kCQGs8F2~BT1)yVWC>qT8(=HtA}w6;PZ7r zI96=MUWf6Ip<3y(pQ%zPAa-QLokM;Q074zPr17`C?40 zJupWk=#7WJyS;r) zX#i&nr2j&e*)S;2xWjyzs}Om6*i~~$dQrdwIVvhnGy|Dw>a{K(j+iLiBh7WqgO|7j z&Yru}@s~YThX*jM@Ww_nutbfJ*VAEIng|s6{V+k303@|U9NP~Y1Jr33V)`U!>z#-A zO)(snyma9@C?szagrx!hgtSnvjxs-H@#D=51yvmRAq8DD ze^WCEr@Y{qNDy5XQjKC71`gXCAohB`jX=URg7l)xb|FT(rB~XGi68AWvc0O{bQ0Im zrK2s5OIFomu2Nvp4=A`qHN{U0?T?Da5YL3^W(>lj#OC!lcD~* z&2_-$n~eh>_aP?WkkJJ(a-nEWK@mmnxS6F3rvT$Gyy0<6~+Frak{6))1Tr&jJ;1$A|Gju7aL zgxJ^@>!}=}gnlYqv~7!isa{y^u&>QZnL@KRai-G9$>BB0M21GWTsS0x-O)Sd^1P^$V4kw@UEtljqVWkDR4miLV_^(e?8+N zrnwn3oE*Tz#N@aRz%)2++do4Q$rBa2kDyY9W9UTJ#t#^n|MP%J-Kb+9b*l<37A=ZX zG#5MXU%(C>s#& z@U*nH*1`<^MxqWYHDLCFC^!l&h)@}3J{=AHj!Z8=Y-eX`x=ooTf6GckbC?^6O1h!b z=CW-JNSx>?g!{guQJNS>_7@us%89CeL4X~8E1^ApwhzaJQKvBZ`l{6JWYQboN0J_5?J@F?e^+~cu+$8k>0_FIxMF0Q* literal 0 HcmV?d00001 diff --git a/plugins/cordova-plugin-camera/src/ubuntu/toolbar-left.png b/plugins/cordova-plugin-camera/src/ubuntu/toolbar-left.png new file mode 100644 index 0000000000000000000000000000000000000000..720d7f601675cb18b2394fedb47dc43805df7adf GIT binary patch literal 1212 zcmeAS@N?(olHy`uVBq!ia0y~yU}OWb=Ws9s$yJG8=K}>g1AIbU|D%HX`ue?l_rk@_ zoH+w$BQx~$^wibWAtE0?esp$r{`Kn@kn8X74$p2$-0F2n4dSGJzyBGY~-m3k$QOqhnfH8j!&P z2CS?sV8jaKv9hwVu>lDdAjt-1K^S3SVL)Sn;_U2fT3VVA1HsDJczC$^`1sV-)xh>L zNlHorodk3M4-XGe1ZXRel$V!>+0P7i53``4pqQ8#P!OmLA_7qWbOW3LbO$FVCr||D z5;m9%K~4k;va_>87;rMvh&={qeRD~WUoZnR3mZEJ2fv_@sEoXdnzoL$hnJVPZ*X)> zLRv{#d1Z5RTU%G}^yxEa%?5%wbLY;TH*fy@`3n{T!JNRWDu3fi&!$u(3v}yC^EnBy4+YSUfcI@1_YuB#byLa!|vv==4c3+`X zU|__1x;TbZ+OE-f7&?D@}I`tyzkfj1A}hA ze{p}`mMey*`;Qzt^gVyRYs%fmr*Y3;|K4f-w(R%P#5j$!X`fe~xNtD;dGPC#SGjxJ zo?kulXxG)OrH?F9J>S05J$G-n#E;VT&sNQ}oU`v_(aMl1zU#%J%?~Yjcy-k;$D10e zp$?}{?>qO#H+12%FqyeWEm~{rrf+_F<#_upr>litRmL_WDd6QSPj? zc{ygYJx@zQ&=DswmJ{49u(#F$dc1aTo3!&nxOj@;e3>@RX5$yD8+lTGOn1CLVcJE> zWo(j0DGJPzCmh&}CIH1LXFeznvGY@7?&c0VAk{5uqFX}8w;MkaH;5B*qJPw=sue+Wii!L>(~orHkuW`Inwhk;g`_W-pA?5cO6>|s+PVx zG4Jz71(yfEc_&|aJ@41^uigqqTTBTiKS!{^-dBiF&&F KxvX*PxS literal 0 HcmV?d00001 diff --git a/plugins/cordova-plugin-camera/src/ubuntu/toolbar-middle.png b/plugins/cordova-plugin-camera/src/ubuntu/toolbar-middle.png new file mode 100644 index 0000000000000000000000000000000000000000..77595bb1332aee9326f86e496a6cf8dca6724327 GIT binary patch literal 4416 zcmYjVcQ_kd-$v~{f*^JxMr^GpRWqb1wPJ5oJhUWM)vDSRyS8d;wxu++DK(<@N{1Fz zBW7Ehpy-?D`QGvUamICi<6P%D*SYWecaqIajo6q4nW?C#*pS8s7L+lK(#jd>DZTCx zpDh&?7X#8j*Xr){&*I@5R$jow@ew7s1db*ZVUFZfd^-8w*u=Z-N2!pHAktXfnVVnm z;xoC~Ajx&Tm~y7dL4ZRmD%cf}P)&@looywj*S}{uq z(nx{oZ4(odDGuSwLGPNHLg3uVHA#%s2~*n6%Z4k*)l^Sn#(TUL>z743yF1K^X)4;= zg-RPxbVn7Pol(;A$ONF=Lcm=+TW-F1I=9Z!QVE$6rurUKFU!-Yl8gOdOqxdMq@%CE z)EMXRKwNlF$ASo^4&b%Q7!(xr5v4vEHs2LPy>7~v36@XhzS#{v^^^u&WBkzVy4|{c zJ)fDD=0-fyO)p9$?|VA6Miiht>it##PUBE!?BdkjG+$;W$uA&nOQs4>`@W9F63mwO zg=sxZQ(jk&oJ}dzwD^e01LxEp(m{L!H0Lwt!huy0oCC@)Je6>MTxIqu5xJSndZWOC ztjf#szR45x4Rp8lW+o61>w{?(9b2{!7J3t-574>1dp1|<48oeEkO3nK#@@C(%%0nX zp4acAg^SEu_$5EoKQgYYcF+?Fg6IiNS~nCd`ek%>b{eBl!;peLtsNUa2+A=_CH@Xr z{-FzZ6=!r6(`81PpAYPA3er^$7xi>hfp={r8tkUeJ))zd;}%H+l$$H-PZMr;wzO2e z9Tx+W>v`b7hgvqX7zitTcPX|rH+NXk!d|M%fJN`GjE;vuF+O$wx!IIExW${#s;a8& z>2XsptE*jP-Ex(+ySgkNoN~}t6}m0?QHinEiLV)qNV?sZ zw46IAW!}d8l}@kbBXF&efE7_T^h22!cP$U+33=jwaG*W;lsMJST1|k_!Maa{-@px% zZ!?5s&T@N(cv;8n1Ephtl`lEmQ-G46DD~-#a0aE$6^^cO5e1Gy4VP~G^^3<@*?Q2df74GDAg&{q9fM7 zwjx(lbGXmV%(OQH`*f#1!rFU0I%Q*nnWJ;U-Xu8WM|jF8B+t^U>o(N=7Bun;KG6NC zsi|3%nc~g`{Wv#w-T||RnB>?QL>JepoZn&Ux&JmkIfwR`B`#SHL9U=5XCi>`M(i0Z zr1FWrZp#oG&nfaB6Jwu|w_l%)*?R^xH<-H(nThe#{rtp$M~rZVlc-wZ;fFubq)M^A zus`RK<*lv9A}6-rF0Kn?*Q&@;Eh}6vq50ZYH}2)!S?h~#f^CW$(Lu%t1cQT2Nu!gI zySI>cPU$Lf(odT3xLOr}lz)s_q@%}^j}2#Z*ax%5X(v!9w3h&x5EQbXt-y) z5_dx|dWs-hPxq<+Q?O511`ml|L$5ZYJ|-rnO_&SHm+~w7tkU+cNcwOY+eh}%TD`LM zPM`XT!N>fpOD_&YNOuAPULU4Bi+5D6uWGSp6RA`)gmM54 z*)vfjK&xR|=8sq0(16vk$9!RP!DGg;!G)L~hcTH6vGb1w)!LUQKLnGwH4N`S`Uhv4 z{hK9Li}<{Pg7)RYJcCDIn-C(gh5ry<@|7B!&2Y4g6zdwxP;24^0cW6#mdp(%QB|3dpFS4a z5#Skpn^`^SIeF%pUblh9b*IH?x_8i$pPw9y=3>uSGnmSxij^n_NCV|-)cF36fIS&kmndUU;(`SNZpioAalKykrcJ+ zv}6atzoRnpxkf`~dGKS9w0zW~9WP^k>7#Y>;) zNA*x&n*A9(Zjtk$K4YKw|4}Pt^3TG*Eqa*$S^n+%kL7O`{*UFqNrp<^a8Ui%>wgIW ziIg4w>-C?ozvKV^R=X~mUOYUXc>8wL_wuQalXP{Fgy)l=lZMR7zBCjL(N4SLykFG# zJrh)>Ye;S?%&0Uu^ER7_L+Hx(im|d%rNt2f5x7Y@IL zU57@n&h{y0Vs6cKte(Qjvzq=&i$ENlUNWsa$%8UwMSxH1DZv ziHyhNZR5BGlW68?%I?x&+JwzYyupPOctkCd7zs?u-?|LJk`vc?5xj;s7;T;F)YbU- znARXFyXDG)ZVg#oOrLm?c%<%GS!LpM>h*zWK&p`2aMLemDZiOHE~|oa9Yl$MTq>Z_ zhzbf6+NY6|?CtcPDcffTB=6G*gb`7Kp>9^@z(d-x47flfw-#f$F*}XV%k)ey!JZ!P zattTpAvam~fUtWU!SzJ(!v2MOoQ%mqGz$+9B|$j|YXLNn!EPQ=%vg*+jruO8taFu+ zOof(^$*9qGU+3NhVk(&|1cQAx+yHJ?c3&6{FVuDk$f?Y z<-NFUiTmjjgyO+U=YhpXp2IMr<&pvK@BKdfRmXG`xixp?ER6^Wp7@^r|fX(L;41YWTooJCIo1OM5U$!i)M0h{u|iwyE%gi3F27=J2d6GDgiyiO7HAa?Q!+RMaNC3 zvil&g*5>A1f5Ra@w$KdI1uEU|j%8qo?PeBFZ*!V@qEh6bYVlm9wyJw0#3APv>JgSK zj2&ogkV1hnOlU=}Mnwet_`IPjKJHo?tGBm)Zv!p$HTDV#tiXniFE-yCf+v2ynX^k&1U`QGq)ukI*LID*sx&1g%|vZJ9~Crd3lO1+74C?N|k<7Ih_n^ci02@ zz4^YgfO63Y1(S^sA&r)xb)p?9E^rB2vo6KHy|eCd@XDdtwASTalyQBKPxzCYbTsSI zD3zYIaDg*o+!sj-YpxQEY(Jnut~_*vN(#|NexH~SE4-DsA$d>KeOA5y2l$$*T~!7IXjHcj&|EkH&9< z%w>lvf92@nxO^WTi%4{7Y;#&)PLdp4Yz+SWSToer3XNv-slKs6gEzRB*>yA8&E*yB z1#?-oN={CWev-0#YW}bkT)2-~z(9OwvPj*(kRoUFS@;#qUZ%I}lrmhikdPq~Bn*+x zeEUk9J{QQav zrr?ZrgO|pzY-efSbox4;D}p^Qr4`=XPcqG4Tr^ash;O|b_^rU@OW{pPk~=$g`U3cr zO|IkQ&FGF6_rBfy=?h#J##{i8xYrHc3&2-oxcRcY4b5*-5bS)WSByT1&Rq}xVhPAQ z(EIi)<<*Y+9x!mO^`-E?S_ptQU_3NfNM`YBImToLfLh%5h2ZYo{cHO!AE#{isy1kp zyhenTbzpEQ7LpM?q8NV{4v#0;YiGlQ&Q7j+k+=Lo#aE*{YxH25_R0587yuLmHp|lLIYiq-6K$b34_og8= zkmY?G-VFzodq3jw{eJ6qaRgRFW%0V7V%&X2aT)^%z6icgxz6mV+Ouy+&8*IZgcE7@ zk@D+;FB~Ta#Ub5|0i#V#P1-nWkA)IX^>pPfkFn4VCmcLG#e~FdNWjj;(}o!ljZbx& zO-foKe~0|06shN0p_`6dlVwJd#sMayhhJ7ki##9@NHi}mZ=X(7lr}P#32`nQ4I1wb z+!1`sw-rO~2`7gC(PapP2FN>R*9nvGuvPr><;NWqUduDqFrX&0ZE;ncio5dSv*o(9 zH>XWE4K{g25eyXRV6oux7I*liAIGjt`5B=? M8k!o^>bXAn7gDq;O#lD@ literal 0 HcmV?d00001 diff --git a/plugins/cordova-plugin-camera/src/ubuntu/toolbar-right.png b/plugins/cordova-plugin-camera/src/ubuntu/toolbar-right.png new file mode 100644 index 0000000000000000000000000000000000000000..e4e6aa6026a3bc336abf5c46223c4f0152ecd2da GIT binary patch literal 1161 zcmeAS@N?(olHy`uVBq!ia0y~yU}OQZ=Ws9s$#qjy7Xbwd1AIbU|099Ay1Ko4_re9v zo;?d^!x`%8>Uw&55bpc;@132UfBpIe-}+aZ9Fk%5tsao)UnKoSU;n1Bcbva&LPBr`J*K>-U3v!kP9YHBKw!2$-X ztSn%}3IuFytUz@@E|9^-#>U6T2VsPTg#oPqinFt`X=!P}&4kGE@NffFs;jF3tp?f! zbR^JKV21#?%u-TP5WB&;m<0p`#KgpaA`mV+J3B-cNCKS$AvriWfVKmu1L4Lsu%q(mi9Q=YpVlwh7YT7!Uo?hO5!7(ujX(eUlmCenqZQavn%$zkF z23T_2sUlr zym`ykZQHhQ-@aq#&Yin zZ+-VWOhL%umWmV;=d4>R3h#@GUJ1LiYHQNLx+-<&^B?Ej`+n$i{d{k|`;yP}>{+1^ z3ZgdLtm9{Ew!an7v$fRQ{M@_St9stsPoG{dSsNG@zFDsS`|~N+^0wd4$WMJ)wp(6o z|DPB9*ZcA>3(6cXwLSm+^&%F>&6RJjoj$ky--jbJg0|i|v&Q(*sfRzmE)aCPK3{JQ z5C78;)8NaRDkuH!tY$x}vG00h<#z9zWjkY5dM)O^Tlja^x`O(J^&wM@wrQjmzcD@j zaTAyRzPJ$A)0@0L-I$t{d+lSh!Myi-!hbdeiX1-mf+w|B{7#i}SG?}ZJvOXor9wY^ z3ElBK@@cA;i1$*j(qmWGAA0Mb^-Dfdbj_r->zm|VKHHk=28B7sw_g13=sw|OOlwi7 zeQ)9(4eO>#kq!kLr?~w+E*k6HGXxtsTojlDI~-V)1Sn>HDAbtGDctz7;eU}!ljX#W zb;mdOO!+cHqHFTJH5)aPAKwW175L{(gtlkAvBPw`9ZGdw2A=chPP6lxx#Z>N=0(pv zeVf~#t3Tzt+7_stJt1!1t(7+Rzcn*VW;L}WiX63SEc^PQ!tbS;RoBHyis#O#svVrm z?f$JtGj-OHPK}ixUz|MatM*|Tm;48FA_Lb$p-|30t~frA?{^^95F Vdv8wr^Q;LZ=;`X`vd$@?2>|~T#2)|v literal 0 HcmV?d00001 diff --git a/plugins/cordova-plugin-camera/src/windows/CameraProxy.js b/plugins/cordova-plugin-camera/src/windows/CameraProxy.js new file mode 100644 index 0000000..eb10cd2 --- /dev/null +++ b/plugins/cordova-plugin-camera/src/windows/CameraProxy.js @@ -0,0 +1,882 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ + +/*jshint unused:true, undef:true, browser:true */ +/*global Windows:true, URL:true, module:true, require:true, WinJS:true */ + + +var Camera = require('./Camera'); + + +var getAppData = function () { + return Windows.Storage.ApplicationData.current; +}; +var encodeToBase64String = function (buffer) { + return Windows.Security.Cryptography.CryptographicBuffer.encodeToBase64String(buffer); +}; +var OptUnique = Windows.Storage.CreationCollisionOption.generateUniqueName; +var CapMSType = Windows.Media.Capture.MediaStreamType; +var webUIApp = Windows.UI.WebUI.WebUIApplication; +var fileIO = Windows.Storage.FileIO; +var pickerLocId = Windows.Storage.Pickers.PickerLocationId; + +module.exports = { + + // args will contain : + // ... it is an array, so be careful + // 0 quality:50, + // 1 destinationType:Camera.DestinationType.FILE_URI, + // 2 sourceType:Camera.PictureSourceType.CAMERA, + // 3 targetWidth:-1, + // 4 targetHeight:-1, + // 5 encodingType:Camera.EncodingType.JPEG, + // 6 mediaType:Camera.MediaType.PICTURE, + // 7 allowEdit:false, + // 8 correctOrientation:false, + // 9 saveToPhotoAlbum:false, + // 10 popoverOptions:null + // 11 cameraDirection:0 + + takePicture: function (successCallback, errorCallback, args) { + var sourceType = args[2]; + + if (sourceType != Camera.PictureSourceType.CAMERA) { + takePictureFromFile(successCallback, errorCallback, args); + } else { + takePictureFromCamera(successCallback, errorCallback, args); + } + } +}; + +// https://msdn.microsoft.com/en-us/library/windows/apps/ff462087(v=vs.105).aspx +var windowsVideoContainers = [".avi", ".flv", ".asx", ".asf", ".mov", ".mp4", ".mpg", ".rm", ".srt", ".swf", ".wmv", ".vob"]; +var windowsPhoneVideoContainers = [".avi", ".3gp", ".3g2", ".wmv", ".3gp", ".3g2", ".mp4", ".m4v"]; + +// Default aspect ratio 1.78 (16:9 hd video standard) +var DEFAULT_ASPECT_RATIO = '1.8'; + +// Highest possible z-index supported across browsers. Anything used above is converted to this value. +var HIGHEST_POSSIBLE_Z_INDEX = 2147483647; + +// Resize method +function resizeImage(successCallback, errorCallback, file, targetWidth, targetHeight, encodingType) { + var tempPhotoFileName = ""; + var targetContentType = ""; + + if (encodingType == Camera.EncodingType.PNG) { + tempPhotoFileName = "camera_cordova_temp_return.png"; + targetContentType = "image/png"; + } else { + tempPhotoFileName = "camera_cordova_temp_return.jpg"; + targetContentType = "image/jpeg"; + } + + var storageFolder = getAppData().localFolder; + file.copyAsync(storageFolder, file.name, Windows.Storage.NameCollisionOption.replaceExisting) + .then(function (storageFile) { + return fileIO.readBufferAsync(storageFile); + }) + .then(function(buffer) { + var strBase64 = encodeToBase64String(buffer); + var imageData = "data:" + file.contentType + ";base64," + strBase64; + var image = new Image(); + image.src = imageData; + image.onload = function() { + var ratio = Math.min(targetWidth / this.width, targetHeight / this.height); + var imageWidth = ratio * this.width; + var imageHeight = ratio * this.height; + + var canvas = document.createElement('canvas'); + var storageFileName; + + canvas.width = imageWidth; + canvas.height = imageHeight; + + canvas.getContext("2d").drawImage(this, 0, 0, imageWidth, imageHeight); + + var fileContent = canvas.toDataURL(targetContentType).split(',')[1]; + + var storageFolder = getAppData().localFolder; + + storageFolder.createFileAsync(tempPhotoFileName, OptUnique) + .then(function (storagefile) { + var content = Windows.Security.Cryptography.CryptographicBuffer.decodeFromBase64String(fileContent); + storageFileName = storagefile.name; + return fileIO.writeBufferAsync(storagefile, content); + }) + .done(function () { + successCallback("ms-appdata:///local/" + storageFileName); + }, errorCallback); + }; + }) + .done(null, function(err) { + errorCallback(err); + } + ); +} + +// Because of asynchronous method, so let the successCallback be called in it. +function resizeImageBase64(successCallback, errorCallback, file, targetWidth, targetHeight) { + fileIO.readBufferAsync(file).done( function(buffer) { + var strBase64 = encodeToBase64String(buffer); + var imageData = "data:" + file.contentType + ";base64," + strBase64; + + var image = new Image(); + image.src = imageData; + + image.onload = function() { + var ratio = Math.min(targetWidth / this.width, targetHeight / this.height); + var imageWidth = ratio * this.width; + var imageHeight = ratio * this.height; + var canvas = document.createElement('canvas'); + + canvas.width = imageWidth; + canvas.height = imageHeight; + + var ctx = canvas.getContext("2d"); + ctx.drawImage(this, 0, 0, imageWidth, imageHeight); + + // The resized file ready for upload + var finalFile = canvas.toDataURL(file.contentType); + + // Remove the prefix such as "data:" + contentType + ";base64," , in order to meet the Cordova API. + var arr = finalFile.split(","); + var newStr = finalFile.substr(arr[0].length + 1); + successCallback(newStr); + }; + }, function(err) { errorCallback(err); }); +} + +function takePictureFromFile(successCallback, errorCallback, args) { + // Detect Windows Phone + if (navigator.appVersion.indexOf('Windows Phone 8.1') >= 0) { + takePictureFromFileWP(successCallback, errorCallback, args); + } else { + takePictureFromFileWindows(successCallback, errorCallback, args); + } +} + +function takePictureFromFileWP(successCallback, errorCallback, args) { + var mediaType = args[6], + destinationType = args[1], + targetWidth = args[3], + targetHeight = args[4], + encodingType = args[5]; + + /* + Need to add and remove an event listener to catch activation state + Using FileOpenPicker will suspend the app and it's required to catch the PickSingleFileAndContinue + https://msdn.microsoft.com/en-us/library/windows/apps/xaml/dn631755.aspx + */ + var filePickerActivationHandler = function(eventArgs) { + if (eventArgs.kind === Windows.ApplicationModel.Activation.ActivationKind.pickFileContinuation) { + var file = eventArgs.files[0]; + if (!file) { + errorCallback("User didn't choose a file."); + webUIApp.removeEventListener("activated", filePickerActivationHandler); + return; + } + if (destinationType == Camera.DestinationType.FILE_URI || destinationType == Camera.DestinationType.NATIVE_URI) { + if (targetHeight > 0 && targetWidth > 0) { + resizeImage(successCallback, errorCallback, file, targetWidth, targetHeight, encodingType); + } + else { + var storageFolder = getAppData().localFolder; + file.copyAsync(storageFolder, file.name, Windows.Storage.NameCollisionOption.replaceExisting).done(function (storageFile) { + if(destinationType == Camera.DestinationType.NATIVE_URI) { + successCallback("ms-appdata:///local/" + storageFile.name); + } + else { + successCallback(URL.createObjectURL(storageFile)); + } + }, function () { + errorCallback("Can't access localStorage folder."); + }); + } + } + else { + if (targetHeight > 0 && targetWidth > 0) { + resizeImageBase64(successCallback, errorCallback, file, targetWidth, targetHeight); + } else { + fileIO.readBufferAsync(file).done(function (buffer) { + var strBase64 =encodeToBase64String(buffer); + successCallback(strBase64); + }, errorCallback); + } + } + webUIApp.removeEventListener("activated", filePickerActivationHandler); + } + }; + + var fileOpenPicker = new Windows.Storage.Pickers.FileOpenPicker(); + if (mediaType == Camera.MediaType.PICTURE) { + fileOpenPicker.fileTypeFilter.replaceAll([".png", ".jpg", ".jpeg"]); + fileOpenPicker.suggestedStartLocation = pickerLocId.picturesLibrary; + } + else if (mediaType == Camera.MediaType.VIDEO) { + fileOpenPicker.fileTypeFilter.replaceAll(windowsPhoneVideoContainers); + fileOpenPicker.suggestedStartLocation = pickerLocId.videosLibrary; + } + else { + fileOpenPicker.fileTypeFilter.replaceAll(["*"]); + fileOpenPicker.suggestedStartLocation = pickerLocId.documentsLibrary; + } + + webUIApp.addEventListener("activated", filePickerActivationHandler); + fileOpenPicker.pickSingleFileAndContinue(); +} + +function takePictureFromFileWindows(successCallback, errorCallback, args) { + var mediaType = args[6], + destinationType = args[1], + targetWidth = args[3], + targetHeight = args[4], + encodingType = args[5]; + + var fileOpenPicker = new Windows.Storage.Pickers.FileOpenPicker(); + if (mediaType == Camera.MediaType.PICTURE) { + fileOpenPicker.fileTypeFilter.replaceAll([".png", ".jpg", ".jpeg"]); + fileOpenPicker.suggestedStartLocation = pickerLocId.picturesLibrary; + } + else if (mediaType == Camera.MediaType.VIDEO) { + fileOpenPicker.fileTypeFilter.replaceAll(windowsVideoContainers); + fileOpenPicker.suggestedStartLocation = pickerLocId.videosLibrary; + } + else { + fileOpenPicker.fileTypeFilter.replaceAll(["*"]); + fileOpenPicker.suggestedStartLocation = pickerLocId.documentsLibrary; + } + + fileOpenPicker.pickSingleFileAsync().done(function (file) { + if (!file) { + errorCallback("User didn't choose a file."); + return; + } + if (destinationType == Camera.DestinationType.FILE_URI || destinationType == Camera.DestinationType.NATIVE_URI) { + if (targetHeight > 0 && targetWidth > 0) { + resizeImage(successCallback, errorCallback, file, targetWidth, targetHeight, encodingType); + } + else { + var storageFolder = getAppData().localFolder; + file.copyAsync(storageFolder, file.name, Windows.Storage.NameCollisionOption.replaceExisting).done(function (storageFile) { + if(destinationType == Camera.DestinationType.NATIVE_URI) { + successCallback("ms-appdata:///local/" + storageFile.name); + } + else { + successCallback(URL.createObjectURL(storageFile)); + } + }, function () { + errorCallback("Can't access localStorage folder."); + }); + } + } + else { + if (targetHeight > 0 && targetWidth > 0) { + resizeImageBase64(successCallback, errorCallback, file, targetWidth, targetHeight); + } else { + fileIO.readBufferAsync(file).done(function (buffer) { + var strBase64 =encodeToBase64String(buffer); + successCallback(strBase64); + }, errorCallback); + } + } + }, function () { + errorCallback("User didn't choose a file."); + }); +} + +function takePictureFromCamera(successCallback, errorCallback, args) { + // Check if necessary API available + if (!Windows.Media.Capture.CameraCaptureUI) { + takePictureFromCameraWP(successCallback, errorCallback, args); + } else { + takePictureFromCameraWindows(successCallback, errorCallback, args); + } +} + +function takePictureFromCameraWP(successCallback, errorCallback, args) { + // We are running on WP8.1 which lacks CameraCaptureUI class + // so we need to use MediaCapture class instead and implement custom UI for camera + var destinationType = args[1], + targetWidth = args[3], + targetHeight = args[4], + encodingType = args[5], + saveToPhotoAlbum = args[9], + cameraDirection = args[11], + capturePreview = null, + cameraCaptureButton = null, + cameraCancelButton = null, + capture = null, + captureSettings = null, + CaptureNS = Windows.Media.Capture, + sensor = null; + + function createCameraUI() { + // create style for take and cancel buttons + var buttonStyle = "width:45%;padding: 10px 16px;font-size: 18px;line-height: 1.3333333;color: #333;background-color: #fff;border-color: #ccc; border: 1px solid transparent;border-radius: 6px; display: block; margin: 20px; z-index: 1000;border-color: #adadad;"; + + // Create fullscreen preview + // z-order style element for capturePreview and cameraCancelButton elts + // is necessary to avoid overriding by another page elements, -1 sometimes is not enough + capturePreview = document.createElement("video"); + capturePreview.style.cssText = "position: fixed; left: 0; top: 0; width: 100%; height: 100%; z-index: " + (HIGHEST_POSSIBLE_Z_INDEX - 1) + ";"; + + // Create capture button + cameraCaptureButton = document.createElement("button"); + cameraCaptureButton.innerText = "Take"; + cameraCaptureButton.style.cssText = buttonStyle + "position: fixed; left: 0; bottom: 0; margin: 20px; z-index: " + HIGHEST_POSSIBLE_Z_INDEX + ";"; + + // Create cancel button + cameraCancelButton = document.createElement("button"); + cameraCancelButton.innerText = "Cancel"; + cameraCancelButton.style.cssText = buttonStyle + "position: fixed; right: 0; bottom: 0; margin: 20px; z-index: " + HIGHEST_POSSIBLE_Z_INDEX + ";"; + + capture = new CaptureNS.MediaCapture(); + + captureSettings = new CaptureNS.MediaCaptureInitializationSettings(); + captureSettings.streamingCaptureMode = CaptureNS.StreamingCaptureMode.video; + } + + function continueVideoOnFocus() { + // if preview is defined it would be stuck, play it + if (capturePreview) { + capturePreview.play(); + } + } + + function startCameraPreview() { + // Search for available camera devices + // This is necessary to detect which camera (front or back) we should use + var DeviceEnum = Windows.Devices.Enumeration; + var expectedPanel = cameraDirection === 1 ? DeviceEnum.Panel.front : DeviceEnum.Panel.back; + + // Add focus event handler to capture the event when user suspends the app and comes back while the preview is on + window.addEventListener("focus", continueVideoOnFocus); + + DeviceEnum.DeviceInformation.findAllAsync(DeviceEnum.DeviceClass.videoCapture).then(function (devices) { + if (devices.length <= 0) { + destroyCameraPreview(); + errorCallback('Camera not found'); + return; + } + + devices.forEach(function(currDev) { + if (currDev.enclosureLocation.panel && currDev.enclosureLocation.panel == expectedPanel) { + captureSettings.videoDeviceId = currDev.id; + } + }); + + captureSettings.photoCaptureSource = Windows.Media.Capture.PhotoCaptureSource.photo; + + return capture.initializeAsync(captureSettings); + }).then(function () { + + // create focus control if available + var VideoDeviceController = capture.videoDeviceController; + var FocusControl = VideoDeviceController.focusControl; + + if (FocusControl.supported === true) { + capturePreview.addEventListener('click', function () { + // Make sure function isn't called again before previous focus is completed + if (this.getAttribute('clicked') === '1') { + return false; + } else { + this.setAttribute('clicked', '1'); + } + var preset = Windows.Media.Devices.FocusPreset.autoNormal; + var parent = this; + FocusControl.setPresetAsync(preset).done(function () { + // set the clicked attribute back to '0' to allow focus again + parent.setAttribute('clicked', '0'); + }); + }); + } + + // msdn.microsoft.com/en-us/library/windows/apps/hh452807.aspx + capturePreview.msZoom = true; + capturePreview.src = URL.createObjectURL(capture); + capturePreview.play(); + + // Bind events to controls + sensor = Windows.Devices.Sensors.SimpleOrientationSensor.getDefault(); + if (sensor !== null) { + sensor.addEventListener("orientationchanged", onOrientationChange); + } + + // add click events to capture and cancel buttons + cameraCaptureButton.addEventListener('click', onCameraCaptureButtonClick); + cameraCancelButton.addEventListener('click', onCameraCancelButtonClick); + + // Change default orientation + if (sensor) { + setPreviewRotation(sensor.getCurrentOrientation()); + } else { + setPreviewRotation(Windows.Graphics.Display.DisplayInformation.getForCurrentView().currentOrientation); + } + + // Get available aspect ratios + var aspectRatios = getAspectRatios(capture); + + // Couldn't find a good ratio + if (aspectRatios.length === 0) { + destroyCameraPreview(); + errorCallback('There\'s not a good aspect ratio available'); + return; + } + + // add elements to body + document.body.appendChild(capturePreview); + document.body.appendChild(cameraCaptureButton); + document.body.appendChild(cameraCancelButton); + + if (aspectRatios.indexOf(DEFAULT_ASPECT_RATIO) > -1) { + return setAspectRatio(capture, DEFAULT_ASPECT_RATIO); + } else { + // Doesn't support 16:9 - pick next best + return setAspectRatio(capture, aspectRatios[0]); + } + }).done(null, function (err) { + destroyCameraPreview(); + errorCallback('Camera intitialization error ' + err); + }); + } + + function destroyCameraPreview() { + // If sensor is available, remove event listener + if (sensor !== null) { + sensor.removeEventListener('orientationchanged', onOrientationChange); + } + + // Pause and dispose preview element + capturePreview.pause(); + capturePreview.src = null; + + // Remove event listeners from buttons + cameraCaptureButton.removeEventListener('click', onCameraCaptureButtonClick); + cameraCancelButton.removeEventListener('click', onCameraCancelButtonClick); + + // Remove the focus event handler + window.removeEventListener("focus", continueVideoOnFocus); + + // Remove elements + [capturePreview, cameraCaptureButton, cameraCancelButton].forEach(function (elem) { + if (elem /* && elem in document.body.childNodes */) { + document.body.removeChild(elem); + } + }); + + // Stop and dispose media capture manager + if (capture) { + capture.stopRecordAsync(); + capture = null; + } + } + + function captureAction() { + + var encodingProperties, + fileName, + tempFolder = getAppData().temporaryFolder; + + if (encodingType == Camera.EncodingType.PNG) { + fileName = 'photo.png'; + encodingProperties = Windows.Media.MediaProperties.ImageEncodingProperties.createPng(); + } else { + fileName = 'photo.jpg'; + encodingProperties = Windows.Media.MediaProperties.ImageEncodingProperties.createJpeg(); + } + + tempFolder.createFileAsync(fileName, OptUnique) + .then(function(tempCapturedFile) { + return new WinJS.Promise(function (complete) { + var photoStream = new Windows.Storage.Streams.InMemoryRandomAccessStream(); + var finalStream = new Windows.Storage.Streams.InMemoryRandomAccessStream(); + capture.capturePhotoToStreamAsync(encodingProperties, photoStream) + .then(function() { + return Windows.Graphics.Imaging.BitmapDecoder.createAsync(photoStream); + }) + .then(function(dec) { + finalStream.size = 0; // BitmapEncoder requires the output stream to be empty + return Windows.Graphics.Imaging.BitmapEncoder.createForTranscodingAsync(finalStream, dec); + }) + .then(function(enc) { + // We need to rotate the photo wrt sensor orientation + enc.bitmapTransform.rotation = orientationToRotation(sensor.getCurrentOrientation()); + return enc.flushAsync(); + }) + .then(function() { + return tempCapturedFile.openAsync(Windows.Storage.FileAccessMode.readWrite); + }) + .then(function(fileStream) { + return Windows.Storage.Streams.RandomAccessStream.copyAndCloseAsync(finalStream, fileStream); + }) + .done(function() { + photoStream.close(); + finalStream.close(); + complete(tempCapturedFile); + }, function() { + photoStream.close(); + finalStream.close(); + throw new Error("An error has occured while capturing the photo."); + }); + }); + }) + .done(function(capturedFile) { + destroyCameraPreview(); + savePhoto(capturedFile, { + destinationType: destinationType, + targetHeight: targetHeight, + targetWidth: targetWidth, + encodingType: encodingType, + saveToPhotoAlbum: saveToPhotoAlbum + }, successCallback, errorCallback); + }, function(err) { + destroyCameraPreview(); + errorCallback(err); + }); + } + + function getAspectRatios(capture) { + var videoDeviceController = capture.videoDeviceController; + var photoAspectRatios = videoDeviceController.getAvailableMediaStreamProperties(CapMSType.photo).map(function (element) { + return (element.width / element.height).toFixed(1); + }).filter(function (element, index, array) { return (index === array.indexOf(element)); }); + + var videoAspectRatios = videoDeviceController.getAvailableMediaStreamProperties(CapMSType.videoRecord).map(function (element) { + return (element.width / element.height).toFixed(1); + }).filter(function (element, index, array) { return (index === array.indexOf(element)); }); + + var videoPreviewAspectRatios = videoDeviceController.getAvailableMediaStreamProperties(CapMSType.videoPreview).map(function (element) { + return (element.width / element.height).toFixed(1); + }).filter(function (element, index, array) { return (index === array.indexOf(element)); }); + + var allAspectRatios = [].concat(photoAspectRatios, videoAspectRatios, videoPreviewAspectRatios); + + var aspectObj = allAspectRatios.reduce(function (map, item) { + if (!map[item]) { + map[item] = 0; + } + map[item]++; + return map; + }, {}); + + return Object.keys(aspectObj).filter(function (k) { + return aspectObj[k] === 3; + }); + } + + function setAspectRatio(capture, aspect) { + // Max photo resolution with desired aspect ratio + var videoDeviceController = capture.videoDeviceController; + var photoResolution = videoDeviceController.getAvailableMediaStreamProperties(CapMSType.photo) + .filter(function (elem) { + return ((elem.width / elem.height).toFixed(1) === aspect); + }) + .reduce(function (prop1, prop2) { + return (prop1.width * prop1.height) > (prop2.width * prop2.height) ? prop1 : prop2; + }); + + // Max video resolution with desired aspect ratio + var videoRecordResolution = videoDeviceController.getAvailableMediaStreamProperties(CapMSType.videoRecord) + .filter(function (elem) { + return ((elem.width / elem.height).toFixed(1) === aspect); + }) + .reduce(function (prop1, prop2) { + return (prop1.width * prop1.height) > (prop2.width * prop2.height) ? prop1 : prop2; + }); + + // Max video preview resolution with desired aspect ratio + var videoPreviewResolution = videoDeviceController.getAvailableMediaStreamProperties(CapMSType.videoPreview) + .filter(function (elem) { + return ((elem.width / elem.height).toFixed(1) === aspect); + }) + .reduce(function (prop1, prop2) { + return (prop1.width * prop1.height) > (prop2.width * prop2.height) ? prop1 : prop2; + }); + + return videoDeviceController.setMediaStreamPropertiesAsync(CapMSType.photo, photoResolution) + .then(function () { + return videoDeviceController.setMediaStreamPropertiesAsync(CapMSType.videoPreview, videoPreviewResolution); + }) + .then(function () { + return videoDeviceController.setMediaStreamPropertiesAsync(CapMSType.videoRecord, videoRecordResolution); + }); + } + + /** + * When Capture button is clicked, try to capture a picture and return + */ + function onCameraCaptureButtonClick() { + // Make sure user can't click more than once + if (this.getAttribute('clicked') === '1') { + return false; + } else { + this.setAttribute('clicked', '1'); + } + captureAction(); + } + + /** + * When Cancel button is clicked, destroy camera preview and return with error callback + */ + function onCameraCancelButtonClick() { + // Make sure user can't click more than once + if (this.getAttribute('clicked') === '1') { + return false; + } else { + this.setAttribute('clicked', '1'); + } + destroyCameraPreview(); + errorCallback('no image selected'); + } + + /** + * When the phone orientation change, get the event and change camera preview rotation + * @param {Object} e - SimpleOrientationSensorOrientationChangedEventArgs + */ + function onOrientationChange(e) { + setPreviewRotation(e.orientation); + } + + /** + * Converts SimpleOrientation to a VideoRotation to remove difference between camera sensor orientation + * and video orientation + * @param {number} orientation - Windows.Devices.Sensors.SimpleOrientation + * @return {number} - Windows.Media.Capture.VideoRotation + */ + function orientationToRotation(orientation) { + // VideoRotation enumerable and BitmapRotation enumerable have the same values + // https://msdn.microsoft.com/en-us/library/windows/apps/windows.media.capture.videorotation.aspx + // https://msdn.microsoft.com/en-us/library/windows/apps/windows.graphics.imaging.bitmaprotation.aspx + + switch (orientation) { + // portrait + case Windows.Devices.Sensors.SimpleOrientation.notRotated: + return Windows.Media.Capture.VideoRotation.clockwise90Degrees; + // landscape + case Windows.Devices.Sensors.SimpleOrientation.rotated90DegreesCounterclockwise: + return Windows.Media.Capture.VideoRotation.none; + // portrait-flipped (not supported by WinPhone Apps) + case Windows.Devices.Sensors.SimpleOrientation.rotated180DegreesCounterclockwise: + // Falling back to portrait default + return Windows.Media.Capture.VideoRotation.clockwise90Degrees; + // landscape-flipped + case Windows.Devices.Sensors.SimpleOrientation.rotated270DegreesCounterclockwise: + return Windows.Media.Capture.VideoRotation.clockwise180Degrees; + // faceup & facedown + default: + // Falling back to portrait default + return Windows.Media.Capture.VideoRotation.clockwise90Degrees; + } + } + + /** + * Rotates the current MediaCapture's video + * @param {number} orientation - Windows.Devices.Sensors.SimpleOrientation + */ + function setPreviewRotation(orientation) { + capture.setPreviewRotation(orientationToRotation(orientation)); + } + + try { + createCameraUI(); + startCameraPreview(); + } catch (ex) { + errorCallback(ex); + } +} + +function takePictureFromCameraWindows(successCallback, errorCallback, args) { + var destinationType = args[1], + targetWidth = args[3], + targetHeight = args[4], + encodingType = args[5], + allowCrop = !!args[7], + saveToPhotoAlbum = args[9], + WMCapture = Windows.Media.Capture, + cameraCaptureUI = new WMCapture.CameraCaptureUI(); + + cameraCaptureUI.photoSettings.allowCropping = allowCrop; + + if (encodingType == Camera.EncodingType.PNG) { + cameraCaptureUI.photoSettings.format = WMCapture.CameraCaptureUIPhotoFormat.png; + } else { + cameraCaptureUI.photoSettings.format = WMCapture.CameraCaptureUIPhotoFormat.jpeg; + } + + // decide which max pixels should be supported by targetWidth or targetHeight. + var maxRes = null; + var UIMaxRes = WMCapture.CameraCaptureUIMaxPhotoResolution; + var totalPixels = targetWidth * targetHeight; + + if (targetWidth == -1 && targetHeight == -1) { + maxRes = UIMaxRes.highestAvailable; + } + // Temp fix for CB-10539 + /*else if (totalPixels <= 320 * 240) { + maxRes = UIMaxRes.verySmallQvga; + }*/ + else if (totalPixels <= 640 * 480) { + maxRes = UIMaxRes.smallVga; + } else if (totalPixels <= 1024 * 768) { + maxRes = UIMaxRes.mediumXga; + } else if (totalPixels <= 3 * 1000 * 1000) { + maxRes = UIMaxRes.large3M; + } else if (totalPixels <= 5 * 1000 * 1000) { + maxRes = UIMaxRes.veryLarge5M; + } else { + maxRes = UIMaxRes.highestAvailable; + } + + cameraCaptureUI.photoSettings.maxResolution = maxRes; + + var cameraPicture; + + // define focus handler for windows phone 10.0 + var savePhotoOnFocus = function () { + window.removeEventListener("focus", savePhotoOnFocus); + // call only when the app is in focus again + savePhoto(cameraPicture, { + destinationType: destinationType, + targetHeight: targetHeight, + targetWidth: targetWidth, + encodingType: encodingType, + saveToPhotoAlbum: saveToPhotoAlbum + }, successCallback, errorCallback); + }; + + // if windows phone 10, add and delete focus eventHandler to capture the focus back from cameraUI to app + if (navigator.appVersion.indexOf('Windows Phone 10.0') >= 0) { + window.addEventListener("focus", savePhotoOnFocus); + } + + cameraCaptureUI.captureFileAsync(WMCapture.CameraCaptureUIMode.photo).done(function (picture) { + if (!picture) { + errorCallback("User didn't capture a photo."); + // Remove the focus handler if present + window.removeEventListener("focus", savePhotoOnFocus); + return; + } + cameraPicture = picture; + + // If not windows 10, call savePhoto() now. If windows 10, wait for the app to be in focus again + if (navigator.appVersion.indexOf('Windows Phone 10.0') < 0) { + savePhoto(cameraPicture, { + destinationType: destinationType, + targetHeight: targetHeight, + targetWidth: targetWidth, + encodingType: encodingType, + saveToPhotoAlbum: saveToPhotoAlbum + }, successCallback, errorCallback); + } + }, function () { + errorCallback("Fail to capture a photo."); + window.removeEventListener("focus", savePhotoOnFocus); + }); +} + +function savePhoto(picture, options, successCallback, errorCallback) { + // success callback for capture operation + var success = function(picture) { + if (options.destinationType == Camera.DestinationType.FILE_URI || options.destinationType == Camera.DestinationType.NATIVE_URI) { + if (options.targetHeight > 0 && options.targetWidth > 0) { + resizeImage(successCallback, errorCallback, picture, options.targetWidth, options.targetHeight, options.encodingType); + } else { + picture.copyAsync(getAppData().localFolder, picture.name, OptUnique).done(function (copiedFile) { + successCallback("ms-appdata:///local/" + copiedFile.name); + },errorCallback); + } + } else { + if (options.targetHeight > 0 && options.targetWidth > 0) { + resizeImageBase64(successCallback, errorCallback, picture, options.targetWidth, options.targetHeight); + } else { + fileIO.readBufferAsync(picture).done(function(buffer) { + var strBase64 = encodeToBase64String(buffer); + picture.deleteAsync().done(function() { + successCallback(strBase64); + }, function(err) { + errorCallback(err); + }); + }, errorCallback); + } + } + }; + + if (!options.saveToPhotoAlbum) { + success(picture); + return; + } else { + var savePicker = new Windows.Storage.Pickers.FileSavePicker(); + var saveFile = function(file) { + if (file) { + // Prevent updates to the remote version of the file until we're done + Windows.Storage.CachedFileManager.deferUpdates(file); + picture.moveAndReplaceAsync(file) + .then(function() { + // Let Windows know that we're finished changing the file so + // the other app can update the remote version of the file. + return Windows.Storage.CachedFileManager.completeUpdatesAsync(file); + }) + .done(function(updateStatus) { + if (updateStatus === Windows.Storage.Provider.FileUpdateStatus.complete) { + success(picture); + } else { + errorCallback("File update status is not complete."); + } + }, errorCallback); + } else { + errorCallback("Failed to select a file."); + } + }; + savePicker.suggestedStartLocation = pickerLocId.picturesLibrary; + + if (options.encodingType === Camera.EncodingType.PNG) { + savePicker.fileTypeChoices.insert("PNG", [".png"]); + savePicker.suggestedFileName = "photo.png"; + } else { + savePicker.fileTypeChoices.insert("JPEG", [".jpg"]); + savePicker.suggestedFileName = "photo.jpg"; + } + + // If Windows Phone 8.1 use pickSaveFileAndContinue() + if (navigator.appVersion.indexOf('Windows Phone 8.1') >= 0) { + /* + Need to add and remove an event listener to catch activation state + Using FileSavePicker will suspend the app and it's required to catch the pickSaveFileContinuation + https://msdn.microsoft.com/en-us/library/windows/apps/xaml/dn631755.aspx + */ + var fileSaveHandler = function(eventArgs) { + if (eventArgs.kind === Windows.ApplicationModel.Activation.ActivationKind.pickSaveFileContinuation) { + var file = eventArgs.file; + saveFile(file); + webUIApp.removeEventListener("activated", fileSaveHandler); + } + }; + webUIApp.addEventListener("activated", fileSaveHandler); + savePicker.pickSaveFileAndContinue(); + } else { + savePicker.pickSaveFileAsync() + .done(saveFile, errorCallback); + } + } +} + +require("cordova/exec/proxy").add("Camera",module.exports); diff --git a/plugins/cordova-plugin-camera/src/wp/Camera.cs b/plugins/cordova-plugin-camera/src/wp/Camera.cs new file mode 100644 index 0000000..264a205 --- /dev/null +++ b/plugins/cordova-plugin-camera/src/wp/Camera.cs @@ -0,0 +1,534 @@ +/* + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +using System; +using System.Net; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Documents; +using System.Windows.Ink; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Animation; +using System.Collections.Generic; +using Microsoft.Phone.Tasks; +using System.Runtime.Serialization; +using System.IO; +using System.IO.IsolatedStorage; +using System.Windows.Media.Imaging; +using Microsoft.Phone; +using Microsoft.Xna.Framework.Media; +using System.Diagnostics; + +namespace WPCordovaClassLib.Cordova.Commands +{ + public class Camera : BaseCommand + { + + /// + /// Return base64 encoded string + /// + private const int DATA_URL = 0; + + /// + /// Return file uri + /// + private const int FILE_URI = 1; + + /// + /// Return native uri + /// + private const int NATIVE_URI = 2; + + /// + /// Choose image from picture library + /// + private const int PHOTOLIBRARY = 0; + + /// + /// Take picture from camera + /// + + private const int CAMERA = 1; + + /// + /// Choose image from picture library + /// + private const int SAVEDPHOTOALBUM = 2; + + /// + /// Take a picture of type JPEG + /// + private const int JPEG = 0; + + /// + /// Take a picture of type PNG + /// + private const int PNG = 1; + + /// + /// Folder to store captured images + /// + private const string isoFolder = "CapturedImagesCache"; + + /// + /// Represents captureImage action options. + /// + [DataContract] + public class CameraOptions + { + /// + /// Source to getPicture from. + /// + [DataMember(IsRequired = false, Name = "sourceType")] + public int PictureSourceType { get; set; } + + /// + /// Format of image that returned from getPicture. + /// + [DataMember(IsRequired = false, Name = "destinationType")] + public int DestinationType { get; set; } + + /// + /// Quality of saved image + /// + [DataMember(IsRequired = false, Name = "quality")] + public int Quality { get; set; } + + /// + /// Controls whether or not the image is also added to the device photo album. + /// + [DataMember(IsRequired = false, Name = "saveToPhotoAlbum")] + public bool SaveToPhotoAlbum { get; set; } + + /// + /// Ignored + /// + [DataMember(IsRequired = false, Name = "correctOrientation")] + public bool CorrectOrientation { get; set; } + + /// + /// Ignored + /// + [DataMember(IsRequired = false, Name = "allowEdit")] + public bool AllowEdit { get; set; } + + /// + /// Height in pixels to scale image + /// + [DataMember(IsRequired = false, Name = "encodingType")] + public int EncodingType { get; set; } + + /// + /// Height in pixels to scale image + /// + [DataMember(IsRequired = false, Name = "mediaType")] + public int MediaType { get; set; } + + + /// + /// Height in pixels to scale image + /// + [DataMember(IsRequired = false, Name = "targetHeight")] + public int TargetHeight { get; set; } + + + /// + /// Width in pixels to scale image + /// + [DataMember(IsRequired = false, Name = "targetWidth")] + public int TargetWidth { get; set; } + + /// + /// Creates options object with default parameters + /// + public CameraOptions() + { + this.SetDefaultValues(new StreamingContext()); + } + + /// + /// Initializes default values for class fields. + /// Implemented in separate method because default constructor is not invoked during deserialization. + /// + /// + [OnDeserializing()] + public void SetDefaultValues(StreamingContext context) + { + PictureSourceType = CAMERA; + DestinationType = FILE_URI; + Quality = 80; + TargetHeight = -1; + TargetWidth = -1; + SaveToPhotoAlbum = false; + CorrectOrientation = true; + AllowEdit = false; + MediaType = -1; + EncodingType = -1; + } + } + + /// + /// Camera options + /// + CameraOptions cameraOptions; + + public void takePicture(string options) + { + try + { + string[] args = JSON.JsonHelper.Deserialize(options); + // ["quality", "destinationType", "sourceType", "targetWidth", "targetHeight", "encodingType", + // "mediaType", "allowEdit", "correctOrientation", "saveToPhotoAlbum" ] + cameraOptions = new CameraOptions(); + cameraOptions.Quality = int.Parse(args[0]); + cameraOptions.DestinationType = int.Parse(args[1]); + cameraOptions.PictureSourceType = int.Parse(args[2]); + cameraOptions.TargetWidth = int.Parse(args[3]); + cameraOptions.TargetHeight = int.Parse(args[4]); + cameraOptions.EncodingType = int.Parse(args[5]); + cameraOptions.MediaType = int.Parse(args[6]); + cameraOptions.AllowEdit = bool.Parse(args[7]); + cameraOptions.CorrectOrientation = bool.Parse(args[8]); + cameraOptions.SaveToPhotoAlbum = bool.Parse(args[9]); + + // a very large number will force the other value to be the bound + if (cameraOptions.TargetWidth > -1 && cameraOptions.TargetHeight == -1) + { + cameraOptions.TargetHeight = 100000; + } + else if (cameraOptions.TargetHeight > -1 && cameraOptions.TargetWidth == -1) + { + cameraOptions.TargetWidth = 100000; + } + } + catch (Exception ex) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION, ex.Message)); + return; + } + + // Api supports FILE_URI, DATA_URL, NATIVE_URI destination types. + // Treat all other destination types as an error. + switch (cameraOptions.DestinationType) + { + case Camera.FILE_URI: + case Camera.DATA_URL: + case Camera.NATIVE_URI: + break; + default: + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Incorrect option: destinationType")); + return; + } + + ChooserBase chooserTask = null; + if (cameraOptions.PictureSourceType == CAMERA) + { + chooserTask = new CameraCaptureTask(); + } + else if ((cameraOptions.PictureSourceType == PHOTOLIBRARY) || (cameraOptions.PictureSourceType == SAVEDPHOTOALBUM)) + { + chooserTask = new PhotoChooserTask(); + } + // if chooserTask is still null, then PictureSourceType was invalid + if (chooserTask != null) + { + chooserTask.Completed += onTaskCompleted; + chooserTask.Show(); + } + else + { + Debug.WriteLine("Unrecognized PictureSourceType :: " + cameraOptions.PictureSourceType.ToString()); + DispatchCommandResult(new PluginResult(PluginResult.Status.NO_RESULT)); + } + } + + public void onTaskCompleted(object sender, PhotoResult e) + { + var task = sender as ChooserBase; + if (task != null) + { + task.Completed -= onTaskCompleted; + } + + if (e.Error != null) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR)); + return; + } + + switch (e.TaskResult) + { + case TaskResult.OK: + try + { + string imagePathOrContent = string.Empty; + + // Save image back to media library + // only save to photoalbum if it didn't come from there ... + if (cameraOptions.PictureSourceType == CAMERA && cameraOptions.SaveToPhotoAlbum) + { + MediaLibrary library = new MediaLibrary(); + Picture pict = library.SavePicture(e.OriginalFileName, e.ChosenPhoto); // to save to photo-roll ... + } + + int newAngle = 0; + // There's bug in Windows Phone 8.1 causing Seek on a DssPhotoStream not working properly. + // https://connect.microsoft.com/VisualStudio/feedback/details/783252 + // But a mis-oriented file is better than nothing, so try and catch. + try { + int orient = ImageExifHelper.getImageOrientationFromStream(e.ChosenPhoto); + switch (orient) { + case ImageExifOrientation.LandscapeLeft: + newAngle = 90; + break; + case ImageExifOrientation.PortraitUpsideDown: + newAngle = 180; + break; + case ImageExifOrientation.LandscapeRight: + newAngle = 270; + break; + case ImageExifOrientation.Portrait: + default: break; // 0 default already set + } + } catch { + Debug.WriteLine("Error fetching orientation from Exif"); + } + + if (newAngle != 0) + { + using (Stream rotImageStream = ImageExifHelper.RotateStream(e.ChosenPhoto, newAngle)) + { + // we should reset stream position after saving stream to media library + rotImageStream.Seek(0, SeekOrigin.Begin); + if (cameraOptions.DestinationType == DATA_URL) + { + imagePathOrContent = GetImageContent(rotImageStream); + } + else // FILE_URL or NATIVE_URI (both use the same resultant uri format) + { + imagePathOrContent = SaveImageToLocalStorage(rotImageStream, Path.GetFileName(e.OriginalFileName)); + } + } + } + else // no need to reorient + { + if (cameraOptions.DestinationType == DATA_URL) + { + imagePathOrContent = GetImageContent(e.ChosenPhoto); + } + else // FILE_URL or NATIVE_URI (both use the same resultant uri format) + { + imagePathOrContent = SaveImageToLocalStorage(e.ChosenPhoto, Path.GetFileName(e.OriginalFileName)); + } + } + + DispatchCommandResult(new PluginResult(PluginResult.Status.OK, imagePathOrContent)); + } + catch (Exception) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Error retrieving image.")); + } + break; + case TaskResult.Cancel: + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Selection cancelled.")); + break; + default: + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Selection did not complete!")); + break; + } + } + + /// + /// Returns image content in a form of base64 string + /// + /// Image stream + /// Base64 representation of the image + private string GetImageContent(Stream stream) + { + byte[] imageContent = null; + + try + { + // Resize photo and convert to JPEG + imageContent = ResizePhoto(stream); + } + finally + { + stream.Dispose(); + } + + return Convert.ToBase64String(imageContent); + } + + /// + /// Resize image + /// + /// Image stream + /// resized image + private byte[] ResizePhoto(Stream stream) + { + //output + byte[] resizedFile; + + BitmapImage objBitmap = new BitmapImage(); + objBitmap.SetSource(stream); + objBitmap.CreateOptions = BitmapCreateOptions.None; + + WriteableBitmap objWB = new WriteableBitmap(objBitmap); + objBitmap.UriSource = null; + + // Calculate resultant image size + int width, height; + if (cameraOptions.TargetWidth >= 0 && cameraOptions.TargetHeight >= 0) + { + // Keep proportionally + double ratio = Math.Min( + (double)cameraOptions.TargetWidth / objWB.PixelWidth, + (double)cameraOptions.TargetHeight / objWB.PixelHeight); + width = Convert.ToInt32(ratio * objWB.PixelWidth); + height = Convert.ToInt32(ratio * objWB.PixelHeight); + } + else + { + width = objWB.PixelWidth; + height = objWB.PixelHeight; + } + + //Hold the result stream + using (MemoryStream objBitmapStreamResized = new MemoryStream()) + { + + try + { + // resize the photo with user defined TargetWidth & TargetHeight + Extensions.SaveJpeg(objWB, objBitmapStreamResized, width, height, 0, cameraOptions.Quality); + } + finally + { + //Dispose bitmaps immediately, they are memory expensive + DisposeImage(objBitmap); + DisposeImage(objWB); + GC.Collect(); + } + + //Convert the resized stream to a byte array. + int streamLength = (int)objBitmapStreamResized.Length; + resizedFile = new Byte[streamLength]; //-1 + objBitmapStreamResized.Position = 0; + + //for some reason we have to set Position to zero, but we don't have to earlier when we get the bytes from the chosen photo... + objBitmapStreamResized.Read(resizedFile, 0, streamLength); + } + + return resizedFile; + } + + /// + /// Util: Dispose a bitmap resource + /// + /// BitmapSource subclass to dispose + private void DisposeImage(BitmapSource image) + { + if (image != null) + { + try + { + using (var ms = new MemoryStream(new byte[] { 0x0 })) + { + image.SetSource(ms); + } + } + catch (Exception) + { + } + } + } + + /// + /// Saves captured image in isolated storage + /// + /// image file name + /// Image path + private string SaveImageToLocalStorage(Stream stream, string imageFileName) + { + + if (stream == null) + { + throw new ArgumentNullException("imageBytes"); + } + try + { + var isoFile = IsolatedStorageFile.GetUserStoreForApplication(); + + if (!isoFile.DirectoryExists(isoFolder)) + { + isoFile.CreateDirectory(isoFolder); + } + + string filePath = System.IO.Path.Combine("///" + isoFolder + "/", imageFileName); + + using (IsolatedStorageFileStream outputStream = isoFile.CreateFile(filePath)) + { + BitmapImage objBitmap = new BitmapImage(); + objBitmap.SetSource(stream); + objBitmap.CreateOptions = BitmapCreateOptions.None; + + WriteableBitmap objWB = new WriteableBitmap(objBitmap); + objBitmap.UriSource = null; + + try + { + + //use photo's actual width & height if user doesn't provide width & height + if (cameraOptions.TargetWidth < 0 && cameraOptions.TargetHeight < 0) + { + objWB.SaveJpeg(outputStream, objWB.PixelWidth, objWB.PixelHeight, 0, cameraOptions.Quality); + } + else + { + //Resize + //Keep proportionally + double ratio = Math.Min((double)cameraOptions.TargetWidth / objWB.PixelWidth, (double)cameraOptions.TargetHeight / objWB.PixelHeight); + int width = Convert.ToInt32(ratio * objWB.PixelWidth); + int height = Convert.ToInt32(ratio * objWB.PixelHeight); + + // resize the photo with user defined TargetWidth & TargetHeight + objWB.SaveJpeg(outputStream, width, height, 0, cameraOptions.Quality); + } + } + finally + { + //Dispose bitmaps immediately, they are memory expensive + DisposeImage(objBitmap); + DisposeImage(objWB); + GC.Collect(); + } + } + + return new Uri(filePath, UriKind.Relative).ToString(); + } + catch (Exception) + { + //TODO: log or do something else + throw; + } + finally + { + stream.Dispose(); + } + } + + } +} diff --git a/plugins/cordova-plugin-camera/tests/ios/.npmignore b/plugins/cordova-plugin-camera/tests/ios/.npmignore new file mode 100644 index 0000000..b512c09 --- /dev/null +++ b/plugins/cordova-plugin-camera/tests/ios/.npmignore @@ -0,0 +1 @@ +node_modules \ No newline at end of file diff --git a/plugins/cordova-plugin-camera/tests/ios/CDVCameraTest.xcworkspace/contents.xcworkspacedata b/plugins/cordova-plugin-camera/tests/ios/CDVCameraTest.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..22fcf41 --- /dev/null +++ b/plugins/cordova-plugin-camera/tests/ios/CDVCameraTest.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/plugins/cordova-plugin-camera/tests/ios/CDVCameraTest.xcworkspace/xcshareddata/CDVCameraTest.xccheckout b/plugins/cordova-plugin-camera/tests/ios/CDVCameraTest.xcworkspace/xcshareddata/CDVCameraTest.xccheckout new file mode 100644 index 0000000..c8a5605 --- /dev/null +++ b/plugins/cordova-plugin-camera/tests/ios/CDVCameraTest.xcworkspace/xcshareddata/CDVCameraTest.xccheckout @@ -0,0 +1,41 @@ + + + + + IDESourceControlProjectFavoriteDictionaryKey + + IDESourceControlProjectIdentifier + 6BE9AD73-1B9F-4362-98D7-DC631BEC6185 + IDESourceControlProjectName + CDVCameraTest + IDESourceControlProjectOriginsDictionary + + 729B5706E7BAF4E9EE7AEE3C003A08107411AB7C + github.com:shazron/cordova-plugin-camera.git + + IDESourceControlProjectPath + tests/ios/CDVCameraTest.xcworkspace + IDESourceControlProjectRelativeInstallPathDictionary + + 729B5706E7BAF4E9EE7AEE3C003A08107411AB7C + ../../.. + + IDESourceControlProjectURL + github.com:shazron/cordova-plugin-camera.git + IDESourceControlProjectVersion + 111 + IDESourceControlProjectWCCIdentifier + 729B5706E7BAF4E9EE7AEE3C003A08107411AB7C + IDESourceControlProjectWCConfigurations + + + IDESourceControlRepositoryExtensionIdentifierKey + public.vcs.git + IDESourceControlWCCIdentifierKey + 729B5706E7BAF4E9EE7AEE3C003A08107411AB7C + IDESourceControlWCCName + cordova-plugin-camera + + + + diff --git a/plugins/cordova-plugin-camera/tests/ios/CDVCameraTest.xcworkspace/xcshareddata/xcschemes/CordovaLib.xcscheme b/plugins/cordova-plugin-camera/tests/ios/CDVCameraTest.xcworkspace/xcshareddata/xcschemes/CordovaLib.xcscheme new file mode 100644 index 0000000..3e8cd2c --- /dev/null +++ b/plugins/cordova-plugin-camera/tests/ios/CDVCameraTest.xcworkspace/xcshareddata/xcschemes/CordovaLib.xcscheme @@ -0,0 +1,77 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/cordova-plugin-camera/tests/ios/CDVCameraTest/CDVCameraLibTests/CameraTest.m b/plugins/cordova-plugin-camera/tests/ios/CDVCameraTest/CDVCameraLibTests/CameraTest.m new file mode 100644 index 0000000..b9439d1 --- /dev/null +++ b/plugins/cordova-plugin-camera/tests/ios/CDVCameraTest/CDVCameraLibTests/CameraTest.m @@ -0,0 +1,511 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. + */ + +#import +#import +#import "CDVCamera.h" +#import "UIImage+CropScaleOrientation.h" +#import + + +@interface CameraTest : XCTestCase + +@property (nonatomic, strong) CDVCamera* plugin; + +@end + +@interface CDVCamera () + +// expose private interface +- (NSData*)processImage:(UIImage*)image info:(NSDictionary*)info options:(CDVPictureOptions*)options; +- (UIImage*)retrieveImage:(NSDictionary*)info options:(CDVPictureOptions*)options; +- (CDVPluginResult*)resultForImage:(CDVPictureOptions*)options info:(NSDictionary*)info; +- (CDVPluginResult*)resultForVideo:(NSDictionary*)info; + +@end + +@implementation CameraTest + +- (void)setUp { + [super setUp]; + // Put setup code here. This method is called before the invocation of each test method in the class. + + self.plugin = [[CDVCamera alloc] init]; +} + +- (void)tearDown { + // Put teardown code here. This method is called after the invocation of each test method in the class. + [super tearDown]; +} + +- (void) testPictureOptionsCreate +{ + NSArray* args; + CDVPictureOptions* options; + NSDictionary* popoverOptions; + + // No arguments, check whether the defaults are set + args = @[]; + CDVInvokedUrlCommand* command = [[CDVInvokedUrlCommand alloc] initWithArguments:args callbackId:@"dummy" className:@"myclassname" methodName:@"mymethodname"]; + + options = [CDVPictureOptions createFromTakePictureArguments:command]; + + XCTAssertEqual([options.quality intValue], 50); + XCTAssertEqual(options.destinationType, (int)DestinationTypeFileUri); + XCTAssertEqual(options.sourceType, (int)UIImagePickerControllerSourceTypeCamera); + XCTAssertEqual(options.targetSize.width, 0); + XCTAssertEqual(options.targetSize.height, 0); + XCTAssertEqual(options.encodingType, (int)EncodingTypeJPEG); + XCTAssertEqual(options.mediaType, (int)MediaTypePicture); + XCTAssertEqual(options.allowsEditing, NO); + XCTAssertEqual(options.correctOrientation, NO); + XCTAssertEqual(options.saveToPhotoAlbum, NO); + XCTAssertEqualObjects(options.popoverOptions, nil); + XCTAssertEqual(options.cameraDirection, (int)UIImagePickerControllerCameraDeviceRear); + XCTAssertEqual(options.popoverSupported, NO); + XCTAssertEqual(options.usesGeolocation, NO); + + // Set each argument, check whether they are set. different from defaults + popoverOptions = @{ @"x" : @1, @"y" : @2, @"width" : @3, @"height" : @4 }; + + args = @[ + @(49), + @(DestinationTypeDataUrl), + @(UIImagePickerControllerSourceTypePhotoLibrary), + @(120), + @(240), + @(EncodingTypePNG), + @(MediaTypeVideo), + @YES, + @YES, + @YES, + popoverOptions, + @(UIImagePickerControllerCameraDeviceFront), + ]; + + command = [[CDVInvokedUrlCommand alloc] initWithArguments:args callbackId:@"dummy" className:@"myclassname" methodName:@"mymethodname"]; + options = [CDVPictureOptions createFromTakePictureArguments:command]; + + XCTAssertEqual([options.quality intValue], 49); + XCTAssertEqual(options.destinationType, (int)DestinationTypeDataUrl); + XCTAssertEqual(options.sourceType, (int)UIImagePickerControllerSourceTypePhotoLibrary); + XCTAssertEqual(options.targetSize.width, 120); + XCTAssertEqual(options.targetSize.height, 240); + XCTAssertEqual(options.encodingType, (int)EncodingTypePNG); + XCTAssertEqual(options.mediaType, (int)MediaTypeVideo); + XCTAssertEqual(options.allowsEditing, YES); + XCTAssertEqual(options.correctOrientation, YES); + XCTAssertEqual(options.saveToPhotoAlbum, YES); + XCTAssertEqualObjects(options.popoverOptions, popoverOptions); + XCTAssertEqual(options.cameraDirection, (int)UIImagePickerControllerCameraDeviceFront); + XCTAssertEqual(options.popoverSupported, NO); + XCTAssertEqual(options.usesGeolocation, NO); +} + +- (void) testCameraPickerCreate +{ + NSDictionary* popoverOptions; + NSArray* args; + CDVPictureOptions* pictureOptions; + CDVCameraPicker* picker; + + // Souce is Camera, and image type + + popoverOptions = @{ @"x" : @1, @"y" : @2, @"width" : @3, @"height" : @4 }; + args = @[ + @(49), + @(DestinationTypeDataUrl), + @(UIImagePickerControllerSourceTypeCamera), + @(120), + @(240), + @(EncodingTypePNG), + @(MediaTypeAll), + @YES, + @YES, + @YES, + popoverOptions, + @(UIImagePickerControllerCameraDeviceFront), + ]; + + CDVInvokedUrlCommand* command = [[CDVInvokedUrlCommand alloc] initWithArguments:args callbackId:@"dummy" className:@"myclassname" methodName:@"mymethodname"]; + pictureOptions = [CDVPictureOptions createFromTakePictureArguments:command]; + + if ([UIImagePickerController isSourceTypeAvailable:pictureOptions.sourceType]) { + picker = [CDVCameraPicker createFromPictureOptions:pictureOptions]; + + XCTAssertEqualObjects(picker.pictureOptions, pictureOptions); + + XCTAssertEqual(picker.sourceType, pictureOptions.sourceType); + XCTAssertEqual(picker.allowsEditing, pictureOptions.allowsEditing); + XCTAssertEqualObjects(picker.mediaTypes, @[(NSString*)kUTTypeImage]); + XCTAssertEqual(picker.cameraDevice, pictureOptions.cameraDirection); + } + + // Souce is not Camera, and all media types + + args = @[ + @(49), + @(DestinationTypeDataUrl), + @(UIImagePickerControllerSourceTypePhotoLibrary), + @(120), + @(240), + @(EncodingTypePNG), + @(MediaTypeAll), + @YES, + @YES, + @YES, + popoverOptions, + @(UIImagePickerControllerCameraDeviceFront), + ]; + + command = [[CDVInvokedUrlCommand alloc] initWithArguments:args callbackId:@"dummy" className:@"myclassname" methodName:@"mymethodname"]; + pictureOptions = [CDVPictureOptions createFromTakePictureArguments:command]; + + if ([UIImagePickerController isSourceTypeAvailable:pictureOptions.sourceType]) { + picker = [CDVCameraPicker createFromPictureOptions:pictureOptions]; + + XCTAssertEqualObjects(picker.pictureOptions, pictureOptions); + + XCTAssertEqual(picker.sourceType, pictureOptions.sourceType); + XCTAssertEqual(picker.allowsEditing, pictureOptions.allowsEditing); + XCTAssertEqualObjects(picker.mediaTypes, [UIImagePickerController availableMediaTypesForSourceType:picker.sourceType]); + } + + // Souce is not Camera, and either Image or Movie media type + + args = @[ + @(49), + @(DestinationTypeDataUrl), + @(UIImagePickerControllerSourceTypePhotoLibrary), + @(120), + @(240), + @(EncodingTypePNG), + @(MediaTypeVideo), + @YES, + @YES, + @YES, + popoverOptions, + @(UIImagePickerControllerCameraDeviceFront), + ]; + + command = [[CDVInvokedUrlCommand alloc] initWithArguments:args callbackId:@"dummy" className:@"myclassname" methodName:@"mymethodname"]; + pictureOptions = [CDVPictureOptions createFromTakePictureArguments:command]; + + if ([UIImagePickerController isSourceTypeAvailable:pictureOptions.sourceType]) { + picker = [CDVCameraPicker createFromPictureOptions:pictureOptions]; + + XCTAssertEqualObjects(picker.pictureOptions, pictureOptions); + + XCTAssertEqual(picker.sourceType, pictureOptions.sourceType); + XCTAssertEqual(picker.allowsEditing, pictureOptions.allowsEditing); + XCTAssertEqualObjects(picker.mediaTypes, @[(NSString*)kUTTypeMovie]); + } +} + +- (UIImage*) createImage:(CGRect)rect orientation:(UIImageOrientation)imageOrientation { + UIGraphicsBeginImageContext(rect.size); + CGContextRef context = UIGraphicsGetCurrentContext(); + + CGContextSetFillColorWithColor(context, [[UIColor greenColor] CGColor]); + CGContextFillRect(context, rect); + + CGImageRef result = CGBitmapContextCreateImage(UIGraphicsGetCurrentContext()); + UIImage* image = [UIImage imageWithCGImage:result scale:1.0f orientation:imageOrientation]; + + UIGraphicsEndImageContext(); + + return image; +} + +- (void) testImageScaleCropForSize { + + UIImage *sourceImagePortrait, *sourceImageLandscape, *targetImage; + CGSize targetSize = CGSizeZero; + + sourceImagePortrait = [self createImage:CGRectMake(0, 0, 2448, 3264) orientation:UIImageOrientationUp]; + sourceImageLandscape = [self createImage:CGRectMake(0, 0, 3264, 2448) orientation:UIImageOrientationUp]; + + // test 640x480 + + targetSize = CGSizeMake(640, 480); + + targetImage = [sourceImagePortrait imageByScalingAndCroppingForSize:targetSize]; + XCTAssertEqual(targetImage.size.width, targetSize.width); + XCTAssertEqual(targetImage.size.height, targetSize.height); + + targetImage = [sourceImageLandscape imageByScalingAndCroppingForSize:targetSize]; + XCTAssertEqual(targetImage.size.width, targetSize.width); + XCTAssertEqual(targetImage.size.height, targetSize.height); + + + // test 800x600 + + targetSize = CGSizeMake(800, 600); + + targetImage = [sourceImagePortrait imageByScalingAndCroppingForSize:targetSize]; + XCTAssertEqual(targetImage.size.width, targetSize.width); + XCTAssertEqual(targetImage.size.height, targetSize.height); + + targetImage = [sourceImageLandscape imageByScalingAndCroppingForSize:targetSize]; + XCTAssertEqual(targetImage.size.width, targetSize.width); + XCTAssertEqual(targetImage.size.height, targetSize.height); + + // test 1024x768 + + targetSize = CGSizeMake(1024, 768); + + targetImage = [sourceImagePortrait imageByScalingAndCroppingForSize:targetSize]; + XCTAssertEqual(targetImage.size.width, targetSize.width); + XCTAssertEqual(targetImage.size.height, targetSize.height); + + targetImage = [sourceImageLandscape imageByScalingAndCroppingForSize:targetSize]; + XCTAssertEqual(targetImage.size.width, targetSize.width); + XCTAssertEqual(targetImage.size.height, targetSize.height); +} + +- (void) testImageScaleNoCropForSize { + UIImage *sourceImagePortrait, *sourceImageLandscape, *targetImage; + CGSize targetSize = CGSizeZero; + + sourceImagePortrait = [self createImage:CGRectMake(0, 0, 2448, 3264) orientation:UIImageOrientationUp]; + sourceImageLandscape = [self createImage:CGRectMake(0, 0, 3264, 2448) orientation:UIImageOrientationUp]; + + // test 640x480 + + targetSize = CGSizeMake(480, 640); + + targetImage = [sourceImagePortrait imageByScalingNotCroppingForSize:targetSize]; + XCTAssertEqual(targetImage.size.width, targetSize.width); + XCTAssertEqual(targetImage.size.height, targetSize.height); + + targetSize = CGSizeMake(640, 480); + + targetImage = [sourceImageLandscape imageByScalingNotCroppingForSize:targetSize]; + XCTAssertEqual(targetImage.size.width, targetSize.width); + XCTAssertEqual(targetImage.size.height, targetSize.height); + + + // test 800x600 + + targetSize = CGSizeMake(600, 800); + + targetImage = [sourceImagePortrait imageByScalingNotCroppingForSize:targetSize]; + XCTAssertEqual(targetImage.size.width, targetSize.width); + XCTAssertEqual(targetImage.size.height, targetSize.height); + + targetSize = CGSizeMake(800, 600); + + targetImage = [sourceImageLandscape imageByScalingNotCroppingForSize:targetSize]; + XCTAssertEqual(targetImage.size.width, targetSize.width); + XCTAssertEqual(targetImage.size.height, targetSize.height); + + // test 1024x768 + + targetSize = CGSizeMake(768, 1024); + + targetImage = [sourceImagePortrait imageByScalingNotCroppingForSize:targetSize]; + XCTAssertEqual(targetImage.size.width, targetSize.width); + XCTAssertEqual(targetImage.size.height, targetSize.height); + + targetSize = CGSizeMake(1024, 768); + + targetImage = [sourceImageLandscape imageByScalingNotCroppingForSize:targetSize]; + XCTAssertEqual(targetImage.size.width, targetSize.width); + XCTAssertEqual(targetImage.size.height, targetSize.height); +} + +- (void) testImageCorrectedForOrientation { + UIImage *sourceImagePortrait, *sourceImageLandscape, *targetImage; + CGSize targetSize = CGSizeZero; + + sourceImagePortrait = [self createImage:CGRectMake(0, 0, 2448, 3264) orientation:UIImageOrientationDown]; + sourceImageLandscape = [self createImage:CGRectMake(0, 0, 3264, 2448) orientation:UIImageOrientationDown]; + + // PORTRAIT - image size should be unchanged + + targetSize = CGSizeMake(2448, 3264); + + targetImage = [sourceImagePortrait imageCorrectedForCaptureOrientation:UIImageOrientationUp]; + XCTAssertEqual(targetImage.size.width, targetSize.width); + XCTAssertEqual(targetImage.size.height, targetSize.height); + XCTAssertEqual(targetImage.imageOrientation, UIImageOrientationUp); + + targetImage = [sourceImagePortrait imageCorrectedForCaptureOrientation:UIImageOrientationDown]; + XCTAssertEqual(targetImage.size.width, targetSize.width); + XCTAssertEqual(targetImage.size.height, targetSize.height); + XCTAssertEqual(targetImage.imageOrientation, UIImageOrientationUp); + + targetImage = [sourceImagePortrait imageCorrectedForCaptureOrientation:UIImageOrientationRight]; + XCTAssertEqual(targetImage.size.width, targetSize.width); + XCTAssertEqual(targetImage.size.height, targetSize.height); + XCTAssertEqual(targetImage.imageOrientation, UIImageOrientationUp); + + targetImage = [sourceImagePortrait imageCorrectedForCaptureOrientation:UIImageOrientationLeft]; + XCTAssertEqual(targetImage.size.width, targetSize.width); + XCTAssertEqual(targetImage.size.height, targetSize.height); + XCTAssertEqual(targetImage.imageOrientation, UIImageOrientationUp); + + // LANDSCAPE - image size should be unchanged + + targetSize = CGSizeMake(3264, 2448); + + targetImage = [sourceImageLandscape imageCorrectedForCaptureOrientation:UIImageOrientationUp]; + XCTAssertEqual(targetImage.size.width, targetSize.width); + XCTAssertEqual(targetImage.size.height, targetSize.height); + + targetImage = [sourceImageLandscape imageCorrectedForCaptureOrientation:UIImageOrientationDown]; + XCTAssertEqual(targetImage.size.width, targetSize.width); + XCTAssertEqual(targetImage.size.height, targetSize.height); + + targetImage = [sourceImageLandscape imageCorrectedForCaptureOrientation:UIImageOrientationRight]; + XCTAssertEqual(targetImage.size.width, targetSize.width); + XCTAssertEqual(targetImage.size.height, targetSize.height); + + targetImage = [sourceImageLandscape imageCorrectedForCaptureOrientation:UIImageOrientationLeft]; + XCTAssertEqual(targetImage.size.width, targetSize.width); + XCTAssertEqual(targetImage.size.height, targetSize.height); +} + + +- (void) testRetrieveImage +{ + CDVPictureOptions* pictureOptions = [[CDVPictureOptions alloc] init]; + NSDictionary *infoDict1, *infoDict2; + UIImage* resultImage; + + UIImage* originalImage = [self createImage:CGRectMake(0, 0, 1024, 768) orientation:UIImageOrientationDown]; + UIImage* originalCorrectedForOrientation = [originalImage imageCorrectedForCaptureOrientation]; + + UIImage* editedImage = [self createImage:CGRectMake(0, 0, 800, 600) orientation:UIImageOrientationDown]; + UIImage* scaledImageWithCrop = [originalImage imageByScalingAndCroppingForSize:CGSizeMake(640, 480)]; + UIImage* scaledImageNoCrop = [originalImage imageByScalingNotCroppingForSize:CGSizeMake(640, 480)]; + + infoDict1 = @{ + UIImagePickerControllerOriginalImage : originalImage + }; + + infoDict2 = @{ + UIImagePickerControllerOriginalImage : originalImage, + UIImagePickerControllerEditedImage : editedImage + }; + + // Original with no options + + pictureOptions.allowsEditing = YES; + pictureOptions.targetSize = CGSizeZero; + pictureOptions.cropToSize = NO; + pictureOptions.correctOrientation = NO; + + resultImage = [self.plugin retrieveImage:infoDict1 options:pictureOptions]; + XCTAssertEqualObjects(resultImage, originalImage); + + // Original with no options + + pictureOptions.allowsEditing = YES; + pictureOptions.targetSize = CGSizeZero; + pictureOptions.cropToSize = NO; + pictureOptions.correctOrientation = NO; + + resultImage = [self.plugin retrieveImage:infoDict2 options:pictureOptions]; + XCTAssertEqualObjects(resultImage, editedImage); + + // Original with corrected orientation + + pictureOptions.allowsEditing = YES; + pictureOptions.targetSize = CGSizeZero; + pictureOptions.cropToSize = NO; + pictureOptions.correctOrientation = YES; + + resultImage = [self.plugin retrieveImage:infoDict1 options:pictureOptions]; + XCTAssertNotEqual(resultImage.imageOrientation, originalImage.imageOrientation); + XCTAssertEqual(resultImage.imageOrientation, originalCorrectedForOrientation.imageOrientation); + XCTAssertEqual(resultImage.size.width, originalCorrectedForOrientation.size.width); + XCTAssertEqual(resultImage.size.height, originalCorrectedForOrientation.size.height); + + // Original with targetSize, no crop + + pictureOptions.allowsEditing = YES; + pictureOptions.targetSize = CGSizeMake(640, 480); + pictureOptions.cropToSize = NO; + pictureOptions.correctOrientation = NO; + + resultImage = [self.plugin retrieveImage:infoDict1 options:pictureOptions]; + XCTAssertEqual(resultImage.size.width, scaledImageNoCrop.size.width); + XCTAssertEqual(resultImage.size.height, scaledImageNoCrop.size.height); + + // Original with targetSize, plus crop + + pictureOptions.allowsEditing = YES; + pictureOptions.targetSize = CGSizeMake(640, 480); + pictureOptions.cropToSize = YES; + pictureOptions.correctOrientation = NO; + + resultImage = [self.plugin retrieveImage:infoDict1 options:pictureOptions]; + XCTAssertEqual(resultImage.size.width, scaledImageWithCrop.size.width); + XCTAssertEqual(resultImage.size.height, scaledImageWithCrop.size.height); +} + +- (void) testProcessImage +{ + CDVPictureOptions* pictureOptions = [[CDVPictureOptions alloc] init]; + NSData* resultData; + + UIImage* originalImage = [self createImage:CGRectMake(0, 0, 1024, 768) orientation:UIImageOrientationDown]; + NSData* originalImageDataPNG = UIImagePNGRepresentation(originalImage); + NSData* originalImageDataJPEG = UIImageJPEGRepresentation(originalImage, 1.0); + + // Original, PNG + + pictureOptions.allowsEditing = YES; + pictureOptions.targetSize = CGSizeZero; + pictureOptions.cropToSize = NO; + pictureOptions.correctOrientation = NO; + pictureOptions.encodingType = EncodingTypePNG; + + resultData = [self.plugin processImage:originalImage info:@{} options:pictureOptions]; + XCTAssertEqualObjects([resultData base64EncodedStringWithOptions:0], [originalImageDataPNG base64EncodedStringWithOptions:0]); + + // Original, JPEG, full quality + + pictureOptions.allowsEditing = NO; + pictureOptions.targetSize = CGSizeZero; + pictureOptions.cropToSize = NO; + pictureOptions.correctOrientation = NO; + pictureOptions.encodingType = EncodingTypeJPEG; + + resultData = [self.plugin processImage:originalImage info:@{} options:pictureOptions]; + XCTAssertEqualObjects([resultData base64EncodedStringWithOptions:0], [originalImageDataJPEG base64EncodedStringWithOptions:0]); + + // Original, JPEG, with quality value + + pictureOptions.allowsEditing = YES; + pictureOptions.targetSize = CGSizeZero; + pictureOptions.cropToSize = NO; + pictureOptions.correctOrientation = NO; + pictureOptions.encodingType = EncodingTypeJPEG; + pictureOptions.quality = @(57); + + NSData* originalImageDataJPEGWithQuality = UIImageJPEGRepresentation(originalImage, [pictureOptions.quality floatValue]/ 100.f); + resultData = [self.plugin processImage:originalImage info:@{} options:pictureOptions]; + XCTAssertEqualObjects([resultData base64EncodedStringWithOptions:0], [originalImageDataJPEGWithQuality base64EncodedStringWithOptions:0]); + + // TODO: usesGeolocation is not tested +} + +@end diff --git a/plugins/cordova-plugin-camera/tests/ios/CDVCameraTest/CDVCameraLibTests/Info.plist b/plugins/cordova-plugin-camera/tests/ios/CDVCameraTest/CDVCameraLibTests/Info.plist new file mode 100644 index 0000000..95c8add --- /dev/null +++ b/plugins/cordova-plugin-camera/tests/ios/CDVCameraTest/CDVCameraLibTests/Info.plist @@ -0,0 +1,44 @@ + + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + org.apache.cordova.$(PRODUCT_NAME:rfc1034identifier) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + BNDL + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1 + + diff --git a/plugins/cordova-plugin-camera/tests/ios/CDVCameraTest/CDVCameraTest.xcodeproj/project.pbxproj b/plugins/cordova-plugin-camera/tests/ios/CDVCameraTest/CDVCameraTest.xcodeproj/project.pbxproj new file mode 100644 index 0000000..3e5a4c0 --- /dev/null +++ b/plugins/cordova-plugin-camera/tests/ios/CDVCameraTest/CDVCameraTest.xcodeproj/project.pbxproj @@ -0,0 +1,561 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 46; + objects = { + +/* Begin PBXBuildFile section */ + 30486FEB1A40DC350065C233 /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 30486FEA1A40DC350065C233 /* UIKit.framework */; }; + 30486FED1A40DC3B0065C233 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 30486FEC1A40DC3A0065C233 /* Foundation.framework */; }; + 30486FF91A40DCC70065C233 /* CDVCamera.m in Sources */ = {isa = PBXBuildFile; fileRef = 30486FF31A40DCC70065C233 /* CDVCamera.m */; }; + 30486FFA1A40DCC70065C233 /* CDVJpegHeaderWriter.m in Sources */ = {isa = PBXBuildFile; fileRef = 30486FF61A40DCC70065C233 /* CDVJpegHeaderWriter.m */; }; + 30486FFB1A40DCC70065C233 /* UIImage+CropScaleOrientation.m in Sources */ = {isa = PBXBuildFile; fileRef = 30486FF81A40DCC70065C233 /* UIImage+CropScaleOrientation.m */; }; + 304870011A40DD620065C233 /* CoreGraphics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 30486FFE1A40DD180065C233 /* CoreGraphics.framework */; }; + 304870021A40DD860065C233 /* CoreGraphics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 30486FFE1A40DD180065C233 /* CoreGraphics.framework */; }; + 304870031A40DD8C0065C233 /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 30486FEA1A40DC350065C233 /* UIKit.framework */; }; + 304870051A40DD9A0065C233 /* MobileCoreServices.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 304870041A40DD9A0065C233 /* MobileCoreServices.framework */; }; + 304870071A40DDAC0065C233 /* AssetsLibrary.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 304870061A40DDAC0065C233 /* AssetsLibrary.framework */; }; + 304870091A40DDB90065C233 /* CoreLocation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 304870081A40DDB90065C233 /* CoreLocation.framework */; }; + 3048700B1A40DDF30065C233 /* ImageIO.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 3048700A1A40DDF30065C233 /* ImageIO.framework */; }; + 308F59B11A4228730031A4D4 /* libCordova.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 7E9F519019DA0F8300DA31AC /* libCordova.a */; }; + 7E9F51B119DA114400DA31AC /* CameraTest.m in Sources */ = {isa = PBXBuildFile; fileRef = 7E9F51B019DA114400DA31AC /* CameraTest.m */; }; + 7E9F51B919DA1B1600DA31AC /* libCDVCameraLib.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 7E9F519519DA102000DA31AC /* libCDVCameraLib.a */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 30486FFC1A40DCE80065C233 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 7E9F518B19DA0F8300DA31AC /* CordovaLib.xcodeproj */; + proxyType = 1; + remoteGlobalIDString = D2AAC07D0554694100DB518D; + remoteInfo = CordovaLib; + }; + 7E9F518F19DA0F8300DA31AC /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 7E9F518B19DA0F8300DA31AC /* CordovaLib.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 68A32D7114102E1C006B237C; + remoteInfo = CordovaLib; + }; + 7E9F51AC19DA10DE00DA31AC /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 7E9F517219DA09CE00DA31AC /* Project object */; + proxyType = 1; + remoteGlobalIDString = 7E9F519419DA102000DA31AC; + remoteInfo = CDVCameraLib; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 7E9F519319DA102000DA31AC /* CopyFiles */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = "include/$(PRODUCT_NAME)"; + dstSubfolderSpec = 16; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 30486FEA1A40DC350065C233 /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.1.sdk/System/Library/Frameworks/UIKit.framework; sourceTree = DEVELOPER_DIR; }; + 30486FEC1A40DC3A0065C233 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.1.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; }; + 30486FF21A40DCC70065C233 /* CDVCamera.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDVCamera.h; sourceTree = ""; }; + 30486FF31A40DCC70065C233 /* CDVCamera.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDVCamera.m; sourceTree = ""; }; + 30486FF41A40DCC70065C233 /* CDVExif.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDVExif.h; sourceTree = ""; }; + 30486FF51A40DCC70065C233 /* CDVJpegHeaderWriter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDVJpegHeaderWriter.h; sourceTree = ""; }; + 30486FF61A40DCC70065C233 /* CDVJpegHeaderWriter.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDVJpegHeaderWriter.m; sourceTree = ""; }; + 30486FF71A40DCC70065C233 /* UIImage+CropScaleOrientation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIImage+CropScaleOrientation.h"; sourceTree = ""; }; + 30486FF81A40DCC70065C233 /* UIImage+CropScaleOrientation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIImage+CropScaleOrientation.m"; sourceTree = ""; }; + 30486FFE1A40DD180065C233 /* CoreGraphics.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreGraphics.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.1.sdk/System/Library/Frameworks/CoreGraphics.framework; sourceTree = DEVELOPER_DIR; }; + 304870041A40DD9A0065C233 /* MobileCoreServices.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = MobileCoreServices.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.1.sdk/System/Library/Frameworks/MobileCoreServices.framework; sourceTree = DEVELOPER_DIR; }; + 304870061A40DDAC0065C233 /* AssetsLibrary.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AssetsLibrary.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.1.sdk/System/Library/Frameworks/AssetsLibrary.framework; sourceTree = DEVELOPER_DIR; }; + 304870081A40DDB90065C233 /* CoreLocation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreLocation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.1.sdk/System/Library/Frameworks/CoreLocation.framework; sourceTree = DEVELOPER_DIR; }; + 3048700A1A40DDF30065C233 /* ImageIO.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = ImageIO.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.1.sdk/System/Library/Frameworks/ImageIO.framework; sourceTree = DEVELOPER_DIR; }; + 7E9F518B19DA0F8300DA31AC /* CordovaLib.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = CordovaLib.xcodeproj; path = "../node_modules/cordova-ios/CordovaLib/CordovaLib.xcodeproj"; sourceTree = ""; }; + 7E9F519519DA102000DA31AC /* libCDVCameraLib.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libCDVCameraLib.a; sourceTree = BUILT_PRODUCTS_DIR; }; + 7E9F519F19DA102000DA31AC /* CDVCameraLibTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = CDVCameraLibTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 7E9F51A219DA102000DA31AC /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 7E9F51B019DA114400DA31AC /* CameraTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CameraTest.m; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 7E9F519219DA102000DA31AC /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 308F59B11A4228730031A4D4 /* libCordova.a in Frameworks */, + 304870011A40DD620065C233 /* CoreGraphics.framework in Frameworks */, + 30486FED1A40DC3B0065C233 /* Foundation.framework in Frameworks */, + 30486FEB1A40DC350065C233 /* UIKit.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 7E9F519C19DA102000DA31AC /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 3048700B1A40DDF30065C233 /* ImageIO.framework in Frameworks */, + 304870091A40DDB90065C233 /* CoreLocation.framework in Frameworks */, + 304870071A40DDAC0065C233 /* AssetsLibrary.framework in Frameworks */, + 304870051A40DD9A0065C233 /* MobileCoreServices.framework in Frameworks */, + 304870031A40DD8C0065C233 /* UIKit.framework in Frameworks */, + 304870021A40DD860065C233 /* CoreGraphics.framework in Frameworks */, + 7E9F51B919DA1B1600DA31AC /* libCDVCameraLib.a in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 30486FF11A40DCC70065C233 /* CDVCameraLib */ = { + isa = PBXGroup; + children = ( + 30486FF21A40DCC70065C233 /* CDVCamera.h */, + 30486FF31A40DCC70065C233 /* CDVCamera.m */, + 30486FF41A40DCC70065C233 /* CDVExif.h */, + 30486FF51A40DCC70065C233 /* CDVJpegHeaderWriter.h */, + 30486FF61A40DCC70065C233 /* CDVJpegHeaderWriter.m */, + 30486FF71A40DCC70065C233 /* UIImage+CropScaleOrientation.h */, + 30486FF81A40DCC70065C233 /* UIImage+CropScaleOrientation.m */, + ); + name = CDVCameraLib; + path = ../../../src/ios; + sourceTree = ""; + }; + 308F59B01A4227A60031A4D4 /* Frameworks */ = { + isa = PBXGroup; + children = ( + 3048700A1A40DDF30065C233 /* ImageIO.framework */, + 304870081A40DDB90065C233 /* CoreLocation.framework */, + 304870061A40DDAC0065C233 /* AssetsLibrary.framework */, + 304870041A40DD9A0065C233 /* MobileCoreServices.framework */, + 30486FFE1A40DD180065C233 /* CoreGraphics.framework */, + 30486FEC1A40DC3A0065C233 /* Foundation.framework */, + 30486FEA1A40DC350065C233 /* UIKit.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; + 7E9F517119DA09CE00DA31AC = { + isa = PBXGroup; + children = ( + 7E9F518B19DA0F8300DA31AC /* CordovaLib.xcodeproj */, + 308F59B01A4227A60031A4D4 /* Frameworks */, + 30486FF11A40DCC70065C233 /* CDVCameraLib */, + 7E9F51A019DA102000DA31AC /* CDVCameraLibTests */, + 7E9F517D19DA0A0A00DA31AC /* Products */, + ); + sourceTree = ""; + }; + 7E9F517D19DA0A0A00DA31AC /* Products */ = { + isa = PBXGroup; + children = ( + 7E9F519519DA102000DA31AC /* libCDVCameraLib.a */, + 7E9F519F19DA102000DA31AC /* CDVCameraLibTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 7E9F518C19DA0F8300DA31AC /* Products */ = { + isa = PBXGroup; + children = ( + 7E9F519019DA0F8300DA31AC /* libCordova.a */, + ); + name = Products; + sourceTree = ""; + }; + 7E9F51A019DA102000DA31AC /* CDVCameraLibTests */ = { + isa = PBXGroup; + children = ( + 7E9F51A119DA102000DA31AC /* Supporting Files */, + 7E9F51B019DA114400DA31AC /* CameraTest.m */, + ); + path = CDVCameraLibTests; + sourceTree = ""; + }; + 7E9F51A119DA102000DA31AC /* Supporting Files */ = { + isa = PBXGroup; + children = ( + 7E9F51A219DA102000DA31AC /* Info.plist */, + ); + name = "Supporting Files"; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 7E9F519419DA102000DA31AC /* CDVCameraLib */ = { + isa = PBXNativeTarget; + buildConfigurationList = 7E9F51A319DA102000DA31AC /* Build configuration list for PBXNativeTarget "CDVCameraLib" */; + buildPhases = ( + 7E9F519119DA102000DA31AC /* Sources */, + 7E9F519219DA102000DA31AC /* Frameworks */, + 7E9F519319DA102000DA31AC /* CopyFiles */, + ); + buildRules = ( + ); + dependencies = ( + 30486FFD1A40DCE80065C233 /* PBXTargetDependency */, + ); + name = CDVCameraLib; + productName = CDVCameraLib; + productReference = 7E9F519519DA102000DA31AC /* libCDVCameraLib.a */; + productType = "com.apple.product-type.library.static"; + }; + 7E9F519E19DA102000DA31AC /* CDVCameraLibTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 7E9F51A619DA102000DA31AC /* Build configuration list for PBXNativeTarget "CDVCameraLibTests" */; + buildPhases = ( + 7E9F519B19DA102000DA31AC /* Sources */, + 7E9F519C19DA102000DA31AC /* Frameworks */, + 7E9F519D19DA102000DA31AC /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 7E9F51AD19DA10DE00DA31AC /* PBXTargetDependency */, + ); + name = CDVCameraLibTests; + productName = CDVCameraLibTests; + productReference = 7E9F519F19DA102000DA31AC /* CDVCameraLibTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 7E9F517219DA09CE00DA31AC /* Project object */ = { + isa = PBXProject; + attributes = { + LastUpgradeCheck = 0610; + TargetAttributes = { + 7E9F519419DA102000DA31AC = { + CreatedOnToolsVersion = 6.0; + }; + 7E9F519E19DA102000DA31AC = { + CreatedOnToolsVersion = 6.0; + }; + }; + }; + buildConfigurationList = 7E9F517519DA09CE00DA31AC /* Build configuration list for PBXProject "CDVCameraTest" */; + compatibilityVersion = "Xcode 3.2"; + developmentRegion = English; + hasScannedForEncodings = 0; + knownRegions = ( + en, + ); + mainGroup = 7E9F517119DA09CE00DA31AC; + productRefGroup = 7E9F517D19DA0A0A00DA31AC /* Products */; + projectDirPath = ""; + projectReferences = ( + { + ProductGroup = 7E9F518C19DA0F8300DA31AC /* Products */; + ProjectRef = 7E9F518B19DA0F8300DA31AC /* CordovaLib.xcodeproj */; + }, + ); + projectRoot = ""; + targets = ( + 7E9F519419DA102000DA31AC /* CDVCameraLib */, + 7E9F519E19DA102000DA31AC /* CDVCameraLibTests */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXReferenceProxy section */ + 7E9F519019DA0F8300DA31AC /* libCordova.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = libCordova.a; + remoteRef = 7E9F518F19DA0F8300DA31AC /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; +/* End PBXReferenceProxy section */ + +/* Begin PBXResourcesBuildPhase section */ + 7E9F519D19DA102000DA31AC /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 7E9F519119DA102000DA31AC /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 30486FF91A40DCC70065C233 /* CDVCamera.m in Sources */, + 30486FFB1A40DCC70065C233 /* UIImage+CropScaleOrientation.m in Sources */, + 30486FFA1A40DCC70065C233 /* CDVJpegHeaderWriter.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 7E9F519B19DA102000DA31AC /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 7E9F51B119DA114400DA31AC /* CameraTest.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 30486FFD1A40DCE80065C233 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = CordovaLib; + targetProxy = 30486FFC1A40DCE80065C233 /* PBXContainerItemProxy */; + }; + 7E9F51AD19DA10DE00DA31AC /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 7E9F519419DA102000DA31AC /* CDVCameraLib */; + targetProxy = 7E9F51AC19DA10DE00DA31AC /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin XCBuildConfiguration section */ + 7E9F517619DA09CE00DA31AC /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ONLY_ACTIVE_ARCH = YES; + }; + name = Debug; + }; + 7E9F517719DA09CE00DA31AC /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + }; + name = Release; + }; + 7E9F51A419DA102000DA31AC /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_SYMBOLS_PRIVATE_EXTERN = NO; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + HEADER_SEARCH_PATHS = ( + "$(inherited)", + "\"$(TARGET_BUILD_DIR)/usr/local/lib/include\"", + "\"$(OBJROOT)/UninstalledProducts/include\"", + "\"$(BUILT_PRODUCTS_DIR)\"", + ); + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + OTHER_LDFLAGS = "-ObjC"; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + }; + name = Debug; + }; + 7E9F51A519DA102000DA31AC /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = YES; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + HEADER_SEARCH_PATHS = ( + "$(inherited)", + "\"$(TARGET_BUILD_DIR)/usr/local/lib/include\"", + "\n\"$(OBJROOT)/UninstalledProducts/include\"\n\"$(BUILT_PRODUCTS_DIR)\"", + ); + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + MTL_ENABLE_DEBUG_INFO = NO; + OTHER_LDFLAGS = "-ObjC"; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 7E9F51A719DA102000DA31AC /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + FRAMEWORK_SEARCH_PATHS = ( + "$(SDKROOT)/Developer/Library/Frameworks", + "$(inherited)", + ); + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_SYMBOLS_PRIVATE_EXTERN = NO; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + INFOPLIST_FILE = CDVCameraLibTests/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + OTHER_LDFLAGS = ( + "$(inherited)", + "-framework", + XCTest, + "-all_load", + "-ObjC", + ); + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = iphoneos; + }; + name = Debug; + }; + 7E9F51A819DA102000DA31AC /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = YES; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + FRAMEWORK_SEARCH_PATHS = ( + "$(SDKROOT)/Developer/Library/Frameworks", + "$(inherited)", + ); + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + INFOPLIST_FILE = CDVCameraLibTests/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MTL_ENABLE_DEBUG_INFO = NO; + OTHER_LDFLAGS = ( + "$(inherited)", + "-framework", + XCTest, + "-all_load", + "-ObjC", + ); + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = iphoneos; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 7E9F517519DA09CE00DA31AC /* Build configuration list for PBXProject "CDVCameraTest" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 7E9F517619DA09CE00DA31AC /* Debug */, + 7E9F517719DA09CE00DA31AC /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 7E9F51A319DA102000DA31AC /* Build configuration list for PBXNativeTarget "CDVCameraLib" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 7E9F51A419DA102000DA31AC /* Debug */, + 7E9F51A519DA102000DA31AC /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 7E9F51A619DA102000DA31AC /* Build configuration list for PBXNativeTarget "CDVCameraLibTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 7E9F51A719DA102000DA31AC /* Debug */, + 7E9F51A819DA102000DA31AC /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 7E9F517219DA09CE00DA31AC /* Project object */; +} diff --git a/plugins/cordova-plugin-camera/tests/ios/CDVCameraTest/CDVCameraTest.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/plugins/cordova-plugin-camera/tests/ios/CDVCameraTest/CDVCameraTest.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..98498f8 --- /dev/null +++ b/plugins/cordova-plugin-camera/tests/ios/CDVCameraTest/CDVCameraTest.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/plugins/cordova-plugin-camera/tests/ios/CDVCameraTest/CDVCameraTest.xcodeproj/project.xcworkspace/xcshareddata/CDVCameraTest.xccheckout b/plugins/cordova-plugin-camera/tests/ios/CDVCameraTest/CDVCameraTest.xcodeproj/project.xcworkspace/xcshareddata/CDVCameraTest.xccheckout new file mode 100644 index 0000000..2a654cb --- /dev/null +++ b/plugins/cordova-plugin-camera/tests/ios/CDVCameraTest/CDVCameraTest.xcodeproj/project.xcworkspace/xcshareddata/CDVCameraTest.xccheckout @@ -0,0 +1,41 @@ + + + + + IDESourceControlProjectFavoriteDictionaryKey + + IDESourceControlProjectIdentifier + 6BE9AD73-1B9F-4362-98D7-DC631BEC6185 + IDESourceControlProjectName + CDVCameraTest + IDESourceControlProjectOriginsDictionary + + BEF5A5D0FF64801E558286389440357A9233D7DB + https://git-wip-us.apache.org/repos/asf/cordova-plugin-camera.git + + IDESourceControlProjectPath + tests/ios/CDVCameraTest/CDVCameraTest.xcodeproj + IDESourceControlProjectRelativeInstallPathDictionary + + BEF5A5D0FF64801E558286389440357A9233D7DB + ../../../../.. + + IDESourceControlProjectURL + https://git-wip-us.apache.org/repos/asf/cordova-plugin-camera.git + IDESourceControlProjectVersion + 111 + IDESourceControlProjectWCCIdentifier + BEF5A5D0FF64801E558286389440357A9233D7DB + IDESourceControlProjectWCConfigurations + + + IDESourceControlRepositoryExtensionIdentifierKey + public.vcs.git + IDESourceControlWCCIdentifierKey + BEF5A5D0FF64801E558286389440357A9233D7DB + IDESourceControlWCCName + cordova-plugin-camera + + + + diff --git a/plugins/cordova-plugin-camera/tests/ios/CDVCameraTest/CDVCameraTest.xcodeproj/xcshareddata/xcschemes/CDVCameraLib.xcscheme b/plugins/cordova-plugin-camera/tests/ios/CDVCameraTest/CDVCameraTest.xcodeproj/xcshareddata/xcschemes/CDVCameraLib.xcscheme new file mode 100644 index 0000000..f0a8304 --- /dev/null +++ b/plugins/cordova-plugin-camera/tests/ios/CDVCameraTest/CDVCameraTest.xcodeproj/xcshareddata/xcschemes/CDVCameraLib.xcscheme @@ -0,0 +1,77 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/cordova-plugin-camera/tests/ios/CDVCameraTest/CDVCameraTest.xcodeproj/xcshareddata/xcschemes/CDVCameraLibTests.xcscheme b/plugins/cordova-plugin-camera/tests/ios/CDVCameraTest/CDVCameraTest.xcodeproj/xcshareddata/xcschemes/CDVCameraLibTests.xcscheme new file mode 100644 index 0000000..b5d2603 --- /dev/null +++ b/plugins/cordova-plugin-camera/tests/ios/CDVCameraTest/CDVCameraTest.xcodeproj/xcshareddata/xcschemes/CDVCameraLibTests.xcscheme @@ -0,0 +1,96 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/cordova-plugin-camera/tests/ios/README.md b/plugins/cordova-plugin-camera/tests/ios/README.md new file mode 100644 index 0000000..b839310 --- /dev/null +++ b/plugins/cordova-plugin-camera/tests/ios/README.md @@ -0,0 +1,40 @@ + + +# iOS Tests for CDVCamera + +You need to install `node.js` to pull in `cordova-ios`. + +First install cordova-ios: + + npm install + +... in the current folder. + + +# Testing from Xcode + +1. Launch the `CDVCameraTest.xcworkspace` file. +2. Choose "CDVCameraLibTests" from the scheme drop-down menu +3. Click and hold on the `Play` button, and choose the `Wrench` icon to run the tests + + +# Testing from the command line + + npm test diff --git a/plugins/cordova-plugin-camera/tests/ios/doc/de/README.md b/plugins/cordova-plugin-camera/tests/ios/doc/de/README.md new file mode 100644 index 0000000..0b3ae96 --- /dev/null +++ b/plugins/cordova-plugin-camera/tests/ios/doc/de/README.md @@ -0,0 +1,39 @@ + + +# iOS-Tests für CDVCamera + +Sie müssen installieren `node.js` in `Cordova-Ios` zu ziehen. + +Installieren Sie Cordova-Ios zum ersten Mal: + + npm install + + +... im aktuellen Ordner. + +# Testen von Xcode + + 1. Starten Sie die Datei `CDVCameraTest.xcworkspace` . + 2. Wählen Sie im Dropdown-Schema "CDVCameraLibTests" + 3. Klicken Sie und halten Sie auf den `Play` -Button und wählen Sie das `Schraubenschlüssel` -Symbol zum Ausführen der tests + +# Tests von der Befehlszeile aus + + npm test \ No newline at end of file diff --git a/plugins/cordova-plugin-camera/tests/ios/doc/es/README.md b/plugins/cordova-plugin-camera/tests/ios/doc/es/README.md new file mode 100644 index 0000000..7240746 --- /dev/null +++ b/plugins/cordova-plugin-camera/tests/ios/doc/es/README.md @@ -0,0 +1,39 @@ + + +# Pruebas de iOS para CDVCamera + +Necesita instalar `node.js` en `Córdoba-ios`. + +Primero instalar cordova-ios: + + npm install + + +... en la carpeta actual. + +# Prueba de Xcode + + 1. Iniciar el archivo `CDVCameraTest.xcworkspace` . + 2. Elija "CDVCameraLibTests" en el menú de lista desplegable esquema + 3. Haga clic y mantenga el botón de `Play` y elegir el icono de `llave inglesa` para ejecutar las pruebas + +# Pruebas desde la línea de comandos + + npm test \ No newline at end of file diff --git a/plugins/cordova-plugin-camera/tests/ios/doc/fr/README.md b/plugins/cordova-plugin-camera/tests/ios/doc/fr/README.md new file mode 100644 index 0000000..4c656a3 --- /dev/null +++ b/plugins/cordova-plugin-camera/tests/ios/doc/fr/README.md @@ -0,0 +1,39 @@ + + +# Tests d'iOS pour CDVCamera + +Vous devez installer `node.js` à `cordova-ios`. + +Commencez par installer cordova-ios : + + npm install + + +... dans le dossier actuel. + +# Tests de Xcode + + 1. Lancez le fichier `CDVCameraTest.xcworkspace` . + 2. Choisissez « CDVCameraLibTests » dans le menu déroulant de régime + 3. Cliquez et maintenez sur la touche `Play` et cliquez sur l'icône de `clé` pour exécuter les tests + +# Test de la ligne de commande + + npm test \ No newline at end of file diff --git a/plugins/cordova-plugin-camera/tests/ios/doc/it/README.md b/plugins/cordova-plugin-camera/tests/ios/doc/it/README.md new file mode 100644 index 0000000..af02253 --- /dev/null +++ b/plugins/cordova-plugin-camera/tests/ios/doc/it/README.md @@ -0,0 +1,39 @@ + + +# Test di iOS per CDVCamera + +È necessario installare `node. js` per tirare in `cordova-ios`. + +In primo luogo installare cordova-ios: + + npm install + + +... nella cartella corrente. + +# Test da Xcode + + 1. Lanciare il file `CDVCameraTest.xcworkspace` . + 2. Scegli "CDVCameraLibTests" dal menu a discesa Schema + 3. Fare clic e tenere premuto il pulsante `Play` e scegliere l'icona della `chiave inglese` per eseguire i test + +# Test dalla riga di comando + + npm test \ No newline at end of file diff --git a/plugins/cordova-plugin-camera/tests/ios/doc/ja/README.md b/plugins/cordova-plugin-camera/tests/ios/doc/ja/README.md new file mode 100644 index 0000000..ca0fe84 --- /dev/null +++ b/plugins/cordova-plugin-camera/tests/ios/doc/ja/README.md @@ -0,0 +1,39 @@ + + +# CDVCamera の iOS のテスト + +`Node.js` `コルドバ`ios をプルするをインストールする必要があります。. + +コルドバ ios をインストールします。 + + npm install + + +現在のフォルダーに. + +# Xcode からテスト + + 1. `CDVCameraTest.xcworkspace`ファイルを起動します。 + 2. スキーム] ドロップダウン メニューから"CDVCameraLibTests"を選択します。 + 3. クリックし、`再生`ボタンを押し、テストを実行する`レンチ`のアイコンを選択 + +# コマンドラインからテスト + + npm test \ No newline at end of file diff --git a/plugins/cordova-plugin-camera/tests/ios/doc/ko/README.md b/plugins/cordova-plugin-camera/tests/ios/doc/ko/README.md new file mode 100644 index 0000000..3ad9cfc --- /dev/null +++ b/plugins/cordova-plugin-camera/tests/ios/doc/ko/README.md @@ -0,0 +1,39 @@ + + +# CDVCamera에 대 한 iOS 테스트 + +`Node.js` `코르도바` ios에서를 설치 해야. + +코르도바-ios를 설치 하는 첫번째는: + + npm install + + +현재 폴더에.... + +# Xcode에서 테스트 + + 1. `CDVCameraTest.xcworkspace` 파일을 시작 합니다. + 2. 구성표 드롭 다운 메뉴에서 "CDVCameraLibTests"를 선택 + 3. 클릭 하 고 `재생` 버튼에는 테스트를 실행 하려면 `공구 모양` 아이콘을 선택 + +# 명령줄에서 테스트 + + npm test \ No newline at end of file diff --git a/plugins/cordova-plugin-camera/tests/ios/doc/pl/README.md b/plugins/cordova-plugin-camera/tests/ios/doc/pl/README.md new file mode 100644 index 0000000..82caa41 --- /dev/null +++ b/plugins/cordova-plugin-camera/tests/ios/doc/pl/README.md @@ -0,0 +1,39 @@ + + +# iOS testy dla CDVCamera + +Musisz zainstalować `node.js` ciągnąć w `cordova-ios`. + +Najpierw zainstalować cordova-ios: + + npm install + + +... w folderze bieżącym. + +# Badania z Xcode + + 1. Uruchom plik `CDVCameraTest.xcworkspace` . + 2. Wybierz z menu rozwijanego systemu "CDVCameraLibTests" + 3. Kliknij i przytrzymaj przycisk `Play` i wybrać ikonę `klucz` do testów + +# Badania z wiersza polecenia + + npm test \ No newline at end of file diff --git a/plugins/cordova-plugin-camera/tests/ios/doc/zh/README.md b/plugins/cordova-plugin-camera/tests/ios/doc/zh/README.md new file mode 100644 index 0000000..5312987 --- /dev/null +++ b/plugins/cordova-plugin-camera/tests/ios/doc/zh/README.md @@ -0,0 +1,39 @@ + + +# CDVCamera 的 iOS 測試 + +您需要安裝`node.js`拉`科爾多瓦 ios`中. + +第一次安裝科爾多瓦 ios: + + npm install + + +在當前資料夾中。 + +# 從 Xcode 測試 + + 1. 啟動`CDVCameraTest.xcworkspace`檔。 + 2. 從方案下拉式功能表中選擇"CDVCameraLibTests" + 3. 按一下並堅持`播放`按鈕,然後選擇要運行的測試的`扳手`圖示 + +# 從命令列測試 + + npm test \ No newline at end of file diff --git a/plugins/cordova-plugin-camera/tests/ios/package.json b/plugins/cordova-plugin-camera/tests/ios/package.json new file mode 100644 index 0000000..4b9486f --- /dev/null +++ b/plugins/cordova-plugin-camera/tests/ios/package.json @@ -0,0 +1,13 @@ +{ + "name": "cordova-plugin-camera-test-ios", + "version": "1.0.0", + "description": "iOS Unit Tests for Camera Plugin", + "author": "Apache Software Foundation", + "license": "Apache Version 2.0", + "dependencies": { + "cordova-ios": "*" + }, + "scripts": { + "test": "xcodebuild -scheme CordovaLib && xcodebuild test -scheme CDVCameraLibTests -destination 'platform=iOS Simulator,name=iPhone 5'" + } +} diff --git a/plugins/cordova-plugin-camera/tests/package.json b/plugins/cordova-plugin-camera/tests/package.json new file mode 100644 index 0000000..646e22c --- /dev/null +++ b/plugins/cordova-plugin-camera/tests/package.json @@ -0,0 +1,14 @@ +{ + "name": "cordova-plugin-camera-tests", + "version": "2.4.1-dev", + "description": "", + "cordova": { + "id": "cordova-plugin-camera-tests", + "platforms": [] + }, + "keywords": [ + "ecosystem:cordova" + ], + "author": "", + "license": "Apache 2.0" +} diff --git a/plugins/cordova-plugin-camera/tests/plugin.xml b/plugins/cordova-plugin-camera/tests/plugin.xml new file mode 100644 index 0000000..073ef28 --- /dev/null +++ b/plugins/cordova-plugin-camera/tests/plugin.xml @@ -0,0 +1,33 @@ + + + + + Cordova Camera Plugin Tests + Apache 2.0 + + + + + + diff --git a/plugins/cordova-plugin-camera/tests/tests.js b/plugins/cordova-plugin-camera/tests/tests.js new file mode 100644 index 0000000..0c85188 --- /dev/null +++ b/plugins/cordova-plugin-camera/tests/tests.js @@ -0,0 +1,510 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ + +/* globals Camera, resolveLocalFileSystemURL, FileEntry, CameraPopoverOptions, FileTransfer, FileUploadOptions, LocalFileSystem, MSApp */ +/* jshint jasmine: true */ + +exports.defineAutoTests = function () { + describe('Camera (navigator.camera)', function () { + it("should exist", function () { + expect(navigator.camera).toBeDefined(); + }); + + it("should contain a getPicture function", function () { + expect(navigator.camera.getPicture).toBeDefined(); + expect(typeof navigator.camera.getPicture == 'function').toBe(true); + }); + }); + + describe('Camera Constants (window.Camera + navigator.camera)', function () { + it("camera.spec.1 window.Camera should exist", function () { + expect(window.Camera).toBeDefined(); + }); + + it("camera.spec.2 should contain three DestinationType constants", function () { + expect(Camera.DestinationType.DATA_URL).toBe(0); + expect(Camera.DestinationType.FILE_URI).toBe(1); + expect(Camera.DestinationType.NATIVE_URI).toBe(2); + expect(navigator.camera.DestinationType.DATA_URL).toBe(0); + expect(navigator.camera.DestinationType.FILE_URI).toBe(1); + expect(navigator.camera.DestinationType.NATIVE_URI).toBe(2); + }); + + it("camera.spec.3 should contain two EncodingType constants", function () { + expect(Camera.EncodingType.JPEG).toBe(0); + expect(Camera.EncodingType.PNG).toBe(1); + expect(navigator.camera.EncodingType.JPEG).toBe(0); + expect(navigator.camera.EncodingType.PNG).toBe(1); + }); + + it("camera.spec.4 should contain three MediaType constants", function () { + expect(Camera.MediaType.PICTURE).toBe(0); + expect(Camera.MediaType.VIDEO).toBe(1); + expect(Camera.MediaType.ALLMEDIA).toBe(2); + expect(navigator.camera.MediaType.PICTURE).toBe(0); + expect(navigator.camera.MediaType.VIDEO).toBe(1); + expect(navigator.camera.MediaType.ALLMEDIA).toBe(2); + }); + + it("camera.spec.5 should contain three PictureSourceType constants", function () { + expect(Camera.PictureSourceType.PHOTOLIBRARY).toBe(0); + expect(Camera.PictureSourceType.CAMERA).toBe(1); + expect(Camera.PictureSourceType.SAVEDPHOTOALBUM).toBe(2); + expect(navigator.camera.PictureSourceType.PHOTOLIBRARY).toBe(0); + expect(navigator.camera.PictureSourceType.CAMERA).toBe(1); + expect(navigator.camera.PictureSourceType.SAVEDPHOTOALBUM).toBe(2); + }); + }); +}; + + +/******************************************************************************/ +/******************************************************************************/ +/******************************************************************************/ + +exports.defineManualTests = function (contentEl, createActionButton) { + var pictureUrl = null; + var fileObj = null; + var fileEntry = null; + var pageStartTime = +new Date(); + + //default camera options + var camQualityDefault = ['50', 50]; + var camDestinationTypeDefault = ['FILE_URI', 1]; + var camPictureSourceTypeDefault = ['CAMERA', 1]; + var camAllowEditDefault = ['allowEdit', false]; + var camEncodingTypeDefault = ['JPEG', 0]; + var camMediaTypeDefault = ['mediaType', 0]; + var camCorrectOrientationDefault = ['correctOrientation', false]; + var camSaveToPhotoAlbumDefault = ['saveToPhotoAlbum', true]; + + function log(value) { + console.log(value); + document.getElementById('camera_status').textContent += (new Date() - pageStartTime) / 1000 + ': ' + value + '\n'; + } + + function clearStatus() { + document.getElementById('camera_status').innerHTML = ''; + document.getElementById('camera_image').src = 'about:blank'; + var canvas = document.getElementById('canvas'); + canvas.width = canvas.height = 1; + pictureUrl = null; + fileObj = null; + fileEntry = null; + } + + function setPicture(url, callback) { + try { + window.atob(url); + // if we got here it is a base64 string (DATA_URL) + url = "data:image/jpeg;base64," + url; + } catch (e) { + // not DATA_URL + } + log('URL: "' + url.slice(0, 90) + '"'); + + pictureUrl = url; + var img = document.getElementById('camera_image'); + var startTime = new Date(); + img.src = url; + img.onload = function () { + log('Img size: ' + img.naturalWidth + 'x' + img.naturalHeight); + log('Image tag load time: ' + (new Date() - startTime)); + if (callback) { + callback(); + } + }; + } + + function onGetPictureError(e) { + log('Error getting picture: ' + (e.code || e)); + } + + function getPictureWin(data) { + setPicture(data); + // TODO: Fix resolveLocalFileSystemURI to work with native-uri. + if (pictureUrl.indexOf('file:') === 0 || pictureUrl.indexOf('content:') === 0 || pictureUrl.indexOf('ms-appdata:') === 0 || pictureUrl.indexOf('assets-library:') === 0) { + resolveLocalFileSystemURL(data, function (e) { + fileEntry = e; + logCallback('resolveLocalFileSystemURL()', true)(e.toURL()); + readFile(); + }, logCallback('resolveLocalFileSystemURL()', false)); + } else if (pictureUrl.indexOf('data:image/jpeg;base64') === 0) { + // do nothing + } else { + var path = pictureUrl.replace(/^file:\/\/(localhost)?/, '').replace(/%20/g, ' '); + fileEntry = new FileEntry('image_name.png', path); + } + } + + function getPicture() { + clearStatus(); + var options = extractOptions(); + log('Getting picture with options: ' + JSON.stringify(options)); + var popoverHandle = navigator.camera.getPicture(getPictureWin, onGetPictureError, options); + + // Reposition the popover if the orientation changes. + window.onorientationchange = function () { + var newPopoverOptions = new CameraPopoverOptions(0, 0, 100, 100, 0); + popoverHandle.setPosition(newPopoverOptions); + }; + } + + function uploadImage() { + var ft = new FileTransfer(), + options = new FileUploadOptions(); + options.fileKey = "photo"; + options.fileName = 'test.jpg'; + options.mimeType = "image/jpeg"; + ft.onprogress = function (progressEvent) { + console.log('progress: ' + progressEvent.loaded + ' of ' + progressEvent.total); + }; + var server = "http://sheltered-retreat-43956.herokuapp.com"; + + ft.upload(pictureUrl, server + '/upload', win, fail, options); + function win(information_back) { + log('upload complete'); + } + function fail(message) { + log('upload failed: ' + JSON.stringify(message)); + } + } + + function logCallback(apiName, success) { + return function () { + log('Call to ' + apiName + (success ? ' success: ' : ' failed: ') + JSON.stringify([].slice.call(arguments))); + }; + } + + /** + * Select image from library using a NATIVE_URI destination type + * This calls FileEntry.getMetadata, FileEntry.setMetadata, FileEntry.getParent, FileEntry.file, and FileReader.readAsDataURL. + */ + function readFile() { + function onFileReadAsDataURL(evt) { + var img = document.getElementById('camera_image'); + img.style.visibility = "visible"; + img.style.display = "block"; + img.src = evt.target.result; + log("FileReader.readAsDataURL success"); + } + + function onFileReceived(file) { + log('Got file: ' + JSON.stringify(file)); + fileObj = file; + + var reader = new FileReader(); + reader.onload = function () { + log('FileReader.readAsDataURL() - length = ' + reader.result.length); + }; + reader.onerror = logCallback('FileReader.readAsDataURL', false); + reader.onloadend = onFileReadAsDataURL; + reader.readAsDataURL(file); + } + + // Test out onFileReceived when the file object was set via a native elements. + if (fileObj) { + onFileReceived(fileObj); + } else { + fileEntry.file(onFileReceived, logCallback('FileEntry.file', false)); + } + } + + function getFileInfo() { + // Test FileEntry API here. + fileEntry.getMetadata(logCallback('FileEntry.getMetadata', true), logCallback('FileEntry.getMetadata', false)); + fileEntry.setMetadata(logCallback('FileEntry.setMetadata', true), logCallback('FileEntry.setMetadata', false), { "com.apple.MobileBackup": 1 }); + fileEntry.getParent(logCallback('FileEntry.getParent', true), logCallback('FileEntry.getParent', false)); + fileEntry.getParent(logCallback('FileEntry.getParent', true), logCallback('FileEntry.getParent', false)); + } + + /** + * Copy image from library using a NATIVE_URI destination type + * This calls FileEntry.copyTo and FileEntry.moveTo. + */ + function copyImage() { + var onFileSystemReceived = function (fileSystem) { + var destDirEntry = fileSystem.root; + var origName = fileEntry.name; + + // Test FileEntry API here. + fileEntry.copyTo(destDirEntry, 'copied_file.png', logCallback('FileEntry.copyTo', true), logCallback('FileEntry.copyTo', false)); + fileEntry.moveTo(destDirEntry, 'moved_file.png', logCallback('FileEntry.moveTo', true), logCallback('FileEntry.moveTo', false)); + + //cleanup + //rename moved file back to original name so other tests can reference image + resolveLocalFileSystemURL(destDirEntry.nativeURL+'moved_file.png', function(fileEntry) { + fileEntry.moveTo(destDirEntry, origName, logCallback('FileEntry.moveTo', true), logCallback('FileEntry.moveTo', false)); + console.log('Cleanup: successfully renamed file back to original name'); + }, function () { + console.log('Cleanup: failed to rename file back to original name'); + }); + + //remove copied file + resolveLocalFileSystemURL(destDirEntry.nativeURL+'copied_file.png', function(fileEntry) { + fileEntry.remove(logCallback('FileEntry.remove', true), logCallback('FileEntry.remove', false)); + console.log('Cleanup: successfully removed copied file'); + }, function () { + console.log('Cleanup: failed to remove copied file'); + }); + }; + + window.requestFileSystem(LocalFileSystem.TEMPORARY, 0, onFileSystemReceived, null); + } + + /** + * Write image to library using a NATIVE_URI destination type + * This calls FileEntry.createWriter, FileWriter.write, and FileWriter.truncate. + */ + function writeImage() { + var onFileWriterReceived = function (fileWriter) { + fileWriter.onwrite = logCallback('FileWriter.write', true); + fileWriter.onerror = logCallback('FileWriter.write', false); + fileWriter.write("some text!"); + }; + + var onFileTruncateWriterReceived = function (fileWriter) { + fileWriter.onwrite = logCallback('FileWriter.truncate', true); + fileWriter.onerror = logCallback('FileWriter.truncate', false); + fileWriter.truncate(10); + }; + + fileEntry.createWriter(onFileWriterReceived, logCallback('FileEntry.createWriter', false)); + fileEntry.createWriter(onFileTruncateWriterReceived, null); + } + + function displayImageUsingCanvas() { + var canvas = document.getElementById('canvas'); + var img = document.getElementById('camera_image'); + var w = img.width; + var h = img.height; + h = 100 / w * h; + w = 100; + canvas.width = w; + canvas.height = h; + var context = canvas.getContext('2d'); + context.drawImage(img, 0, 0, w, h); + } + + /** + * Remove image from library using a NATIVE_URI destination type + * This calls FileEntry.remove. + */ + function removeImage() { + fileEntry.remove(logCallback('FileEntry.remove', true), logCallback('FileEntry.remove', false)); + } + + function testInputTag(inputEl) { + clearStatus(); + // iOS 6 likes to dead-lock in the onchange context if you + // do any alerts or try to remote-debug. + window.setTimeout(function () { + testNativeFile2(inputEl); + }, 0); + } + + function testNativeFile2(inputEl) { + if (!inputEl.value) { + alert('No file selected.'); + return; + } + fileObj = inputEl.files[0]; + if (!fileObj) { + alert('Got value but no file.'); + return; + } + var URLApi = window.URL || window.webkitURL; + if (URLApi) { + var blobURL = URLApi.createObjectURL(fileObj); + if (blobURL) { + setPicture(blobURL, function () { + URLApi.revokeObjectURL(blobURL); + }); + } else { + log('URL.createObjectURL returned null'); + } + } else { + log('URL.createObjectURL() not supported.'); + } + } + + function extractOptions() { + var els = document.querySelectorAll('#image-options select'); + var ret = {}; + /*jshint -W084 */ + for (var i = 0, el; el = els[i]; ++i) { + var value = el.value; + if (value === '') continue; + value = +value; + + if (el.isBool) { + ret[el.getAttribute("name")] = !!value; + } else { + ret[el.getAttribute("name")] = value; + } + } + /*jshint +W084 */ + return ret; + } + + function createOptionsEl(name, values, selectionDefault) { + var openDiv = '
' + name + ': '; + var select = '
'; + + return openDiv + select + defaultOption + options + closeDiv; + } + + /******************************************************************************/ + + var info_div = '

Camera

' + + '
' + + 'Status:
' + + 'img: ' + + 'canvas: ' + + '
', + options_div = '

Cordova Camera API Options

' + + '
' + + createOptionsEl('sourceType', Camera.PictureSourceType, camPictureSourceTypeDefault) + + createOptionsEl('destinationType', Camera.DestinationType, camDestinationTypeDefault) + + createOptionsEl('encodingType', Camera.EncodingType, camEncodingTypeDefault) + + createOptionsEl('mediaType', Camera.MediaType, camMediaTypeDefault) + + createOptionsEl('quality', { '0': 0, '50': 50, '80': 80, '100': 100 }, camQualityDefault) + + createOptionsEl('targetWidth', { '50': 50, '200': 200, '800': 800, '2048': 2048 }) + + createOptionsEl('targetHeight', { '50': 50, '200': 200, '800': 800, '2048': 2048 }) + + createOptionsEl('allowEdit', true, camAllowEditDefault) + + createOptionsEl('correctOrientation', true, camCorrectOrientationDefault) + + createOptionsEl('saveToPhotoAlbum', true, camSaveToPhotoAlbumDefault) + + createOptionsEl('cameraDirection', Camera.Direction) + + '
', + getpicture_div = '
', + test_procedure = '

Recommended Test Procedure

' + + 'Options not specified should be the default value' + + '
Status box should update with image and info whenever an image is taken or selected from library' + + '

' + + '
  1. All default options. Should be able to edit once picture is taken and will be saved to library.
  2. ' + + '

  3. sourceType=PHOTOLIBRARY
    Should be able to see picture that was just taken in previous test and edit when selected
  4. ' + + '

  5. sourceType=Camera
    allowEdit=false
    saveToPhotoAlbum=false
    Should not be able to edit when taken and will not save to library
  6. ' + + '

  7. encodingType=PNG
    allowEdit=true
    saveToPhotoAlbum=true
    cameraDirection=FRONT
    Should bring up front camera. Verify in status box info URL that image is encoded as PNG.
  8. ' + + '

  9. sourceType=SAVEDPHOTOALBUM
    mediaType=VIDEO
    Should only be able to select a video
  10. ' + + '

  11. sourceType=SAVEDPHOTOALBUM
    mediaType=PICTURE
    allowEdit=false
    Should only be able to select a picture and not edit
  12. ' + + '

  13. sourceType=PHOTOLIBRARY
    mediaType=ALLMEDIA
    allowEdit=true
    Should be able to select pics and videos and edit picture if selected
  14. ' + + '

  15. sourceType=CAMERA
    targetWidth & targetHeight=50
    allowEdit=false
    Do Get File Metadata test below and take note of size
    Repeat test but with width and height=800. Size should be significantly larger.
  16. ' + + '

  17. quality=0
    targetWidth & targetHeight=default
    allowEdit=false
    Do Get File Metadata test below and take note of size
    Repeat test but with quality=80. Size should be significantly larger.
  18. ' + + '
', + inputs_div = '

Native File Inputs

' + + 'For the following tests, status box should update with file selected' + + '

input type=file
' + + '
capture=camera
' + + '
capture=camcorder
' + + '
capture=microphone
', + actions_div = '

Actions

' + + 'For the following tests, ensure that an image is set in status box' + + '

' + + 'Expected result: Get metadata about file selected.
Status box will show, along with the metadata, "Call to FileEntry.getMetadata success, Call to FileEntry.setMetadata success, Call to FileEntry.getParent success"' + + '

' + + 'Expected result: Read contents of file.
Status box will show "Got file: {some metadata}, FileReader.readAsDataURL() - length = someNumber"' + + '

' + + 'Expected result: Copy image to new location and move file to different location.
Status box will show "Call to FileEntry.copyTo success:{some metadata}, Call to FileEntry.moveTo success:{some metadata}"' + + '

' + + 'Expected result: Write image to library.
Status box will show "Call to FileWriter.write success:{some metadata}, Call to FileWriter.truncate success:{some metadata}"' + + '

' + + 'Expected result: Upload image to server.
Status box may print out progress. Once finished will show "upload complete"' + + '

' + + 'Expected result: Display image using canvas.
Image will be displayed in status box under "canvas:"' + + '

' + + 'Expected result: Remove image from library.
Status box will show "FileEntry.remove success:["OK"]'; + + // We need to wrap this code due to Windows security restrictions + // see http://msdn.microsoft.com/en-us/library/windows/apps/hh465380.aspx#differences for details + if (window.MSApp && window.MSApp.execUnsafeLocalFunction) { + MSApp.execUnsafeLocalFunction(function() { + contentEl.innerHTML = info_div + options_div + getpicture_div + test_procedure + inputs_div + actions_div; + }); + } else { + contentEl.innerHTML = info_div + options_div + getpicture_div + test_procedure + inputs_div + actions_div; + } + + var elements = document.getElementsByClassName("testInputTag"); + var listener = function (e) { + testInputTag(e.target); + }; + for (var i = 0; i < elements.length; ++i) { + var item = elements[i]; + item.addEventListener("change", listener, false); + } + + createActionButton('Get picture', function () { + getPicture(); + }, 'getpicture'); + + createActionButton('Clear Status', function () { + clearStatus(); + }, 'getpicture'); + + createActionButton('Get File Metadata', function () { + getFileInfo(); + }, 'metadata'); + + createActionButton('Read with FileReader', function () { + readFile(); + }, 'reader'); + + createActionButton('Copy Image', function () { + copyImage(); + }, 'copy'); + + createActionButton('Write Image', function () { + writeImage(); + }, 'write'); + + createActionButton('Upload Image', function () { + uploadImage(); + }, 'upload'); + + createActionButton('Draw Using Canvas', function () { + displayImageUsingCanvas(); + }, 'draw_canvas'); + + createActionButton('Remove Image', function () { + removeImage(); + }, 'remove'); +}; diff --git a/plugins/cordova-plugin-camera/types/index.d.ts b/plugins/cordova-plugin-camera/types/index.d.ts new file mode 100644 index 0000000..fa50e9c --- /dev/null +++ b/plugins/cordova-plugin-camera/types/index.d.ts @@ -0,0 +1,174 @@ +// Type definitions for Apache Cordova Camera plugin +// Project: https://github.com/apache/cordova-plugin-camera +// Definitions by: Microsoft Open Technologies Inc +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// +// Copyright (c) Microsoft Open Technologies Inc +// Licensed under the MIT license. + +interface Navigator { + /** + * This plugin provides an API for taking pictures and for choosing images from the system's image library. + */ + camera: Camera; +} + +/** + * This plugin provides an API for taking pictures and for choosing images from the system's image library. + */ +interface Camera { + /** + * Removes intermediate photos taken by the camera from temporary storage. + * @param onSuccess Success callback, that called when cleanup succeeds. + * @param onError Error callback, that get an error message. + */ + cleanup( + onSuccess: () => void, + onError: (message: string) => void): void; + /** + * Takes a photo using the camera, or retrieves a photo from the device's image gallery. + * @param cameraSuccess Success callback, that get the image + * as a base64-encoded String, or as the URI for the image file. + * @param cameraError Error callback, that get an error message. + * @param cameraOptions Optional parameters to customize the camera settings. + */ + getPicture( + cameraSuccess: (data: string) => void, + cameraError: (message: string) => void, + cameraOptions?: CameraOptions): void; + // Next will work only on iOS + //getPicture( + // cameraSuccess: (data: string) => void, + // cameraError: (message: string) => void, + // cameraOptions?: CameraOptions): CameraPopoverHandle; +} + +interface CameraOptions { + /** Picture quality in range 0-100. Default is 50 */ + quality?: number; + /** + * Choose the format of the return value. + * Defined in navigator.camera.DestinationType. Default is FILE_URI. + * DATA_URL : 0, Return image as base64-encoded string + * FILE_URI : 1, Return image file URI + * NATIVE_URI : 2 Return image native URI + * (e.g., assets-library:// on iOS or content:// on Android) + */ + destinationType?: number; + /** + * Set the source of the picture. + * Defined in navigator.camera.PictureSourceType. Default is CAMERA. + * PHOTOLIBRARY : 0, + * CAMERA : 1, + * SAVEDPHOTOALBUM : 2 + */ + sourceType?: number; + /** Allow simple editing of image before selection. */ + allowEdit?: boolean; + /** + * Choose the returned image file's encoding. + * Defined in navigator.camera.EncodingType. Default is JPEG + * JPEG : 0 Return JPEG encoded image + * PNG : 1 Return PNG encoded image + */ + encodingType?: number; + /** + * Width in pixels to scale image. Must be used with targetHeight. + * Aspect ratio remains constant. + */ + targetWidth?: number; + /** + * Height in pixels to scale image. Must be used with targetWidth. + * Aspect ratio remains constant. + */ + targetHeight?: number; + /** + * Set the type of media to select from. Only works when PictureSourceType + * is PHOTOLIBRARY or SAVEDPHOTOALBUM. Defined in nagivator.camera.MediaType + * PICTURE: 0 allow selection of still pictures only. DEFAULT. + * Will return format specified via DestinationType + * VIDEO: 1 allow selection of video only, WILL ALWAYS RETURN FILE_URI + * ALLMEDIA : 2 allow selection from all media types + */ + mediaType?: number; + /** Rotate the image to correct for the orientation of the device during capture. */ + correctOrientation?: boolean; + /** Save the image to the photo album on the device after capture. */ + saveToPhotoAlbum?: boolean; + /** + * Choose the camera to use (front- or back-facing). + * Defined in navigator.camera.Direction. Default is BACK. + * FRONT: 0 + * BACK: 1 + */ + cameraDirection?: number; + /** iOS-only options that specify popover location in iPad. Defined in CameraPopoverOptions. */ + popoverOptions?: CameraPopoverOptions; +} + +/** + * A handle to the popover dialog created by navigator.camera.getPicture. Used on iOS only. + */ +interface CameraPopoverHandle { + /** + * Set the position of the popover. + * @param popoverOptions the CameraPopoverOptions that specify the new position. + */ + setPosition(popoverOptions: CameraPopoverOptions): void; +} + +/** + * iOS-only parameters that specify the anchor element location and arrow direction + * of the popover when selecting images from an iPad's library or album. + */ +interface CameraPopoverOptions { + x: number; + y: number; + width: number; + height: number; + /** + * Direction the arrow on the popover should point. Defined in Camera.PopoverArrowDirection + * Matches iOS UIPopoverArrowDirection constants. + * ARROW_UP : 1, + * ARROW_DOWN : 2, + * ARROW_LEFT : 4, + * ARROW_RIGHT : 8, + * ARROW_ANY : 15 + */ + arrowDir : number; +} + +declare var Camera: { + // Camera constants, defined in Camera plugin + DestinationType: { + DATA_URL: number; + FILE_URI: number; + NATIVE_URI: number + } + Direction: { + BACK: number; + FRONT: number; + } + EncodingType: { + JPEG: number; + PNG: number; + } + MediaType: { + PICTURE: number; + VIDEO: number; + ALLMEDIA: number; + } + PictureSourceType: { + PHOTOLIBRARY: number; + CAMERA: number; + SAVEDPHOTOALBUM: number; + } + // Used only on iOS + PopoverArrowDirection: { + ARROW_UP: number; + ARROW_DOWN: number; + ARROW_LEFT: number; + ARROW_RIGHT: number; + ARROW_ANY: number; + } +}; diff --git a/plugins/cordova-plugin-camera/www/Camera.js b/plugins/cordova-plugin-camera/www/Camera.js new file mode 100644 index 0000000..d006787 --- /dev/null +++ b/plugins/cordova-plugin-camera/www/Camera.js @@ -0,0 +1,185 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ + +var argscheck = require('cordova/argscheck'), + exec = require('cordova/exec'), + Camera = require('./Camera'); + // XXX: commented out + //CameraPopoverHandle = require('./CameraPopoverHandle'); + +/** + * @namespace navigator + */ + +/** + * @exports camera + */ +var cameraExport = {}; + +// Tack on the Camera Constants to the base camera plugin. +for (var key in Camera) { + cameraExport[key] = Camera[key]; +} + +/** + * Callback function that provides an error message. + * @callback module:camera.onError + * @param {string} message - The message is provided by the device's native code. + */ + +/** + * Callback function that provides the image data. + * @callback module:camera.onSuccess + * @param {string} imageData - Base64 encoding of the image data, _or_ the image file URI, depending on [`cameraOptions`]{@link module:camera.CameraOptions} in effect. + * @example + * // Show image + * // + * function cameraCallback(imageData) { + * var image = document.getElementById('myImage'); + * image.src = "data:image/jpeg;base64," + imageData; + * } + */ + +/** + * Optional parameters to customize the camera settings. + * * [Quirks](#CameraOptions-quirks) + * @typedef module:camera.CameraOptions + * @type {Object} + * @property {number} [quality=50] - Quality of the saved image, expressed as a range of 0-100, where 100 is typically full resolution with no loss from file compression. (Note that information about the camera's resolution is unavailable.) + * @property {module:Camera.DestinationType} [destinationType=FILE_URI] - Choose the format of the return value. + * @property {module:Camera.PictureSourceType} [sourceType=CAMERA] - Set the source of the picture. + * @property {Boolean} [allowEdit=true] - Allow simple editing of image before selection. + * @property {module:Camera.EncodingType} [encodingType=JPEG] - Choose the returned image file's encoding. + * @property {number} [targetWidth] - Width in pixels to scale image. Must be used with `targetHeight`. Aspect ratio remains constant. + * @property {number} [targetHeight] - Height in pixels to scale image. Must be used with `targetWidth`. Aspect ratio remains constant. + * @property {module:Camera.MediaType} [mediaType=PICTURE] - Set the type of media to select from. Only works when `PictureSourceType` is `PHOTOLIBRARY` or `SAVEDPHOTOALBUM`. + * @property {Boolean} [correctOrientation] - Rotate the image to correct for the orientation of the device during capture. + * @property {Boolean} [saveToPhotoAlbum] - Save the image to the photo album on the device after capture. + * @property {module:CameraPopoverOptions} [popoverOptions] - iOS-only options that specify popover location in iPad. + * @property {module:Camera.Direction} [cameraDirection=BACK] - Choose the camera to use (front- or back-facing). + */ + +/** + * @description Takes a photo using the camera, or retrieves a photo from the device's + * image gallery. The image is passed to the success callback as a + * Base64-encoded `String`, or as the URI for the image file. + * + * The `camera.getPicture` function opens the device's default camera + * application that allows users to snap pictures by default - this behavior occurs, + * when `Camera.sourceType` equals [`Camera.PictureSourceType.CAMERA`]{@link module:Camera.PictureSourceType}. + * Once the user snaps the photo, the camera application closes and the application is restored. + * + * If `Camera.sourceType` is `Camera.PictureSourceType.PHOTOLIBRARY` or + * `Camera.PictureSourceType.SAVEDPHOTOALBUM`, then a dialog displays + * that allows users to select an existing image. + * + * The return value is sent to the [`cameraSuccess`]{@link module:camera.onSuccess} callback function, in + * one of the following formats, depending on the specified + * `cameraOptions`: + * + * - A `String` containing the Base64-encoded photo image. + * - A `String` representing the image file location on local storage (default). + * + * You can do whatever you want with the encoded image or URI, for + * example: + * + * - Render the image in an `` tag, as in the example below + * - Save the data locally (`LocalStorage`, [Lawnchair](http://brianleroux.github.com/lawnchair/), etc.) + * - Post the data to a remote server + * + * __NOTE__: Photo resolution on newer devices is quite good. Photos + * selected from the device's gallery are not downscaled to a lower + * quality, even if a `quality` parameter is specified. To avoid common + * memory problems, set `Camera.destinationType` to `FILE_URI` rather + * than `DATA_URL`. + * + * __Supported Platforms__ + * + * - Android + * - BlackBerry + * - Browser + * - Firefox + * - FireOS + * - iOS + * - Windows + * - WP8 + * - Ubuntu + * + * More examples [here](#camera-getPicture-examples). Quirks [here](#camera-getPicture-quirks). + * + * @example + * navigator.camera.getPicture(cameraSuccess, cameraError, cameraOptions); + * @param {module:camera.onSuccess} successCallback + * @param {module:camera.onError} errorCallback + * @param {module:camera.CameraOptions} options CameraOptions + */ +cameraExport.getPicture = function(successCallback, errorCallback, options) { + argscheck.checkArgs('fFO', 'Camera.getPicture', arguments); + options = options || {}; + var getValue = argscheck.getValue; + + var quality = getValue(options.quality, 50); + var destinationType = getValue(options.destinationType, Camera.DestinationType.FILE_URI); + var sourceType = getValue(options.sourceType, Camera.PictureSourceType.CAMERA); + var targetWidth = getValue(options.targetWidth, -1); + var targetHeight = getValue(options.targetHeight, -1); + var encodingType = getValue(options.encodingType, Camera.EncodingType.JPEG); + var mediaType = getValue(options.mediaType, Camera.MediaType.PICTURE); + var allowEdit = !!options.allowEdit; + var correctOrientation = !!options.correctOrientation; + var saveToPhotoAlbum = !!options.saveToPhotoAlbum; + var popoverOptions = getValue(options.popoverOptions, null); + var cameraDirection = getValue(options.cameraDirection, Camera.Direction.BACK); + + var args = [quality, destinationType, sourceType, targetWidth, targetHeight, encodingType, + mediaType, allowEdit, correctOrientation, saveToPhotoAlbum, popoverOptions, cameraDirection]; + + exec(successCallback, errorCallback, "Camera", "takePicture", args); + // XXX: commented out + //return new CameraPopoverHandle(); +}; + +/** + * Removes intermediate image files that are kept in temporary storage + * after calling [`camera.getPicture`]{@link module:camera.getPicture}. Applies only when the value of + * `Camera.sourceType` equals `Camera.PictureSourceType.CAMERA` and the + * `Camera.destinationType` equals `Camera.DestinationType.FILE_URI`. + * + * __Supported Platforms__ + * + * - iOS + * + * @example + * navigator.camera.cleanup(onSuccess, onFail); + * + * function onSuccess() { + * console.log("Camera cleanup success.") + * } + * + * function onFail(message) { + * alert('Failed because: ' + message); + * } + */ +cameraExport.cleanup = function(successCallback, errorCallback) { + exec(successCallback, errorCallback, "Camera", "cleanup", []); +}; + +module.exports = cameraExport; diff --git a/plugins/cordova-plugin-camera/www/CameraConstants.js b/plugins/cordova-plugin-camera/www/CameraConstants.js new file mode 100644 index 0000000..9974c15 --- /dev/null +++ b/plugins/cordova-plugin-camera/www/CameraConstants.js @@ -0,0 +1,101 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ + +/** + * @module Camera + */ +module.exports = { + /** + * @description + * Defines the output format of `Camera.getPicture` call. + * _Note:_ On iOS passing `DestinationType.NATIVE_URI` along with + * `PictureSourceType.PHOTOLIBRARY` or `PictureSourceType.SAVEDPHOTOALBUM` will + * disable any image modifications (resize, quality change, cropping, etc.) due + * to implementation specific. + * + * @enum {number} + */ + DestinationType:{ + /** Return base64 encoded string. DATA_URL can be very memory intensive and cause app crashes or out of memory errors. Use FILE_URI or NATIVE_URI if possible */ + DATA_URL: 0, + /** Return file uri (content://media/external/images/media/2 for Android) */ + FILE_URI: 1, + /** Return native uri (eg. asset-library://... for iOS) */ + NATIVE_URI: 2 + }, + /** + * @enum {number} + */ + EncodingType:{ + /** Return JPEG encoded image */ + JPEG: 0, + /** Return PNG encoded image */ + PNG: 1 + }, + /** + * @enum {number} + */ + MediaType:{ + /** Allow selection of still pictures only. DEFAULT. Will return format specified via DestinationType */ + PICTURE: 0, + /** Allow selection of video only, ONLY RETURNS URL */ + VIDEO: 1, + /** Allow selection from all media types */ + ALLMEDIA : 2 + }, + /** + * @description + * Defines the output format of `Camera.getPicture` call. + * _Note:_ On iOS passing `PictureSourceType.PHOTOLIBRARY` or `PictureSourceType.SAVEDPHOTOALBUM` + * along with `DestinationType.NATIVE_URI` will disable any image modifications (resize, quality + * change, cropping, etc.) due to implementation specific. + * + * @enum {number} + */ + PictureSourceType:{ + /** Choose image from the device's photo library (same as SAVEDPHOTOALBUM for Android) */ + PHOTOLIBRARY : 0, + /** Take picture from camera */ + CAMERA : 1, + /** Choose image only from the device's Camera Roll album (same as PHOTOLIBRARY for Android) */ + SAVEDPHOTOALBUM : 2 + }, + /** + * Matches iOS UIPopoverArrowDirection constants to specify arrow location on popover. + * @enum {number} + */ + PopoverArrowDirection:{ + ARROW_UP : 1, + ARROW_DOWN : 2, + ARROW_LEFT : 4, + ARROW_RIGHT : 8, + ARROW_ANY : 15 + }, + /** + * @enum {number} + */ + Direction:{ + /** Use the back-facing camera */ + BACK: 0, + /** Use the front-facing camera */ + FRONT: 1 + } +}; diff --git a/plugins/cordova-plugin-camera/www/CameraPopoverHandle.js b/plugins/cordova-plugin-camera/www/CameraPopoverHandle.js new file mode 100644 index 0000000..ba1063a --- /dev/null +++ b/plugins/cordova-plugin-camera/www/CameraPopoverHandle.js @@ -0,0 +1,32 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ + +/** + * @ignore in favour of iOS' one + * A handle to an image picker popover. + */ +var CameraPopoverHandle = function() { + this.setPosition = function(popoverOptions) { + console.log('CameraPopoverHandle.setPosition is only supported on iOS.'); + }; +}; + +module.exports = CameraPopoverHandle; diff --git a/plugins/cordova-plugin-camera/www/CameraPopoverOptions.js b/plugins/cordova-plugin-camera/www/CameraPopoverOptions.js new file mode 100644 index 0000000..27998b6 --- /dev/null +++ b/plugins/cordova-plugin-camera/www/CameraPopoverOptions.js @@ -0,0 +1,52 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ + +var Camera = require('./Camera'); + +/** + * @namespace navigator + */ + +/** + * iOS-only parameters that specify the anchor element location and arrow + * direction of the popover when selecting images from an iPad's library + * or album. + * Note that the size of the popover may change to adjust to the + * direction of the arrow and orientation of the screen. Make sure to + * account for orientation changes when specifying the anchor element + * location. + * @module CameraPopoverOptions + * @param {Number} [x=0] - x pixel coordinate of screen element onto which to anchor the popover. + * @param {Number} [y=32] - y pixel coordinate of screen element onto which to anchor the popover. + * @param {Number} [width=320] - width, in pixels, of the screen element onto which to anchor the popover. + * @param {Number} [height=480] - height, in pixels, of the screen element onto which to anchor the popover. + * @param {module:Camera.PopoverArrowDirection} [arrowDir=ARROW_ANY] - Direction the arrow on the popover should point. + */ +var CameraPopoverOptions = function (x, y, width, height, arrowDir) { + // information of rectangle that popover should be anchored to + this.x = x || 0; + this.y = y || 32; + this.width = width || 320; + this.height = height || 480; + this.arrowDir = arrowDir || Camera.PopoverArrowDirection.ARROW_ANY; +}; + +module.exports = CameraPopoverOptions; diff --git a/plugins/cordova-plugin-camera/www/blackberry10/assets/camera.html b/plugins/cordova-plugin-camera/www/blackberry10/assets/camera.html new file mode 100644 index 0000000..2ebd9d1 --- /dev/null +++ b/plugins/cordova-plugin-camera/www/blackberry10/assets/camera.html @@ -0,0 +1,82 @@ + + + + + + + + + + +
+ +
+
+ +
+
+
+
+
+
+ + diff --git a/plugins/cordova-plugin-camera/www/blackberry10/assets/camera.js b/plugins/cordova-plugin-camera/www/blackberry10/assets/camera.js new file mode 100644 index 0000000..8a245e5 --- /dev/null +++ b/plugins/cordova-plugin-camera/www/blackberry10/assets/camera.js @@ -0,0 +1,46 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +document.addEventListener('DOMContentLoaded', function () { + document.getElementById('back').onclick = function () { + window.qnx.callExtensionMethod('cordova-plugin-camera', 'cancel'); + }; + window.navigator.webkitGetUserMedia( + { video: true }, + function (stream) { + var video = document.getElementById('v'), + canvas = document.getElementById('c'), + camera = document.getElementById('camera'); + video.autoplay = true; + video.width = window.innerWidth; + video.height = window.innerHeight - 100; + video.src = window.webkitURL.createObjectURL(stream); + camera.onclick = function () { + canvas.width = video.videoWidth; + canvas.height = video.videoHeight; + canvas.getContext('2d').drawImage(video, 0, 0, video.videoWidth, video.videoHeight); + window.qnx.callExtensionMethod('cordova-plugin-camera', canvas.toDataURL('img/png')); + }; + }, + function () { + window.qnx.callExtensionMethod('cordova-plugin-camera', 'error', 'getUserMedia failed'); + } + ); +}); diff --git a/plugins/cordova-plugin-camera/www/ios/CameraPopoverHandle.js b/plugins/cordova-plugin-camera/www/ios/CameraPopoverHandle.js new file mode 100644 index 0000000..8b92137 --- /dev/null +++ b/plugins/cordova-plugin-camera/www/ios/CameraPopoverHandle.js @@ -0,0 +1,66 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ + +var exec = require('cordova/exec'); + +/** + * @namespace navigator + */ + +/** + * A handle to an image picker popover. + * + * __Supported Platforms__ + * + * - iOS + * + * @example + * navigator.camera.getPicture(onSuccess, onFail, + * { + * destinationType: Camera.DestinationType.FILE_URI, + * sourceType: Camera.PictureSourceType.PHOTOLIBRARY, + * popoverOptions: new CameraPopoverOptions(300, 300, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY) + * }); + * + * // Reposition the popover if the orientation changes. + * window.onorientationchange = function() { + * var cameraPopoverHandle = new CameraPopoverHandle(); + * var cameraPopoverOptions = new CameraPopoverOptions(0, 0, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY); + * cameraPopoverHandle.setPosition(cameraPopoverOptions); + * } + * @module CameraPopoverHandle + */ +var CameraPopoverHandle = function() { + /** + * Can be used to reposition the image selection dialog, + * for example, when the device orientation changes. + * @memberof CameraPopoverHandle + * @instance + * @method setPosition + * @param {module:CameraPopoverOptions} popoverOptions + */ + this.setPosition = function(popoverOptions) { + var args = [ popoverOptions ]; + exec(null, null, "Camera", "repositionPopover", args); + }; +}; + +module.exports = CameraPopoverHandle; diff --git a/plugins/cordova-plugin-compat/README.md b/plugins/cordova-plugin-compat/README.md new file mode 100644 index 0000000..095c384 --- /dev/null +++ b/plugins/cordova-plugin-compat/README.md @@ -0,0 +1,31 @@ + + +cordova-plugin-compat +------------------------ + +This repo is for remaining backwards compatible with previous versions of Cordova. + +## USAGE + +Your plugin can depend on this plugin and use it to handle the new run time permissions Android 6.0.0 (cordova-android 5.0.0) introduced. + +View [this commit](https://github.com/apache/cordova-plugin-camera/commit/a9c18710f23e86f5b7f8918dfab7c87a85064870) to see how to depend on `cordova-plugin-compat`. View [this file](https://github.com/apache/cordova-plugin-camera/blob/master/src/android/CameraLauncher.java) to see how `PermissionHelper` is being used to request and store permissions. Read more about Android permissions at http://cordova.apache.org/docs/en/latest/guide/platforms/android/plugin.html#android-permissions. diff --git a/plugins/cordova-plugin-compat/RELEASENOTES.md b/plugins/cordova-plugin-compat/RELEASENOTES.md new file mode 100644 index 0000000..b7aa129 --- /dev/null +++ b/plugins/cordova-plugin-compat/RELEASENOTES.md @@ -0,0 +1,29 @@ + +# Release Notes + +### 1.1.0 (Nov 02, 2016) +* [CB-11625](https://issues.apache.org/jira/browse/CB-11625) Adding the `BuildConfig` fetching code as a backup to using a new preference +* Add github pull request template + +### 1.0.0 (Apr 15, 2016) +* Initial release +* Moved `PermissionHelper.java` into `src` diff --git a/plugins/cordova-plugin-compat/package.json b/plugins/cordova-plugin-compat/package.json new file mode 100644 index 0000000..f31174d --- /dev/null +++ b/plugins/cordova-plugin-compat/package.json @@ -0,0 +1,32 @@ +{ + "name": "cordova-plugin-compat", + "description": "This repo is for remaining backwards compatible with previous versions of Cordova.", + "version": "1.1.0", + "homepage": "http://github.com/apache/cordova-plugin-compat#readme", + "repository": { + "type": "git", + "url": "git://github.com/apache/cordova-plugin-compat.git" + }, + "bugs": { + "url": "https://github.com/apache/cordova-plugin-compat/issues" + }, + "cordova": { + "id": "cordova-plugin-compat", + "platforms": [ + "android" + ] + }, + "keywords": [ + "ecosystem:cordova", + "ecosystem:phonegap", + "cordova-android" + ], + "engines": [ + { + "name": "cordova", + "version": ">=5.0.0" + } + ], + "author": "Apache Software Foundation", + "license": "Apache-2.0" +} diff --git a/plugins/cordova-plugin-compat/plugin.xml b/plugins/cordova-plugin-compat/plugin.xml new file mode 100644 index 0000000..40b45cc --- /dev/null +++ b/plugins/cordova-plugin-compat/plugin.xml @@ -0,0 +1,37 @@ + + + + + + Compat + Cordova Compatibility Plugin + Apache 2.0 + cordova,compat + https://git-wip-us.apache.org/repos/asf/cordova-plugin-compat.git + + + + + + + + diff --git a/plugins/cordova-plugin-compat/src/android/BuildHelper.java b/plugins/cordova-plugin-compat/src/android/BuildHelper.java new file mode 100644 index 0000000..d9b18aa --- /dev/null +++ b/plugins/cordova-plugin-compat/src/android/BuildHelper.java @@ -0,0 +1,70 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. +*/ + +package org.apache.cordova; + +/* + * This is a utility class that allows us to get the BuildConfig variable, which is required + * for the use of different providers. This is not guaranteed to work, and it's better for this + * to be set in the build step in config.xml + * + */ + +import android.app.Activity; +import android.content.Context; + +import java.lang.reflect.Field; + + +public class BuildHelper { + + + private static String TAG="BuildHelper"; + + /* + * This needs to be implemented if you wish to use the Camera Plugin or other plugins + * that read the Build Configuration. + * + * Thanks to Phil@Medtronic and Graham Borland for finding the answer and posting it to + * StackOverflow. This is annoying as hell! However, this method does not work with + * ProGuard, and you should use the config.xml to define the application_id + * + */ + + public static Object getBuildConfigValue(Context ctx, String key) + { + try + { + Class clazz = Class.forName(ctx.getPackageName() + ".BuildConfig"); + Field field = clazz.getField(key); + return field.get(null); + } catch (ClassNotFoundException e) { + LOG.d(TAG, "Unable to get the BuildConfig, is this built with ANT?"); + e.printStackTrace(); + } catch (NoSuchFieldException e) { + LOG.d(TAG, key + " is not a valid field. Check your build.gradle"); + } catch (IllegalAccessException e) { + LOG.d(TAG, "Illegal Access Exception: Let's print a stack trace."); + e.printStackTrace(); + } + + return null; + } + +} diff --git a/plugins/cordova-plugin-compat/src/android/PermissionHelper.java b/plugins/cordova-plugin-compat/src/android/PermissionHelper.java new file mode 100644 index 0000000..bbd7911 --- /dev/null +++ b/plugins/cordova-plugin-compat/src/android/PermissionHelper.java @@ -0,0 +1,138 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. +*/ +package org.apache.cordova; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Arrays; + +import org.apache.cordova.CordovaInterface; +import org.apache.cordova.CordovaPlugin; +import org.apache.cordova.LOG; + +import android.content.pm.PackageManager; + +/** + * This class provides reflective methods for permission requesting and checking so that plugins + * written for cordova-android 5.0.0+ can still compile with earlier cordova-android versions. + */ +public class PermissionHelper { + private static final String LOG_TAG = "CordovaPermissionHelper"; + + /** + * Requests a "dangerous" permission for the application at runtime. This is a helper method + * alternative to cordovaInterface.requestPermission() that does not require the project to be + * built with cordova-android 5.0.0+ + * + * @param plugin The plugin the permission is being requested for + * @param requestCode A requestCode to be passed to the plugin's onRequestPermissionResult() + * along with the result of the permission request + * @param permission The permission to be requested + */ + public static void requestPermission(CordovaPlugin plugin, int requestCode, String permission) { + PermissionHelper.requestPermissions(plugin, requestCode, new String[] {permission}); + } + + /** + * Requests "dangerous" permissions for the application at runtime. This is a helper method + * alternative to cordovaInterface.requestPermissions() that does not require the project to be + * built with cordova-android 5.0.0+ + * + * @param plugin The plugin the permissions are being requested for + * @param requestCode A requestCode to be passed to the plugin's onRequestPermissionResult() + * along with the result of the permissions request + * @param permissions The permissions to be requested + */ + public static void requestPermissions(CordovaPlugin plugin, int requestCode, String[] permissions) { + try { + Method requestPermission = CordovaInterface.class.getDeclaredMethod( + "requestPermissions", CordovaPlugin.class, int.class, String[].class); + + // If there is no exception, then this is cordova-android 5.0.0+ + requestPermission.invoke(plugin.cordova, plugin, requestCode, permissions); + } catch (NoSuchMethodException noSuchMethodException) { + // cordova-android version is less than 5.0.0, so permission is implicitly granted + LOG.d(LOG_TAG, "No need to request permissions " + Arrays.toString(permissions)); + + // Notify the plugin that all were granted by using more reflection + deliverPermissionResult(plugin, requestCode, permissions); + } catch (IllegalAccessException illegalAccessException) { + // Should never be caught; this is a public method + LOG.e(LOG_TAG, "IllegalAccessException when requesting permissions " + Arrays.toString(permissions), illegalAccessException); + } catch(InvocationTargetException invocationTargetException) { + // This method does not throw any exceptions, so this should never be caught + LOG.e(LOG_TAG, "invocationTargetException when requesting permissions " + Arrays.toString(permissions), invocationTargetException); + } + } + + /** + * Checks at runtime to see if the application has been granted a permission. This is a helper + * method alternative to cordovaInterface.hasPermission() that does not require the project to + * be built with cordova-android 5.0.0+ + * + * @param plugin The plugin the permission is being checked against + * @param permission The permission to be checked + * + * @return True if the permission has already been granted and false otherwise + */ + public static boolean hasPermission(CordovaPlugin plugin, String permission) { + try { + Method hasPermission = CordovaInterface.class.getDeclaredMethod("hasPermission", String.class); + + // If there is no exception, then this is cordova-android 5.0.0+ + return (Boolean) hasPermission.invoke(plugin.cordova, permission); + } catch (NoSuchMethodException noSuchMethodException) { + // cordova-android version is less than 5.0.0, so permission is implicitly granted + LOG.d(LOG_TAG, "No need to check for permission " + permission); + return true; + } catch (IllegalAccessException illegalAccessException) { + // Should never be caught; this is a public method + LOG.e(LOG_TAG, "IllegalAccessException when checking permission " + permission, illegalAccessException); + } catch(InvocationTargetException invocationTargetException) { + // This method does not throw any exceptions, so this should never be caught + LOG.e(LOG_TAG, "invocationTargetException when checking permission " + permission, invocationTargetException); + } + return false; + } + + private static void deliverPermissionResult(CordovaPlugin plugin, int requestCode, String[] permissions) { + // Generate the request results + int[] requestResults = new int[permissions.length]; + Arrays.fill(requestResults, PackageManager.PERMISSION_GRANTED); + + try { + Method onRequestPermissionResult = CordovaPlugin.class.getDeclaredMethod( + "onRequestPermissionResult", int.class, String[].class, int[].class); + + onRequestPermissionResult.invoke(plugin, requestCode, permissions, requestResults); + } catch (NoSuchMethodException noSuchMethodException) { + // Should never be caught since the plugin must be written for cordova-android 5.0.0+ if it + // made it to this point + LOG.e(LOG_TAG, "NoSuchMethodException when delivering permissions results", noSuchMethodException); + } catch (IllegalAccessException illegalAccessException) { + // Should never be caught; this is a public method + LOG.e(LOG_TAG, "IllegalAccessException when delivering permissions results", illegalAccessException); + } catch(InvocationTargetException invocationTargetException) { + // This method may throw a JSONException. We are just duplicating cordova-android's + // exception handling behavior here; all it does is log the exception in CordovaActivity, + // print the stacktrace, and ignore it + LOG.e(LOG_TAG, "InvocationTargetException when delivering permissions results", invocationTargetException); + } + } +} diff --git a/plugins/cordova-plugin-file/CONTRIBUTING.md b/plugins/cordova-plugin-file/CONTRIBUTING.md new file mode 100644 index 0000000..4c8e6a5 --- /dev/null +++ b/plugins/cordova-plugin-file/CONTRIBUTING.md @@ -0,0 +1,37 @@ + + +# Contributing to Apache Cordova + +Anyone can contribute to Cordova. And we need your contributions. + +There are multiple ways to contribute: report bugs, improve the docs, and +contribute code. + +For instructions on this, start with the +[contribution overview](http://cordova.apache.org/contribute/). + +The details are explained there, but the important items are: + - Sign and submit an Apache ICLA (Contributor License Agreement). + - Have a Jira issue open that corresponds to your contribution. + - Run the tests so your patch doesn't break existing functionality. + +We look forward to your contributions! diff --git a/plugins/cordova-plugin-file/LICENSE b/plugins/cordova-plugin-file/LICENSE new file mode 100644 index 0000000..7a4a3ea --- /dev/null +++ b/plugins/cordova-plugin-file/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/plugins/cordova-plugin-file/NOTICE b/plugins/cordova-plugin-file/NOTICE new file mode 100644 index 0000000..8ec56a5 --- /dev/null +++ b/plugins/cordova-plugin-file/NOTICE @@ -0,0 +1,5 @@ +Apache Cordova +Copyright 2012 The Apache Software Foundation + +This product includes software developed at +The Apache Software Foundation (http://www.apache.org/). diff --git a/plugins/cordova-plugin-file/README.md b/plugins/cordova-plugin-file/README.md new file mode 100644 index 0000000..ab35cd9 --- /dev/null +++ b/plugins/cordova-plugin-file/README.md @@ -0,0 +1,868 @@ +--- +title: File +description: Read/write files on the device. +--- + + +|Android 4.4|Android 5.1|Android 6.0|iOS 9.3|iOS 10.0|Windows 10 Store|Travis CI| +|:-:|:-:|:-:|:-:|:-:|:-:|:-:| +|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=android-4.4,PLUGIN=cordova-plugin-file)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=android-4.4,PLUGIN=cordova-plugin-file/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=android-5.1,PLUGIN=cordova-plugin-file)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=android-5.1,PLUGIN=cordova-plugin-file/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=android-6.0,PLUGIN=cordova-plugin-file)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=android-6.0,PLUGIN=cordova-plugin-file/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=ios-9.3,PLUGIN=cordova-plugin-file)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=ios-9.3,PLUGIN=cordova-plugin-file/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=ios-10.0,PLUGIN=cordova-plugin-file)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=ios-10.0,PLUGIN=cordova-plugin-file/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=windows-10-store,PLUGIN=cordova-plugin-file)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=windows-10-store,PLUGIN=cordova-plugin-file/)|[![Build Status](https://travis-ci.org/apache/cordova-plugin-file.svg?branch=master)](https://travis-ci.org/apache/cordova-plugin-file)| + +# cordova-plugin-file + +This plugin implements a File API allowing read/write access to files residing on the device. + +This plugin is based on several specs, including : +The HTML5 File API +[http://www.w3.org/TR/FileAPI/](http://www.w3.org/TR/FileAPI/) + +The Directories and System extensions +Latest: +[http://www.w3.org/TR/2012/WD-file-system-api-20120417/](http://www.w3.org/TR/2012/WD-file-system-api-20120417/) +Although most of the plugin code was written when an earlier spec was current: +[http://www.w3.org/TR/2011/WD-file-system-api-20110419/](http://www.w3.org/TR/2011/WD-file-system-api-20110419/) + +It also implements the FileWriter spec : +[http://dev.w3.org/2009/dap/file-system/file-writer.html](http://dev.w3.org/2009/dap/file-system/file-writer.html) + +>*Note* While the W3C FileSystem spec is deprecated for web browsers, the FileSystem APIs are supported in Cordova applications with this plugin for the platforms listed in the _Supported Platforms_ list, with the exception of the Browser platform. + +To get a few ideas how to use the plugin, check out the [sample](#sample) at the bottom of this page. For additional examples (browser focused), see the HTML5 Rocks' [FileSystem article.](http://www.html5rocks.com/en/tutorials/file/filesystem/) + +For an overview of other storage options, refer to Cordova's +[storage guide](http://cordova.apache.org/docs/en/latest/cordova/storage/storage.html). + +This plugin defines global `cordova.file` object. + +Although in the global scope, it is not available until after the `deviceready` event. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(cordova.file); + } + +Report issues on the [Apache Cordova issue tracker](https://issues.apache.org/jira/issues/?jql=project%20%3D%20CB%20AND%20status%20in%20%28Open%2C%20%22In%20Progress%22%2C%20Reopened%29%20AND%20resolution%20%3D%20Unresolved%20AND%20component%20%3D%20%22Plugin%20File%22%20ORDER%20BY%20priority%20DESC%2C%20summary%20ASC%2C%20updatedDate%20DESC) + +## Installation + + cordova plugin add cordova-plugin-file + +## Supported Platforms + +- Amazon Fire OS +- Android +- BlackBerry 10 +- Firefox OS +- iOS +- OS X +- Windows Phone 7 and 8* +- Windows 8* +- Windows* +- Browser + +\* _These platforms do not support `FileReader.readAsArrayBuffer` nor `FileWriter.write(blob)`._ + +## Where to Store Files + +As of v1.2.0, URLs to important file-system directories are provided. +Each URL is in the form _file:///path/to/spot/_, and can be converted to a +`DirectoryEntry` using `window.resolveLocalFileSystemURL()`. + +* `cordova.file.applicationDirectory` - Read-only directory where the application + is installed. (_iOS_, _Android_, _BlackBerry 10_, _OSX_, _windows_) + +* `cordova.file.applicationStorageDirectory` - Root directory of the application's + sandbox; on iOS & windows this location is read-only (but specific subdirectories [like + `/Documents` on iOS or `/localState` on windows] are read-write). All data contained within + is private to the app. (_iOS_, _Android_, _BlackBerry 10_, _OSX_) + +* `cordova.file.dataDirectory` - Persistent and private data storage within the + application's sandbox using internal memory (on Android, if you need to use + external memory, use `.externalDataDirectory`). On iOS, this directory is not + synced with iCloud (use `.syncedDataDirectory`). (_iOS_, _Android_, _BlackBerry 10_, _windows_) + +* `cordova.file.cacheDirectory` - Directory for cached data files or any files + that your app can re-create easily. The OS may delete these files when the device + runs low on storage, nevertheless, apps should not rely on the OS to delete files + in here. (_iOS_, _Android_, _BlackBerry 10_, _OSX_, _windows_) + +* `cordova.file.externalApplicationStorageDirectory` - Application space on + external storage. (_Android_) + +* `cordova.file.externalDataDirectory` - Where to put app-specific data files on + external storage. (_Android_) + +* `cordova.file.externalCacheDirectory` - Application cache on external storage. + (_Android_) + +* `cordova.file.externalRootDirectory` - External storage (SD card) root. (_Android_, _BlackBerry 10_) + +* `cordova.file.tempDirectory` - Temp directory that the OS can clear at will. Do not + rely on the OS to clear this directory; your app should always remove files as + applicable. (_iOS_, _OSX_, _windows_) + +* `cordova.file.syncedDataDirectory` - Holds app-specific files that should be synced + (e.g. to iCloud). (_iOS_, _windows_) + +* `cordova.file.documentsDirectory` - Files private to the app, but that are meaningful + to other application (e.g. Office files). Note that for _OSX_ this is the user's `~/Documents` directory. (_iOS_, _OSX_) + +* `cordova.file.sharedDirectory` - Files globally available to all applications (_BlackBerry 10_) + +## File System Layouts + +Although technically an implementation detail, it can be very useful to know how +the `cordova.file.*` properties map to physical paths on a real device. + +### iOS File System Layout + +| Device Path | `cordova.file.*` | `iosExtraFileSystems` | r/w? | persistent? | OS clears | sync | private | +|:-----------------------------------------------|:----------------------------|:----------------------|:----:|:-----------:|:---------:|:----:|:-------:| +| `/var/mobile/Applications//` | applicationStorageDirectory | - | r | N/A | N/A | N/A | Yes | +|    `appname.app/` | applicationDirectory | bundle | r | N/A | N/A | N/A | Yes | +|       `www/` | - | - | r | N/A | N/A | N/A | Yes | +|    `Documents/` | documentsDirectory | documents | r/w | Yes | No | Yes | Yes | +|       `NoCloud/` | - | documents-nosync | r/w | Yes | No | No | Yes | +|    `Library` | - | library | r/w | Yes | No | Yes? | Yes | +|       `NoCloud/` | dataDirectory | library-nosync | r/w | Yes | No | No | Yes | +|       `Cloud/` | syncedDataDirectory | - | r/w | Yes | No | Yes | Yes | +|       `Caches/` | cacheDirectory | cache | r/w | Yes* | Yes\*\*\*| No | Yes | +|    `tmp/` | tempDirectory | - | r/w | No\*\* | Yes\*\*\*| No | Yes | + + + \* Files persist across app restarts and upgrades, but this directory can + be cleared whenever the OS desires. Your app should be able to recreate any + content that might be deleted. + +\*\* Files may persist across app restarts, but do not rely on this behavior. Files + are not guaranteed to persist across updates. Your app should remove files from + this directory when it is applicable, as the OS does not guarantee when (or even + if) these files are removed. + +\*\*\* The OS may clear the contents of this directory whenever it feels it is + necessary, but do not rely on this. You should clear this directory as + appropriate for your application. + +### Android File System Layout + +| Device Path | `cordova.file.*` | `AndroidExtraFileSystems` | r/w? | persistent? | OS clears | private | +|:------------------------------------------------|:----------------------------|:--------------------------|:----:|:-----------:|:---------:|:-------:| +| `file:///android_asset/` | applicationDirectory | assets | r | N/A | N/A | Yes | +| `/data/data//` | applicationStorageDirectory | - | r/w | N/A | N/A | Yes | +|    `cache` | cacheDirectory | cache | r/w | Yes | Yes\* | Yes | +|    `files` | dataDirectory | files | r/w | Yes | No | Yes | +|       `Documents` | | documents | r/w | Yes | No | Yes | +| `/` | externalRootDirectory | sdcard | r/w | Yes | No | No | +|    `Android/data//` | externalApplicationStorageDirectory | - | r/w | Yes | No | No | +|       `cache` | externalCacheDirectry | cache-external | r/w | Yes | No\*\*| No | +|       `files` | externalDataDirectory | files-external | r/w | Yes | No | No | + +\* The OS may periodically clear this directory, but do not rely on this behavior. Clear + the contents of this directory as appropriate for your application. Should a user + purge the cache manually, the contents of this directory are removed. + +\*\* The OS does not clear this directory automatically; you are responsible for managing + the contents yourself. Should the user purge the cache manually, the contents of the + directory are removed. + +**Note**: If external storage can't be mounted, the `cordova.file.external*` +properties are `null`. + +### BlackBerry 10 File System Layout + +| Device Path | `cordova.file.*` | r/w? | persistent? | OS clears | private | +|:-------------------------------------------------------------|:----------------------------|:----:|:-----------:|:---------:|:-------:| +| `file:///accounts/1000/appdata//` | applicationStorageDirectory | r | N/A | N/A | Yes | +|    `app/native` | applicationDirectory | r | N/A | N/A | Yes | +|    `data/webviews/webfs/temporary/local__0` | cacheDirectory | r/w | No | Yes | Yes | +|    `data/webviews/webfs/persistent/local__0` | dataDirectory | r/w | Yes | No | Yes | +| `file:///accounts/1000/removable/sdcard` | externalRemovableDirectory | r/w | Yes | No | No | +| `file:///accounts/1000/shared` | sharedDirectory | r/w | Yes | No | No | + +*Note*: When application is deployed to work perimeter, all paths are relative to /accounts/1000-enterprise. + +### OS X File System Layout + +| Device Path | `cordova.file.*` | `iosExtraFileSystems` | r/w? | OS clears | private | +|:-------------------------------------------------|:----------------------------|:----------------------|:----:|:---------:|:-------:| +| `/Applications/.app/` | - | bundle | r | N/A | Yes | +|     `Content/Resources/` | applicationDirectory | - | r | N/A | Yes | +| `~/Library/Application Support//` | applicationStorageDirectory | - | r/w | No | Yes | +|     `files/` | dataDirectory | - | r/w | No | Yes | +| `~/Documents/` | documentsDirectory | documents | r/w | No | No | +| `~/Library/Caches//` | cacheDirectory | cache | r/w | No | Yes | +| `/tmp/` | tempDirectory | - | r/w | Yes\* | Yes | +| `/` | rootDirectory | root | r/w | No\*\* | No | + +**Note**: This is the layout for non sandboxed applications. I you enable sandboxing, the `applicationStorageDirectory` will be below ` ~/Library/Containers//Data/Library/Application Support`. + +\* Files persist across app restarts and upgrades, but this directory can + be cleared whenever the OS desires. Your app should be able to recreate any + content that might be deleted. You should clear this directory as + appropriate for your application. + +\*\* Allows access to the entire file system. This is only available for non sandboxed apps. + +### Windows File System Layout + +| Device Path | `cordova.file.*` | r/w? | persistent? | OS clears | private | +|:------------------------------------------------------|:----------------------------|:----:|:-----------:|:---------:|:-------:| +| `ms-appdata:///` | applicationDirectory | r | N/A | N/A | Yes | +|    `local/` | dataDirectory | r/w | Yes | No | Yes | +|    `temp/` | cacheDirectory | r/w | No | Yes\* | Yes | +|    `temp/` | tempDirectory | r/w | No | Yes\* | Yes | +|    `roaming/` | syncedDataDirectory | r/w | Yes | No | Yes | + +\* The OS may periodically clear this directory + + +## Android Quirks + +### Android Persistent storage location + +There are multiple valid locations to store persistent files on an Android +device. See [this page](http://developer.android.com/guide/topics/data/data-storage.html) +for an extensive discussion of the various possibilities. + +Previous versions of the plugin would choose the location of the temporary and +persistent files on startup, based on whether the device claimed that the SD +Card (or equivalent storage partition) was mounted. If the SD Card was mounted, +or if a large internal storage partition was available (such as on Nexus +devices,) then the persistent files would be stored in the root of that space. +This meant that all Cordova apps could see all of the files available on the +card. + +If the SD card was not available, then previous versions would store data under +`/data/data/`, which isolates apps from each other, but may still +cause data to be shared between users. + +It is now possible to choose whether to store files in the internal file +storage location, or using the previous logic, with a preference in your +application's `config.xml` file. To do this, add one of these two lines to +`config.xml`: + + + + + +Without this line, the File plugin will use `Internal` as the default. If +a preference tag is present, and is not one of these values, the application +will not start. + +If your application has previously been shipped to users, using an older (pre- +3.0.0) version of this plugin, and has stored files in the persistent filesystem, +then you should set the preference to `Compatibility` if your config.xml does not specify a location for the persistent filesystem. Switching the location to +"Internal" would mean that existing users who upgrade their application may be +unable to access their previously-stored files, depending on their device. + +If your application is new, or has never previously stored files in the +persistent filesystem, then the `Internal` setting is generally recommended. + +### Slow recursive operations for /android_asset + +Listing asset directories is really slow on Android. You can speed it up though, by +adding `src/android/build-extras.gradle` to the root of your android project (also +requires cordova-android@4.0.0 or greater). + +### Permisson to write to external storage when it's not mounted on Marshmallow + +Marshmallow requires the apps to ask for permissions when reading/writing to external locations. By +[default](http://developer.android.com/guide/topics/data/data-storage.html#filesExternal), your app has permission to write to +`cordova.file.applicationStorageDirectory` and `cordova.file.externalApplicationStorageDirectory`, and the plugin doesn't request permission +for these two directories unless external storage is not mounted. However due to a limitation, when external storage is not mounted, it would ask for +permission to write to `cordova.file.externalApplicationStorageDirectory`. + +## iOS Quirks + +- `cordova.file.applicationStorageDirectory` is read-only; attempting to store + files within the root directory will fail. Use one of the other `cordova.file.*` + properties defined for iOS (only `applicationDirectory` and `applicationStorageDirectory` are + read-only). +- `FileReader.readAsText(blob, encoding)` + - The `encoding` parameter is not supported, and UTF-8 encoding is always in effect. + +### iOS Persistent storage location + +There are two valid locations to store persistent files on an iOS device: the +Documents directory and the Library directory. Previous versions of the plugin +only ever stored persistent files in the Documents directory. This had the +side-effect of making all of an application's files visible in iTunes, which +was often unintended, especially for applications which handle lots of small +files, rather than producing complete documents for export, which is the +intended purpose of the directory. + +It is now possible to choose whether to store files in the documents or library +directory, with a preference in your application's `config.xml` file. To do this, +add one of these two lines to `config.xml`: + + + + + +Without this line, the File plugin will use `Compatibility` as the default. If +a preference tag is present, and is not one of these values, the application +will not start. + +If your application has previously been shipped to users, using an older (pre- +1.0) version of this plugin, and has stored files in the persistent filesystem, +then you should set the preference to `Compatibility`. Switching the location to +`Library` would mean that existing users who upgrade their application would be +unable to access their previously-stored files. + +If your application is new, or has never previously stored files in the +persistent filesystem, then the `Library` setting is generally recommended. + +## Firefox OS Quirks + +The File System API is not natively supported by Firefox OS and is implemented +as a shim on top of indexedDB. + +* Does not fail when removing non-empty directories +* Does not support metadata for directories +* Methods `copyTo` and `moveTo` do not support directories + +The following data paths are supported: +* `applicationDirectory` - Uses `xhr` to get local files that are packaged with the app. +* `dataDirectory` - For persistent app-specific data files. +* `cacheDirectory` - Cached files that should survive app restarts (Apps should not rely +on the OS to delete files in here). + +## Browser Quirks + +### Common quirks and remarks +- Each browser uses its own sandboxed filesystem. IE and Firefox use IndexedDB as a base. +All browsers use forward slash as directory separator in a path. +- Directory entries have to be created successively. +For example, the call `fs.root.getDirectory('dir1/dir2', {create:true}, successCallback, errorCallback)` +will fail if dir1 did not exist. +- The plugin requests user permission to use persistent storage at the application first start. +- Plugin supports `cdvfile://localhost` (local resources) only. I.e. external resources are not supported via `cdvfile`. +- The plugin does not follow ["File System API 8.3 Naming restrictions"](http://www.w3.org/TR/2011/WD-file-system-api-20110419/#naming-restrictions). +- Blob and File' `close` function is not supported. +- `FileSaver` and `BlobBuilder` are not supported by this plugin and don't have stubs. +- The plugin does not support `requestAllFileSystems`. This function is also missing in the specifications. +- Entries in directory will not be removed if you use `create: true` flag for existing directory. +- Files created via constructor are not supported. You should use entry.file method instead. +- Each browser uses its own form for blob URL references. +- `readAsDataURL` function is supported, but the mediatype in Chrome depends on entry name extension, +mediatype in IE is always empty (which is the same as `text-plain` according the specification), +the mediatype in Firefox is always `application/octet-stream`. +For example, if the content is `abcdefg` then Firefox returns `data:application/octet-stream;base64,YWJjZGVmZw==`, +IE returns `data:;base64,YWJjZGVmZw==`, Chrome returns `data:;base64,YWJjZGVmZw==`. +- `toInternalURL` returns the path in the form `file:///persistent/path/to/entry` (Firefox, IE). +Chrome returns the path in the form `cdvfile://localhost/persistent/file`. + +### Chrome quirks +- Chrome filesystem is not immediately ready after device ready event. As a workaround you can subscribe to `filePluginIsReady` event. +Example: +```javascript +window.addEventListener('filePluginIsReady', function(){ console.log('File plugin is ready');}, false); +``` +You can use `window.isFilePluginReadyRaised` function to check whether event was already raised. +- window.requestFileSystem TEMPORARY and PERSISTENT filesystem quotas are not limited in Chrome. +- To increase persistent storage in Chrome you need to call `window.initPersistentFileSystem` method. Persistent storage quota is 5 MB by default. +- Chrome requires `--allow-file-access-from-files` run argument to support API via `file:///` protocol. +- `File` object will be not changed if you use flag `{create:true}` when getting an existing `Entry`. +- events `cancelable` property is set to true in Chrome. This is contrary to the [specification](http://dev.w3.org/2009/dap/file-system/file-writer.html). +- `toURL` function in Chrome returns `filesystem:`-prefixed path depending on application host. +For example, `filesystem:file:///persistent/somefile.txt`, `filesystem:http://localhost:8080/persistent/somefile.txt`. +- `toURL` function result does not contain trailing slash in case of directory entry. +Chrome resolves directories with slash-trailed urls correctly though. +- `resolveLocalFileSystemURL` method requires the inbound `url` to have `filesystem` prefix. For example, `url` parameter for `resolveLocalFileSystemURL` +should be in the form `filesystem:file:///persistent/somefile.txt` as opposed to the form `file:///persistent/somefile.txt` in Android. +- Deprecated `toNativeURL` function is not supported and does not have a stub. +- `setMetadata` function is not stated in the specifications and not supported. +- INVALID_MODIFICATION_ERR (code: 9) is thrown instead of SYNTAX_ERR(code: 8) on requesting of a non-existant filesystem. +- INVALID_MODIFICATION_ERR (code: 9) is thrown instead of PATH_EXISTS_ERR(code: 12) on trying to exclusively create a file or directory, which already exists. +- INVALID_MODIFICATION_ERR (code: 9) is thrown instead of NO_MODIFICATION_ALLOWED_ERR(code: 6) on trying to call removeRecursively on the root file system. +- INVALID_MODIFICATION_ERR (code: 9) is thrown instead of NOT_FOUND_ERR(code: 1) on trying to moveTo directory that does not exist. + +### IndexedDB-based impl quirks (Firefox and IE) +- `.` and `..` are not supported. +- IE does not support `file:///`-mode; only hosted mode is supported (http://localhost:xxxx). +- Firefox filesystem size is not limited but each 50MB extension will request a user permission. +IE10 allows up to 10mb of combined AppCache and IndexedDB used in implementation of filesystem without prompting, +once you hit that level you will be asked if you want to allow it to be increased up to a max of 250mb per site. +So `size` parameter for `requestFileSystem` function does not affect filesystem in Firefox and IE. +- `readAsBinaryString` function is not stated in the Specs and not supported in IE and does not have a stub. +- `file.type` is always null. +- You should not create entry using DirectoryEntry instance callback result which was deleted. +Otherwise, you will get a 'hanging entry'. +- Before you can read a file, which was just written you need to get a new instance of this file. +- `setMetadata` function, which is not stated in the Specs supports `modificationTime` field change only. +- `copyTo` and `moveTo` functions do not support directories. +- Directories metadata is not supported. +- Both Entry.remove and directoryEntry.removeRecursively don't fail when removing +non-empty directories - directories being removed are cleaned along with contents instead. +- `abort` and `truncate` functions are not supported. +- progress events are not fired. For example, this handler will be not executed: +```javascript +writer.onprogress = function() { /*commands*/ }; +``` + +## Upgrading Notes + +In v1.0.0 of this plugin, the `FileEntry` and `DirectoryEntry` structures have changed, +to be more in line with the published specification. + +Previous (pre-1.0.0) versions of the plugin stored the device-absolute-file-location +in the `fullPath` property of `Entry` objects. These paths would typically look like + + /var/mobile/Applications//Documents/path/to/file (iOS) + /storage/emulated/0/path/to/file (Android) + +These paths were also returned by the `toURL()` method of the `Entry` objects. + +With v1.0.0, the `fullPath` attribute is the path to the file, _relative to the root of +the HTML filesystem_. So, the above paths would now both be represented by a `FileEntry` +object with a `fullPath` of + + /path/to/file + +If your application works with device-absolute-paths, and you previously retrieved those +paths through the `fullPath` property of `Entry` objects, then you should update your code +to use `entry.toURL()` instead. + +For backwards compatibility, the `resolveLocalFileSystemURL()` method will accept a +device-absolute-path, and will return an `Entry` object corresponding to it, as long as that +file exists within either the `TEMPORARY` or `PERSISTENT` filesystems. + +This has particularly been an issue with the File-Transfer plugin, which previously used +device-absolute-paths (and can still accept them). It has been updated to work correctly +with FileSystem URLs, so replacing `entry.fullPath` with `entry.toURL()` should resolve any +issues getting that plugin to work with files on the device. + +In v1.1.0 the return value of `toURL()` was changed (see [CB-6394](https://issues.apache.org/jira/browse/CB-6394)) +to return an absolute 'file://' URL. wherever possible. To ensure a 'cdvfile:'-URL you can use `toInternalURL()` now. +This method will now return filesystem URLs of the form + + cdvfile://localhost/persistent/path/to/file + +which can be used to identify the file uniquely. + +## cdvfile protocol +**Purpose** + +`cdvfile://localhost/persistent|temporary|another-fs-root*/path/to/file` can be used for platform-independent file paths. +cdvfile paths are supported by core plugins - for example you can download an mp3 file to cdvfile-path via `cordova-plugin-file-transfer` and play it via `cordova-plugin-media`. + +__*Note__: See [Where to Store Files](#where-to-store-files), [File System Layouts](#file-system-layouts) and [Configuring the Plugin](#configuring-the-plugin-optional) for more details about available fs roots. + +To use `cdvfile` as a tag' `src` you can convert it to native path via `toURL()` method of the resolved fileEntry, which you can get via `resolveLocalFileSystemURL` - see examples below. + +You can also use `cdvfile://` paths directly in the DOM, for example: +```HTML + +``` + +__Note__: This method requires following Content Security rules updates: +* Add `cdvfile:` scheme to `Content-Security-Policy` meta tag of the index page, e.g.: + - `` +* Add `` to `config.xml`. + +**Converting cdvfile:// to native path** + +```javascript +resolveLocalFileSystemURL('cdvfile://localhost/temporary/path/to/file.mp4', function(entry) { + var nativePath = entry.toURL(); + console.log('Native URI: ' + nativePath); + document.getElementById('video').src = nativePath; +``` + +**Converting native path to cdvfile://** + +```javascript +resolveLocalFileSystemURL(nativePath, function(entry) { + console.log('cdvfile URI: ' + entry.toInternalURL()); +``` + +**Using cdvfile in core plugins** + +```javascript +fileTransfer.download(uri, 'cdvfile://localhost/temporary/path/to/file.mp3', function (entry) { ... +``` +```javascript +var my_media = new Media('cdvfile://localhost/temporary/path/to/file.mp3', ...); +my_media.play(); +``` + +#### cdvfile quirks +- Using `cdvfile://` paths in the DOM is not supported on Windows platform (a path can be converted to native instead). + + +## List of Error Codes and Meanings +When an error is thrown, one of the following codes will be used. + +| Code | Constant | +|-----:|:------------------------------| +| 1 | `NOT_FOUND_ERR` | +| 2 | `SECURITY_ERR` | +| 3 | `ABORT_ERR` | +| 4 | `NOT_READABLE_ERR` | +| 5 | `ENCODING_ERR` | +| 6 | `NO_MODIFICATION_ALLOWED_ERR` | +| 7 | `INVALID_STATE_ERR` | +| 8 | `SYNTAX_ERR` | +| 9 | `INVALID_MODIFICATION_ERR` | +| 10 | `QUOTA_EXCEEDED_ERR` | +| 11 | `TYPE_MISMATCH_ERR` | +| 12 | `PATH_EXISTS_ERR` | + +## Configuring the Plugin (Optional) + +The set of available filesystems can be configured per-platform. Both iOS and +Android recognize a tag in `config.xml` which names the +filesystems to be installed. By default, all file-system roots are enabled. + + + + +### Android + +* `files`: The application's internal file storage directory +* `files-external`: The application's external file storage directory +* `sdcard`: The global external file storage directory (this is the root of the SD card, if one is installed). You must have the `android.permission.WRITE_EXTERNAL_STORAGE` permission to use this. +* `cache`: The application's internal cache directory +* `cache-external`: The application's external cache directory +* `assets`: The application's bundle (read-only) +* `root`: The entire device filesystem + +Android also supports a special filesystem named "documents", which represents a "/Documents/" subdirectory within the "files" filesystem. + +### iOS + +* `library`: The application's Library directory +* `documents`: The application's Documents directory +* `cache`: The application's Cache directory +* `bundle`: The application's bundle; the location of the app itself on disk (read-only) +* `root`: The entire device filesystem + +By default, the library and documents directories can be synced to iCloud. You can also request two additional filesystems, `library-nosync` and `documents-nosync`, which represent a special non-synced directory within the `/Library` or `/Documents` filesystem. + +## Sample: Create Files and Directories, Write, Read, and Append files
+ +The File plugin allows you to do things like store files in a temporary or persistent storage location for your app (sandboxed storage) and to store files in other platform-dependent locations. The code snippets in this section demonstrate different tasks including: +* [Accessing the file system](#persistent) +* Using cross-platform Cordova file URLs to [store your files](#appendFile) (see _Where to Store Files_ for more info) +* Creating [files](#persistent) and [directories](#createDir) +* [Writing to files](#writeFile) +* [Reading files](#readFile) +* [Appending files](#appendFile) +* [Display an image file](#displayImage) + +## Create a persistent file + +Before you use the File plugin APIs, you can get access to the file system using `requestFileSystem`. When you do this, you can request either persistent or temporary storage. Persistent storage will not be removed unless permission is granted by the user. + +When you get file system access using `requestFileSystem`, access is granted for the sandboxed file system only (the sandbox limits access to the app itself), not for general access to any file system location on the device. (To access file system locations outside the sandboxed storage, use other methods such as window.requestLocalFileSystemURL, which support platform-specific locations. For one example of this, see _Append a File_.) + +Here is a request for persistent storage. + +>*Note* When targeting WebView clients (instead of a browser) or native apps (Windows), you dont need to use `requestQuota` before using persistent storage. + +```js +window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fs) { + + console.log('file system open: ' + fs.name); + fs.root.getFile("newPersistentFile.txt", { create: true, exclusive: false }, function (fileEntry) { + + console.log("fileEntry is file?" + fileEntry.isFile.toString()); + // fileEntry.name == 'someFile.txt' + // fileEntry.fullPath == '/someFile.txt' + writeFile(fileEntry, null); + + }, onErrorCreateFile); + +}, onErrorLoadFs); +``` + +The success callback receives FileSystem object (fs). Use `fs.root` to return a DirectoryEntry object, which you can use to create or get a file (by calling `getFile`). In this example, `fs.root` is a DirectoryEntry object that represents the persistent storage in the sandboxed file system. + +The success callback for `getFile` receives a FileEntry object. You can use this to perform file write and file read operations. + +## Create a temporary file + +Here is an example of a request for temporary storage. Temporary storage may be deleted by the operating system if the device runs low on memory. + +```js +window.requestFileSystem(window.TEMPORARY, 5 * 1024 * 1024, function (fs) { + + console.log('file system open: ' + fs.name); + createFile(fs.root, "newTempFile.txt", false); + +}, onErrorLoadFs); +``` +When you are using temporary storage, you can create or get the file by calling `getFile`. As in the persistent storage example, this will give you a FileEntry object that you can use for read or write operations. + +```js +function createFile(dirEntry, fileName, isAppend) { + // Creates a new file or returns the file if it already exists. + dirEntry.getFile(fileName, {create: true, exclusive: false}, function(fileEntry) { + + writeFile(fileEntry, null, isAppend); + + }, onErrorCreateFile); + +} +``` + +## Write to a file + +Once you have a FileEntry object, you can write to the file by calling `createWriter`, which returns a FileWriter object in the success callback. Call the `write` method of FileWriter to write to the file. + +```js +function writeFile(fileEntry, dataObj) { + // Create a FileWriter object for our FileEntry (log.txt). + fileEntry.createWriter(function (fileWriter) { + + fileWriter.onwriteend = function() { + console.log("Successful file write..."); + readFile(fileEntry); + }; + + fileWriter.onerror = function (e) { + console.log("Failed file write: " + e.toString()); + }; + + // If data object is not passed in, + // create a new Blob instead. + if (!dataObj) { + dataObj = new Blob(['some file data'], { type: 'text/plain' }); + } + + fileWriter.write(dataObj); + }); +} +``` + +## Read a file + +You also need a FileEntry object to read an existing file. Use the file property of FileEntry to get the file reference, and then create a new FileReader object. You can use methods like `readAsText` to start the read operation. When the read operation is complete, `this.result` stores the result of the read operation. + +```js +function readFile(fileEntry) { + + fileEntry.file(function (file) { + var reader = new FileReader(); + + reader.onloadend = function() { + console.log("Successful file read: " + this.result); + displayFileData(fileEntry.fullPath + ": " + this.result); + }; + + reader.readAsText(file); + + }, onErrorReadFile); +} +``` + +## Append a file using alternative methods + +Of course, you will often want to append existing files instead of creating new ones. Here is an example of that. This example shows another way that you can access the file system using window.resolveLocalFileSystemURL. In this example, pass the cross-platform Cordova file URL, cordova.file.dataDirectory, to the function. The success callback receives a DirectoryEntry object, which you can use to do things like create a file. + +```js +window.resolveLocalFileSystemURL(cordova.file.dataDirectory, function (dirEntry) { + console.log('file system open: ' + dirEntry.name); + var isAppend = true; + createFile(dirEntry, "fileToAppend.txt", isAppend); +}, onErrorLoadFs); +``` + +In addition to this usage, you can use `resolveLocalFileSystemURL` to get access to some file system locations that are not part of the sandboxed storage system. See _Where to store Files_ for more information; many of these storage locations are platform-specific. You can also pass cross-platform file system locations to `resolveLocalFileSystemURL` using the _cdvfile protocol_. + +For the append operation, there is nothing new in the `createFile` function that is called in the preceding code (see the preceding examples for the actual code). `createFile` calls `writeFile`. In `writeFile`, you check whether an append operation is requested. + +Once you have a FileWriter object, call the `seek` method, and pass in the index value for the position where you want to write. In this example, you also test whether the file exists. After calling seek, then call the write method of FileWriter. + +```js +function writeFile(fileEntry, dataObj, isAppend) { + // Create a FileWriter object for our FileEntry (log.txt). + fileEntry.createWriter(function (fileWriter) { + + fileWriter.onwriteend = function() { + console.log("Successful file read..."); + readFile(fileEntry); + }; + + fileWriter.onerror = function (e) { + console.log("Failed file read: " + e.toString()); + }; + + // If we are appending data to file, go to the end of the file. + if (isAppend) { + try { + fileWriter.seek(fileWriter.length); + } + catch (e) { + console.log("file doesn't exist!"); + } + } + fileWriter.write(dataObj); + }); +} +``` + +## Store an existing binary file + +We already showed how to write to a file that you just created in the sandboxed file system. What if you need to get access to an existing file and convert that to something you can store on your device? In this example, you obtain a file using an xhr request, and then save it to the cache in the sandboxed file system. + +Before you get the file, get a FileSystem reference using `requestFileSystem`. By passing window.TEMPORARY in the method call (same as before), the returned FileSystem object (fs) represents the cache in the sandboxed file system. Use `fs.root` to get the DirectoryEntry object that you need. + +```js +window.requestFileSystem(window.TEMPORARY, 5 * 1024 * 1024, function (fs) { + + console.log('file system open: ' + fs.name); + getSampleFile(fs.root); + +}, onErrorLoadFs); +``` + +For completeness, here is the xhr request to get a Blob image. There is nothing Cordova-specific in this code, except that you forward the DirectoryEntry reference that you already obtained as an argument to the saveFile function. You will save the blob image and display it later after reading the file (to validate the operation). + +```js +function getSampleFile(dirEntry) { + + var xhr = new XMLHttpRequest(); + xhr.open('GET', 'http://cordova.apache.org/static/img/cordova_bot.png', true); + xhr.responseType = 'blob'; + + xhr.onload = function() { + if (this.status == 200) { + + var blob = new Blob([this.response], { type: 'image/png' }); + saveFile(dirEntry, blob, "downloadedImage.png"); + } + }; + xhr.send(); +} +``` +>*Note* For Cordova 5 security, the preceding code requires that you add the domain name, http://cordova.apache.org, to the Content-Security-Policy element in index.html. + +After getting the file, copy the contents to a new file. The current DirectoryEntry object is already associated with the app cache. + +```js +function saveFile(dirEntry, fileData, fileName) { + + dirEntry.getFile(fileName, { create: true, exclusive: false }, function (fileEntry) { + + writeFile(fileEntry, fileData); + + }, onErrorCreateFile); +} +``` + +In writeFile, you pass in the Blob object as the dataObj and you will save that in the new file. + +```js +function writeFile(fileEntry, dataObj, isAppend) { + + // Create a FileWriter object for our FileEntry (log.txt). + fileEntry.createWriter(function (fileWriter) { + + fileWriter.onwriteend = function() { + console.log("Successful file write..."); + if (dataObj.type == "image/png") { + readBinaryFile(fileEntry); + } + else { + readFile(fileEntry); + } + }; + + fileWriter.onerror = function(e) { + console.log("Failed file write: " + e.toString()); + }; + + fileWriter.write(dataObj); + }); +} +``` + +After writing to the file, read it and display it. You saved the image as binary data, so you can read it using FileReader.readAsArrayBuffer. + +```js +function readBinaryFile(fileEntry) { + + fileEntry.file(function (file) { + var reader = new FileReader(); + + reader.onloadend = function() { + + console.log("Successful file write: " + this.result); + displayFileData(fileEntry.fullPath + ": " + this.result); + + var blob = new Blob([new Uint8Array(this.result)], { type: "image/png" }); + displayImage(blob); + }; + + reader.readAsArrayBuffer(file); + + }, onErrorReadFile); +} +``` + +After reading the data, you can display the image using code like this. Use window.URL.createObjectURL to get a DOM string for the Blob image. + +```js +function displayImage(blob) { + + // Displays image if result is a valid DOM string for an image. + var elem = document.getElementById('imageFile'); + // Note: Use window.URL.revokeObjectURL when finished with image. + elem.src = window.URL.createObjectURL(blob); +} +``` + +## Display an image file + +To display an image using a FileEntry, you can call the `toURL` method. + +```js +function displayImageByFileURL(fileEntry) { + var elem = document.getElementById('imageFile'); + elem.src = fileEntry.toURL(); +} +``` + +If you are using some platform-specific URIs instead of a FileEntry and you want to display an image, you may need to include the main part of the URI in the Content-Security-Policy element in index.html. For example, on Windows 10, you can include `ms-appdata:` in your element. Here is an example. + +```html + +``` + +## Create Directories + +In the code here, you create directories in the root of the app storage location. You could use this code with any writable storage location (that is, any DirectoryEntry). Here, you write to the application cache (assuming that you used window.TEMPORARY to get your FileSystem object) by passing fs.root into this function. + +This code creates the /NewDirInRoot/images folder in the application cache. For platform-specific values, look at _File System Layouts_. + +```js +function createDirectory(rootDirEntry) { + rootDirEntry.getDirectory('NewDirInRoot', { create: true }, function (dirEntry) { + dirEntry.getDirectory('images', { create: true }, function (subDirEntry) { + + createFile(subDirEntry, "fileInNewSubDir.txt"); + + }, onErrorGetDir); + }, onErrorGetDir); +} +``` + +When creating subfolders, you need to create each folder separately as shown in the preceding code. diff --git a/plugins/cordova-plugin-file/RELEASENOTES.md b/plugins/cordova-plugin-file/RELEASENOTES.md new file mode 100644 index 0000000..3dfc70c --- /dev/null +++ b/plugins/cordova-plugin-file/RELEASENOTES.md @@ -0,0 +1,455 @@ + +# Release Notes + +### 4.3.3 (Apr 27, 2017) +* [CB-12622](https://issues.apache.org/jira/browse/CB-12622) Added **Android 6.0** build badge to `README` +* [CB-12685](https://issues.apache.org/jira/browse/CB-12685) added `package.json` to tests folder + +### 4.3.2 (Feb 28, 2017) +* [CB-12353](https://issues.apache.org/jira/browse/CB-12353) Corrected merges usage in `plugin.xml` +* [CB-12369](https://issues.apache.org/jira/browse/CB-12369) Add plugin typings from `DefinitelyTyped` +* [CB-12363](https://issues.apache.org/jira/browse/CB-12363) Added build badges for **iOS 9.3** and **iOS 10.0** +* [CB-12230](https://issues.apache.org/jira/browse/CB-12230) Removed **Windows 8.1** build badges + +### 4.3.1 (Dec 07, 2016) +* [CB-12224](https://issues.apache.org/jira/browse/CB-12224) Updated version and RELEASENOTES.md for release 4.3.1 +* [CB-12112](https://issues.apache.org/jira/browse/CB-12112) windows: Make available to move folder trees +* fix ENCODING_ERR for applicationDirectory +* [CB-11848](https://issues.apache.org/jira/browse/CB-11848) windows: Remove duplicate slash after file system path +* [CB-11917](https://issues.apache.org/jira/browse/CB-11917) - Remove pull request template checklist item: "iCLA has been submitted…" +* [CB-11947](https://issues.apache.org/jira/browse/CB-11947) fixed typo that occurs when adding file-transfer plugin +* [CB-11832](https://issues.apache.org/jira/browse/CB-11832) Incremented plugin version. + +### 4.3.0 (Sep 08, 2016) +* [CB-11795](https://issues.apache.org/jira/browse/CB-11795) Add 'protective' entry to cordovaDependencies +* Add handling for `SecurityException` +* [CB-11368](https://issues.apache.org/jira/browse/CB-11368) **android**: Resolve content `URLs` produced by contacts plugin +* Plugin uses `Android Log class` and not `Cordova LOG class` +* [CB-11693](https://issues.apache.org/jira/browse/CB-11693) **ios**: Run copy and move operations in the background thread +* [CB-11699](https://issues.apache.org/jira/browse/CB-11699) Read files as Data URLs properly +* [CB-11305](https://issues.apache.org/jira/browse/CB-11305) Enable `cdvfile: assets fs root` for `DOM` requests +* [CB-11385](https://issues.apache.org/jira/browse/CB-11385) android: Import java.nio.charset.Charset in LocalFileSystem class +* Add badges for paramedic builds on Jenkins +* [CB-11407](https://issues.apache.org/jira/browse/CB-11407) ios: added extern keyword to constants to fix phonegap-webview-ios template issue. +* [CB-11385](https://issues.apache.org/jira/browse/CB-11385) **android**: Does not pass sonarqube scan +* Add pull request template. +* Minor edits to the `README.md` +* [CB-11142](https://issues.apache.org/jira/browse/CB-11142) Fix the `NeedPermission` code for the case when external media is not mounted in Android +* [CB-11003](https://issues.apache.org/jira/browse/CB-11003) Adding samples to Readme. +* [CB-10996](https://issues.apache.org/jira/browse/CB-10996) Adding front matter to README.md +* [CB-11115](https://issues.apache.org/jira/browse/CB-11115) **android**: Removing dependency on FileDescriptor toString in content provider tests + +### 4.2.0 (Apr 15, 2016) +* [CB-10960](https://issues.apache.org/jira/browse/CB-10960) Uncaught `#` in `write()` when `readyState != WRITING ?` +* Replace `PermissionHelper.java` with `cordova-plugin-compat` +* [CB-10977](https://issues.apache.org/jira/browse/CB-10977) **Android** Removing global state used for permission requests +* CB-10798, [CB-10384](https://issues.apache.org/jira/browse/CB-10384) Fixing permissions for **Marshmallow**. +* Fix test failure on **WP 8.1** +* [CB-10577](https://issues.apache.org/jira/browse/CB-10577) **Windows** `resolveLocalFileSystemURL` should omit trailing slash for file +* [CB-7862](https://issues.apache.org/jira/browse/CB-7862) `FileReader` reads large files in chunks with progress. +* [CB-10577](https://issues.apache.org/jira/browse/CB-10577) **Android** `resolveLocalFileSystemURL` should detect directory vs file. +* [CB-9753](https://issues.apache.org/jira/browse/CB-9753) index out of bounds on `requestFileSystem`. +* Remove `warning` emoji, as it doesn't correctly display in the docs website: cordova.apache.org/docs/en/dev/cordova-plugin-file/index.html. This closes #166 +* [CB-10636](https://issues.apache.org/jira/browse/CB-10636) Add `JSHint` for plugins +* [CB-10411](https://issues.apache.org/jira/browse/CB-10411) Error in `file.spec.129` of `cordova-plugin-file` + +### 4.1.1 (Feb 09, 2016) +* Edit package.json license to match SPDX id +* [CB-10419](https://issues.apache.org/jira/browse/CB-10419) cordova-plugin-file 4.0.0 error with browserify workflow + +### 4.1.0 (Jan 15, 2016) +* added `.ratignore` file +* [CB-10319](https://issues.apache.org/jira/browse/CB-10319) **android** Adding reflective helper methods for permission requests +* [CB-10023](https://issues.apache.org/jira/browse/CB-10023) Fix `proxy not found error` on Chrome. +* [CB-8863](https://issues.apache.org/jira/browse/CB-8863) **ios** Fix block usage of self + +### 4.0.0 (Nov 18, 2015) +* [CB-10035](https://issues.apache.org/jira/browse/CB-10035) Updated `RELEASENOTES` to be newest to oldest +* [CB-8497](https://issues.apache.org/jira/browse/CB-8497) Fix handling of file paths with `#` character +* Do not inject default `AndroidPersistentFileLocation` into `config.xml` +* [CB-9891](https://issues.apache.org/jira/browse/CB-9891): Fix permission errors due to `URI encoding` inconsistency on **Android** +* Fixed `NullPointer Exception` in **Android 5** and above due to invalid column name on cursor +* Fix default persistent file location +* fix `applicationDirectory` to use `ms-appx:///` +* Add **Windows** paths to `cordova.file` object +* [CB-9851](https://issues.apache.org/jira/browse/CB-9851) Document `cdvfile` protocol quirk - using `cdvfile://` in the `DOM` is not supported on **Windows** +* [CB-9752](https://issues.apache.org/jira/browse/CB-9752) `getDirectory` fails on valid directory with assets filesystem +* [CB-7253](https://issues.apache.org/jira/browse/CB-7253) `requestFileSystem` fails when no external storage is present +* Adding permissions for **Marshmallow**. Now supports **Anrdoid 6.0** +* Fixing contribute link. +* always use setters to fix memory issues without `ARC` for **iOS** +* [CB-9331](https://issues.apache.org/jira/browse/CB-9331) `getFreeDiskSpace` **iOS**. +* override `resolveLocalFileSystemURL` by `webkitResolveLocalFileSystemURL` for **browser** platform add `.project` into git ignore list +* Fail with `FileError.ENCODING_ERR` on encoding exception. +* [CB-9544](https://issues.apache.org/jira/browse/CB-9544) Add file plugin for **OSX** +* [CB-9539](https://issues.apache.org/jira/browse/CB-9539) Fixed test failure on **Android** emulator +* Added docs on `CSP` rules needed for using `cdvfile` in DOM src. This closes #120 +* Added `cdvfile` protocol purpose description and examples + +### 3.0.0 (Aug 18, 2015) +* Make Android default persistent file location internal +* Fixed issue with file paths not existing when using browserify +* [CB-9251](https://issues.apache.org/jira/browse/CB-9251): Changed from Intents to Preferences object as per the issue +* [CB-9215](https://issues.apache.org/jira/browse/CB-9215) Add cordova-plugin-file manual test for windows platform + +### 2.1.0 (Jun 17, 2015) +* added missing license header +* [CB-9128](https://issues.apache.org/jira/browse/CB-9128) cordova-plugin-file documentation translation: cordova-plugin-file +* fix npm md +* [CB-8844](https://issues.apache.org/jira/browse/CB-8844) Increased timeout for asset tests +* Updated resolveFileSystem.js so it can be parsed by uglifyJS +* [CB-8860](https://issues.apache.org/jira/browse/CB-8860) cordova-plugin-file documentation translation: cordova-plugin-file +* [CB-8792](https://issues.apache.org/jira/browse/CB-8792) Fixes reading of json files using readAsText + +### 2.0.0 (Apr 15, 2015) +* [CB-8849](https://issues.apache.org/jira/browse/CB-8849) Fixed ReadAsArrayBuffer to return ArrayBuffer and not Array on WP8 +* [CB-8819](https://issues.apache.org/jira/browse/CB-8819) Fixed FileReader's readAsBinaryString on wp8 +* [CB-8746](https://issues.apache.org/jira/browse/CB-8746) gave plugin major version bump +* [CB-8683](https://issues.apache.org/jira/browse/CB-8683) android: Fix broken unit tests from plugin rename +* [CB-8683](https://issues.apache.org/jira/browse/CB-8683) changed plugin-id to pacakge-name +* [CB-8653](https://issues.apache.org/jira/browse/CB-8653) properly updated translated docs to use new id +* [CB-8653](https://issues.apache.org/jira/browse/CB-8653) updated translated docs to use new id +* Use TRAVIS_BUILD_DIR, install paramedic by npm +* docs: added Windows to supported platforms +* [CB-8699](https://issues.apache.org/jira/browse/CB-8699) [CB-6428](https://issues.apache.org/jira/browse/CB-6428) Fix uncompressed assets being copied as zero length files +* [CB-6428](https://issues.apache.org/jira/browse/CB-6428) android: Fix assets FileEntry having size of -1 +* android: Move URLforFullPath into base class (and rename to localUrlforFullPath) +* [CB-6428](https://issues.apache.org/jira/browse/CB-6428) Mention build-extras.gradle in README +* [CB-7109](https://issues.apache.org/jira/browse/CB-7109) android: Parse arguments off of the main thread (close #97) +* [CB-8695](https://issues.apache.org/jira/browse/CB-8695) ios: Fix `blob.slice()` for `asset-library` URLs (close #105) +* Tweak build-extras.gradle to just read/write to main `assets/` instead of `build/` +* [CB-8689](https://issues.apache.org/jira/browse/CB-8689) Fix NPE in makeEntryForNativeUri (was affecting file-transfer) +* [CB-8675](https://issues.apache.org/jira/browse/CB-8675) Revert "CB-8351 ios: Use base64EncodedStringWithOptions instead of CordovaLib's class extension" +* [CB-8653](https://issues.apache.org/jira/browse/CB-8653) Updated Readme +* [CB-8659](https://issues.apache.org/jira/browse/CB-8659): ios: 4.0.x Compatibility: Remove use of initWebView method +* Add a cache to speed up AssetFilesystem directory listings +* [CB-8663](https://issues.apache.org/jira/browse/CB-8663) android: Don't notify MediaScanner of private files +* Don't log stacktrace for normal exceptions (e.g. file not found) +* android: Don't use LimitedInputStream when reading entire file (optimization) +* [CB-6428](https://issues.apache.org/jira/browse/CB-6428) android: Add support for directory copies from assets -> filesystem +* android: Add `listChildren()`: Java-consumable version of `readEntriesAtLocalURL()` +* [CB-6428](https://issues.apache.org/jira/browse/CB-6428) android: Add support for file:///android_asset URLs +* [CB-8642](https://issues.apache.org/jira/browse/CB-8642) android: Fix content URIs not working with resolve / copy +* Tweak tests to fail if deleteEntry fails (rather than time out) +* android: Ensure LocalFilesystemURL can only be created with "cdvfile" URLs +* android: Move CordovaResourceApi into Filesystem base class +* android: Use `CordovaResourceApi.mapUriToFile()` rather than own custom logic in ContentFilesystem +* android: Use Uri.parse rather than manual parsing in resolveLocalFileSystemURI +* Tweak test case that failed twice on error rather than just once +* android: Delete invalid JavaDoc (lint errors) +* android: Use CordovaResourceApi rather than FileHelper +* [CB-8032](https://issues.apache.org/jira/browse/CB-8032) - File Plugin - Add nativeURL external method support for CDVFileSystem->makeEntryForPath:isDirectory: (closes #96) +* [CB-8567](https://issues.apache.org/jira/browse/CB-8567) Integrate TravisCI +* [CB-8438](https://issues.apache.org/jira/browse/CB-8438) cordova-plugin-file documentation translation: cordova-plugin-file +* [CB-8538](https://issues.apache.org/jira/browse/CB-8538) Added package.json file +* [CB-7956](https://issues.apache.org/jira/browse/CB-7956) Add cordova-plugin-file support for browser platform +* [CB-8423](https://issues.apache.org/jira/browse/CB-8423) Corrected usage of done() in async tests +* [CB-8459](https://issues.apache.org/jira/browse/CB-8459) Fixes spec 111 failure due to incorrect relative paths handling +* Code cleanup, whitespace +* Added nativeURL property to FileEntry, implemented readAsArrayBuffer and readAsBinaryString + +### 1.3.3 (Feb 04, 2015) +* [CB-7927](https://issues.apache.org/jira/browse/CB-7927) Encoding data to bytes instead of chars when writing a file. +* ios: Fix compile warning about implicit int conversion +* [CB-8351](https://issues.apache.org/jira/browse/CB-8351) ios: Use base64EncodedStringWithOptions instead of CordovaLib's class extension +* [CB-8351](https://issues.apache.org/jira/browse/CB-8351) ios: Use argumentForIndex rather than NSArray extension +* [CB-8351](https://issues.apache.org/jira/browse/CB-8351) ios: Use a local copy of valueForKeyIsNumber rather than CordovaLib's version +* windows: Handle url's containing absolute windows path starting with drive letter and colon (encoded as %3A) through root FS +* windows: Rework to use normal url form +* android: refactor: Make Filesystem base class store its own name, rootUri, and rootEntry +* android: Simplify code a bit by making makeEntryForPath not throw JSONException +* [CB-6431](https://issues.apache.org/jira/browse/CB-6431) android: Fix plugin breaking content: URLs +* [CB-7375](https://issues.apache.org/jira/browse/CB-7375) Never create new FileSystem instances (except on windows since they don't implement requestAllFileSystems()) + +### 1.3.2 (Dec 02, 2014) +* Gets rid of thread block error in File plugin +* [CB-7917](https://issues.apache.org/jira/browse/CB-7917) Made tests file.spec.114 - 116 pass for **Windows** platform +* [CB-7977](https://issues.apache.org/jira/browse/CB-7977) Mention `deviceready` in plugin docs +* [CB-7602](https://issues.apache.org/jira/browse/CB-7602): Fix `isCopyOnItself` logic +* [CB-7700](https://issues.apache.org/jira/browse/CB-7700) cordova-plugin-file documentation translation: cordova-plugin-file +* Use one proxy for both **Windows** and **Windows8** platforms +* [CB-6994](https://issues.apache.org/jira/browse/CB-6994) Fixes result, returned by proxy's write method +* [fxos] update `__format__` to match `pathsPrefix` +* [CB-6994](https://issues.apache.org/jira/browse/CB-6994) Improves merged code to be able to write a File +* Optimize `FileProxy` for **Windows** platforms +* Synchronize changes with **Windows** platform +* Fix function write for big files on **Windows 8** +* Write file in background +* [CB-7487](https://issues.apache.org/jira/browse/CB-7487) **Android** Broadcast file write This allows MTP USB shares to show the file immediately without reboot/manual refresh using 3rd party app. +* [CB-7700](https://issues.apache.org/jira/browse/CB-7700) cordova-plugin-file documentation translation: cordova-plugin-file +* [CB-7571](https://issues.apache.org/jira/browse/CB-7571) Bump version of nested plugin to match parent plugin + +### 1.3.1 (Sep 17, 2014) +* [CB-7471](https://issues.apache.org/jira/browse/CB-7471) cordova-plugin-file documentation translation +* [CB-7272](https://issues.apache.org/jira/browse/CB-7272) Replace confusing "r/o" abbreviation with just "r" +* [CB-7423](https://issues.apache.org/jira/browse/CB-7423) encode path before attempting to resolve +* [CB-7375](https://issues.apache.org/jira/browse/CB-7375) Fix the filesystem name in resolveLocalFileSystemUri +* [CB-7445](https://issues.apache.org/jira/browse/CB-7445) [BlackBerry10] resolveLocalFileSystemURI - change DEFAULT_SIZE to MAX_SIZE +* [CB-7458](https://issues.apache.org/jira/browse/CB-7458) [BlackBerry10] resolveLocalFileSystemURL - add filesystem property +* [CB-7445](https://issues.apache.org/jira/browse/CB-7445) [BlackBerry10] Add default file system size to prevent quota exceeded error on initial install +* [CB-7431](https://issues.apache.org/jira/browse/CB-7431) Avoid calling done() twice in file.spec.109 test +* [CB-7413](https://issues.apache.org/jira/browse/CB-7413) Adds support of 'ms-appdata://' URIs +* [CB-7422](https://issues.apache.org/jira/browse/CB-7422) [File Tests] Use proper fileSystem to create fullPath +* [CB-7375](https://issues.apache.org/jira/browse/CB-7375) [Entry] get proper filesystem in Entry +* Amazon related changes. +* [CB-7375](https://issues.apache.org/jira/browse/CB-7375) Remove leading slash statement from condition +* Refactored much of the logic in FileMetadata constructor. Directory.size will return 0 +* [CB-7419](https://issues.apache.org/jira/browse/CB-7419) [WP8] Added support to get metada from dir +* [CB-7418](https://issues.apache.org/jira/browse/CB-7418) [DirectoryEntry] Added fullPath variable as part of condition +* [CB-7417](https://issues.apache.org/jira/browse/CB-7417) [File tests] added proper matcher to compare fullPath property +* [CB-7375](https://issues.apache.org/jira/browse/CB-7375) Partial revert to resolve WP8 failures +* Overwrite existing file on getFile when create is true +* [CB-7375](https://issues.apache.org/jira/browse/CB-7375) [CB-6148](https://issues.apache.org/jira/browse/CB-6148): Ensure that return values from copy and move operations reference the correct filesystem +* [CB-6724](https://issues.apache.org/jira/browse/CB-6724) changed style detail on documentation +* Added new js files to amazon-fireos platform. +* Adds Windows platform +* Fixes multiple mobilespec tests errors +* Removed test/tests.js module from main plugin.xml +* [CB-7094](https://issues.apache.org/jira/browse/CB-7094) renamed folder to tests + added nested plugin.xml +* added documentation for manual tests +* [CB-6923](https://issues.apache.org/jira/browse/CB-6923) Adding support to handle relative paths +* Style improvements on Manual tests +* [CB-7094](https://issues.apache.org/jira/browse/CB-7094) Ported File manual tests + +### 1.3.0 (Aug 06, 2014) +* **FFOS** Remove unsupported paths from requestAllPaths +* **FFOS** Support for resolve URI, request all paths and local app directory. +* [CB-4263](https://issues.apache.org/jira/browse/CB-4263) set ready state to done before onload +* [CB-7167](https://issues.apache.org/jira/browse/CB-7167) [BlackBerry10] copyTo - return wrapped entry rather than native +* [CB-7167](https://issues.apache.org/jira/browse/CB-7167) [BlackBerry10] Add directory support to getFileMetadata +* [CB-7167](https://issues.apache.org/jira/browse/CB-7167) [BlackBerry10] Fix tests detection of blob support (window.Blob is BlobConstructor object) +* [CB-7161](https://issues.apache.org/jira/browse/CB-7161) [BlackBerry10] Add file system directory paths +* [CB-7093](https://issues.apache.org/jira/browse/CB-7093) Create separate plugin.xml for new-style tests +* [CB-7057](https://issues.apache.org/jira/browse/CB-7057) Docs update: elaborate on what directories are for +* [CB-7093](https://issues.apache.org/jira/browse/CB-7093): Undo the effects of an old bad S&R command +* [CB-7093](https://issues.apache.org/jira/browse/CB-7093): Remove a bunch of unneeded log messages +* [CB-7093](https://issues.apache.org/jira/browse/CB-7093): Add JS module to plugin.xml file for auto-tests +* [CB-7093](https://issues.apache.org/jira/browse/CB-7093) Ported automated file tests +* **WINDOWS** remove extra function closure, not needed +* **WINDOWS** remove check for undefined fail(), it is defined by the proxy and always exists +* **WINDOWS** re-apply readAsBinaryString and readAsArrayBuffer +* **WINDOWS** Moved similar calls to be the same calls, aliased long namespaced functions +* [CB-6127](https://issues.apache.org/jira/browse/CB-6127) Updated translations for docs. +* [CB-6571](https://issues.apache.org/jira/browse/CB-6571) Fix getParentForLocalURL to work correctly with directories with trailing '/' (This closes #58) +* UTTypeCopyPreferredTagWithClass returns nil mimetype for css when there is no network +* updated spec links in docs ( en only ) +* [CB-6571](https://issues.apache.org/jira/browse/CB-6571) add trailing space it is missing in DirectoryEnty constructor. +* [CB-6980](https://issues.apache.org/jira/browse/CB-6980) Fixing filesystem:null property in Entry +* Add win8 support for readAsBinaryString and readAsArrayBuffer +* [FFOS] Update FileProxy.js +* [CB-6940](https://issues.apache.org/jira/browse/CB-6940): Fixing up commit from dzeims +* [CB-6940](https://issues.apache.org/jira/browse/CB-6940): Android: cleanup try/catch exception handling +* [CB-6940](https://issues.apache.org/jira/browse/CB-6940): `context.getExternal*` methods return null if sdcard isn't in mounted state, causing exceptions that prevent startup from reaching readystate +* Fix mis-handling of filesystem reference in Entry.moveTo ('this' used in closure). +* [CB-6902](https://issues.apache.org/jira/browse/CB-6902): Use File.lastModified rather than .lastModifiedDate +* [CB-6922](https://issues.apache.org/jira/browse/CB-6922): Remove unused getMetadata native code +* [CB-6922](https://issues.apache.org/jira/browse/CB-6922): Use getFileMetadata consistently to get metadata +* changed fullPath to self.rootDocsPath +* [CB-6890](https://issues.apache.org/jira/browse/CB-6890): Fix pluginManager access for 4.0.x branch + +### 1.2.1 +* [CB-6922](https://issues.apache.org/jira/browse/CB-6922) Fix inconsistent handling of lastModifiedDate and modificationTime +* [CB-285](https://issues.apache.org/jira/browse/CB-285): Document filesystem root properties + +### 1.2.0 (Jun 05, 2014) +* [CB-6127](https://issues.apache.org/jira/browse/CB-6127) Spanish and French Translations added. Github close #31 +* updated this reference to window +* Add missing semicolon (copy & paste error) +* Fix compiler warning about symbol in interface not matching implementation +* Fix sorting order in supported platforms +* ubuntu: increase quota value +* ubuntu: Change FS URL scheme to 'cdvfile' +* ubuntu: Return size with Entry.getMetadata() method +* [CB-6803](https://issues.apache.org/jira/browse/CB-6803) Add license +* Initial implementation for Firefox OS +* Small wording tweaks +* Fixed toURL() toInternalURL() information in the doku +* ios: Don't fail a write of zero-length payload. +* [CB-285](https://issues.apache.org/jira/browse/CB-285) Docs for cordova.file.\*Directory properties +* [CB-285](https://issues.apache.org/jira/browse/CB-285) Add cordova.file.\*Directory properties for iOS & Android +* [CB-3440](https://issues.apache.org/jira/browse/CB-3440) [BlackBerry10] Proxy based implementation +* Fix typo in docs "app-bundle" -> "bundle" +* [CB-6583](https://issues.apache.org/jira/browse/CB-6583) ios: Fix failing to create entry when space in parent path +* [CB-6571](https://issues.apache.org/jira/browse/CB-6571) android: Make DirectoryEntry.toURL() have a trailing / +* [CB-6491](https://issues.apache.org/jira/browse/CB-6491) add CONTRIBUTING.md +* [CB-6525](https://issues.apache.org/jira/browse/CB-6525) android, ios: Allow file: URLs in all APIs. Fixes FileTransfer.download not being called. +* fix the Windows 8 implementation of the getFile method +* Update File.js for typo: lastModifiedData --> lastModifiedDate (closes #38) +* Add error codes. +* [CB-5980](https://issues.apache.org/jira/browse/CB-5980) Updated version and RELEASENOTES.md for release 1.0.0 +* Add NOTICE file +* [CB-6114](https://issues.apache.org/jira/browse/CB-6114) Updated version and RELEASENOTES.md for release 1.0.1 +* [CB-5980](https://issues.apache.org/jira/browse/CB-5980) Updated version and RELEASENOTES.md for release 1.0.0 + +### 1.1.0 (Apr 17, 2014) +* [CB-4965](https://issues.apache.org/jira/browse/CB-4965): Remove tests from file plugin +* Android: Allow file:/ URLs +* [CB-6422](https://issues.apache.org/jira/browse/CB-6422): [windows8] use cordova/exec/proxy +* [CB-6249](https://issues.apache.org/jira/browse/CB-6249): [android] Opportunistically resolve content urls to file +* [CB-6394](https://issues.apache.org/jira/browse/CB-6394): [ios, android] Add extra filesystem roots +* [CB-6394](https://issues.apache.org/jira/browse/CB-6394): [ios, android] Fix file resolution for the device root case +* [CB-6394](https://issues.apache.org/jira/browse/CB-6394): [ios] Return ENCODING_ERR when fs name is not valid +* [CB-6393](https://issues.apache.org/jira/browse/CB-6393): Change behaviour of toURL and toNativeURL +* ios: Style: plugin initialization +* ios: Fix handling of file URLs with encoded spaces +* Always use Android's recommended temp file location for temporary file system +* [CB-6352](https://issues.apache.org/jira/browse/CB-6352): Allow FileSystem objects to be serialized to JSON +* [CB-5959](https://issues.apache.org/jira/browse/CB-5959): size is explicitly 0 if not set, file.spec.46&47 are testing the type of size +* [CB-6242](https://issues.apache.org/jira/browse/CB-6242): [BlackBerry10] Add deprecated version of resolveLocalFileSystemURI +* [CB-6242](https://issues.apache.org/jira/browse/CB-6242): [BlackBerry10] add file:/// prefix for toURI / toURL +* [CB-6242](https://issues.apache.org/jira/browse/CB-6242): [BlackBerry10] Polyfill window.requestAnimationFrame for OS < 10.2 +* [CB-6242](https://issues.apache.org/jira/browse/CB-6242): [BlackBerry10] Override window.resolveLocalFileSystemURL +* [CB-6212](https://issues.apache.org/jira/browse/CB-6212): [iOS] fix warnings compiled under arm64 64-bit +* ios: Don't cache responses from CDVFile's URLProtocol +* [CB-6199](https://issues.apache.org/jira/browse/CB-6199): [iOS] Fix toNativeURL() not escaping characters properly +* [CB-6148](https://issues.apache.org/jira/browse/CB-6148): Fix cross-filesystem copy and move +* fixed setMetadata() to use the formatted fullPath +* corrected typo which leads to a "comma expression" +* [CB-4952](https://issues.apache.org/jira/browse/CB-4952): ios: Resolve symlinks in file:// URLs +* Add docs about the extraFileSystems preference +* [CB-6460](https://issues.apache.org/jira/browse/CB-6460): Update license headers + +### 1.0.1 (Feb 28, 2014) +* [CB-6116](https://issues.apache.org/jira/browse/CB-6116) Fix error where resolveLocalFileSystemURL would fail +* [CB-6106](https://issues.apache.org/jira/browse/CB-6106) Add support for nativeURL attribute on Entry objects +* [CB-6110](https://issues.apache.org/jira/browse/CB-6110) iOS: Fix typo in filesystemPathForURL: method +* Android: Use most specific FS match when resolving file: URIs +* iOS: Update fileSystemURLforLocalPath: to return the most match url. +* Allow third-party plugin registration, and the total count of fs type is not limited to just 4. +* [CB-6097](https://issues.apache.org/jira/browse/CB-6097) Added missing files for amazon-fireos platform. Added onLoad flag to true. +* [CB-6087](https://issues.apache.org/jira/browse/CB-6087) Android, iOS: Load file plugin on startup +* [CB-6013](https://issues.apache.org/jira/browse/CB-6013) BlackBerry10: wrap webkit prefixed called in requestAnimationFrame +* Update plugin writers' documentation +* [CB-6080](https://issues.apache.org/jira/browse/CB-6080) Fix file copy when src and dst are on different local file systems +* [CB-6057](https://issues.apache.org/jira/browse/CB-6057) Add methods for plugins to convert between URLs and paths +* [CB-6050](https://issues.apache.org/jira/browse/CB-6050) Public method for returning a FileEntry from a device file path +* [CB-2432](https://issues.apache.org/jira/browse/CB-2432) [CB-3185](https://issues.apache.org/jira/browse/CB-3185), [CB-5975](https://issues.apache.org/jira/browse/CB-5975): Fix Android handling of content:// URLs +* [CB-6022](https://issues.apache.org/jira/browse/CB-6022) Add upgrade notes to doc +* [CB-5233](https://issues.apache.org/jira/browse/CB-5233) Make asset-library urls work properly on iOS +* [CB-6012](https://issues.apache.org/jira/browse/CB-6012) Preserve query strings on cdvfile:// URLs where necessary +* [CB-6010](https://issues.apache.org/jira/browse/CB-6010) Test properly for presence of URLforFilesystemPath method +* [CB-5959](https://issues.apache.org/jira/browse/CB-5959) Entry.getMetadata should return size attribute + +### 1.0.0 (Feb 05, 2014) +* [CB-5974](https://issues.apache.org/jira/browse/CB-5974): Use safe 'Compatibilty' mode by default +* [CB-5915](https://issues.apache.org/jira/browse/CB-5915): [CB-5916](https://issues.apache.org/jira/browse/CB-5916): Reorganize preference code to make defaults possible +* [CB-5974](https://issues.apache.org/jira/browse/CB-5974): Android: Don't allow File operations to continue when not configured +* [CB-5960](https://issues.apache.org/jira/browse/CB-5960): ios: android: Properly handle parent references in getFile/getDirectory +* [ubuntu] adopt to recent changes +* Add default FS root to new FS objects +* [CB-5899](https://issues.apache.org/jira/browse/CB-5899): Make DirectoryReader.readEntries return properly formatted Entry objects +* Add constuctor params to FileUploadResult related to [CB-2421](https://issues.apache.org/jira/browse/CB-2421) +* Fill out filesystem attribute of entities returned from resolveLocalFileSystemURL +* [CB-5916](https://issues.apache.org/jira/browse/CB-5916): Create documents directories if they don't exist +* [CB-5915](https://issues.apache.org/jira/browse/CB-5915): Create documents directories if they don't exist +* [CB-5916](https://issues.apache.org/jira/browse/CB-5916): Android: Fix unfortunate NPE in config check +* [CB-5916](https://issues.apache.org/jira/browse/CB-5916): Android: Add "/files/" to persistent files path +* [CB-5915](https://issues.apache.org/jira/browse/CB-5915): ios: Update config preference (and docs) to match issue +* [CB-5916](https://issues.apache.org/jira/browse/CB-5916): Android: Add config preference for Android persistent storage location +* iOS: Add config preference for iOS persistent storage location +* iOS: Android: Allow third-party plugin registration +* Android: Expose filePlugin getter so that other plugins can register filesystems +* Fix typos in deprecation message +* Add backwards-compatibility shim for file-transfer +* Android: Allow third-party plugin registration +* [CB-5810](https://issues.apache.org/jira/browse/CB-5810) [BlackBerry10] resolve local:/// paths (application assets) +* [CB-5774](https://issues.apache.org/jira/browse/CB-5774): create DirectoryEntry instead of FileEntry +* Initial fix for [CB-5747](https://issues.apache.org/jira/browse/CB-5747) +* Change default FS URL scheme to "cdvfile" +* Android: Properly format content urls +* Android, iOS: Replace "filesystem" protocol string with constant +* Android: Allow absolute paths on Entry.getFile / Entry.getDirectory +* Android: Make clear that getFile takes a path, not just a filename +* [CB-5008](https://issues.apache.org/jira/browse/CB-5008): Rename resolveLocalFileSystemURI to resolveLocalFileSystemURL; deprecate original +* Remove old file reference from plugin.xml +* Android: Refactor File API +* [CB-4899](https://issues.apache.org/jira/browse/CB-4899) [BlackBerry10] Fix resolve directories +* [CB-5602](https://issues.apache.org/jira/browse/CB-5602) Windows8. Fix File Api mobile spec tests +* Android: Better support for content urls and cross-filesystem copy/move ops +* [CB-5699](https://issues.apache.org/jira/browse/CB-5699) [BlackBerry10] Update resolveLocalFileSystemURI implementation +* [CB-5658](https://issues.apache.org/jira/browse/CB-5658) Update license comment formatting of doc/index.md +* [CB-5658](https://issues.apache.org/jira/browse/CB-5658) Add doc.index.md for File plugin. +* [CB-5658](https://issues.apache.org/jira/browse/CB-5658) Delete stale snapshot of plugin docs +* [CB-5403](https://issues.apache.org/jira/browse/CB-5403): Backwards-compatibility with file:// urls where possible +* [CB-5407](https://issues.apache.org/jira/browse/CB-5407): Fixes for ContentFilesystem +* Android: Add method for testing backwards-compatibility of filetransfer plugin +* iOS: Add method for testing backwards-compatiblity of filetransfer plugin +* Android: Updates to allow FileTransfer to continue to work +* Android: Clean up unclosed file objects +* [CB-5407](https://issues.apache.org/jira/browse/CB-5407): Cleanup +* [CB-5407](https://issues.apache.org/jira/browse/CB-5407): Add new Android source files to plugin.xml +* [CB-5407](https://issues.apache.org/jira/browse/CB-5407): Move read, write and truncate methods into modules +* [CB-5407](https://issues.apache.org/jira/browse/CB-5407): Move copy/move methods into FS modules +* [CB-5407](https://issues.apache.org/jira/browse/CB-5407): Move getParent into FS modules +* [CB-5407](https://issues.apache.org/jira/browse/CB-5407): Move getmetadata methods into FS modules +* [CB-5407](https://issues.apache.org/jira/browse/CB-5407): Move readdir methods into FS modules +* [CB-5407](https://issues.apache.org/jira/browse/CB-5407): Move remove methods into FS modules +* [CB-5407](https://issues.apache.org/jira/browse/CB-5407): Move getFile into FS modules +* [CB-5407](https://issues.apache.org/jira/browse/CB-5407): Start refactoring android code: Modular filesystems, rfs, rlfsurl +* [CB-5407](https://issues.apache.org/jira/browse/CB-5407): Update android JS to use FS urls +* [CB-5405](https://issues.apache.org/jira/browse/CB-5405): Use URL formatting for Entry.toURL +* [CB-5532](https://issues.apache.org/jira/browse/CB-5532) Fix +* Log file path for File exceptions. +* Partial fix for iOS File compatibility with previous fileTransfer plugin +* [CB-5532](https://issues.apache.org/jira/browse/CB-5532) WP8. Add binary data support to FileWriter +* [CB-5531](https://issues.apache.org/jira/browse/CB-5531) WP8. File Api readAsText incorrectly handles position args +* Added ubuntu platform support +* Added amazon-fireos platform support +* [CB-5118](https://issues.apache.org/jira/browse/CB-5118) [BlackBerry10] Add check for undefined error handler +* [CB-5406](https://issues.apache.org/jira/browse/CB-5406): Extend public API for dependent plugins +* [CB-5403](https://issues.apache.org/jira/browse/CB-5403): Bump File plugin major version +* [CB-5406](https://issues.apache.org/jira/browse/CB-5406): Split iOS file plugin into modules +* [CB-5406](https://issues.apache.org/jira/browse/CB-5406): Factor out filesystem providers in iOS +* [CB-5408](https://issues.apache.org/jira/browse/CB-5408): Add handler for filesystem:// urls +* [CB-5406](https://issues.apache.org/jira/browse/CB-5406): Update iOS native code to use filesystem URLs internally +* [CB-5405](https://issues.apache.org/jira/browse/CB-5405): Update JS code to use URLs exclusively +* [CB-4816](https://issues.apache.org/jira/browse/CB-4816) Fix file creation outside sandbox for BB10 + +### 0.2.5 (Oct 28, 2013) +* [CB-5129](https://issues.apache.org/jira/browse/CB-5129): Add a consistent filesystem attribute to FileEntry and DirectoryEntry objects +* [CB-5128](https://issues.apache.org/jira/browse/CB-5128): added repo + issue tag to plugin.xml for file plugin +* [CB-5015](https://issues.apache.org/jira/browse/CB-5015) [BlackBerry10] Add missing dependency for File.slice +* [CB-5010](https://issues.apache.org/jira/browse/CB-5010) Incremented plugin version on dev branch. + +### 0.2.4 (Oct 9, 2013) +* [CB-5020](https://issues.apache.org/jira/browse/CB-5020) - File plugin should execute on a separate thread +* [CB-4915](https://issues.apache.org/jira/browse/CB-4915) Incremented plugin version on dev branch. +* [CB-4504](https://issues.apache.org/jira/browse/CB-4504): Updating FileUtils.java to compensate for Java porting failures in the Android SDK. This fails because Java knows nothing about android_asset not being an actual filesystem + +### 0.2.3 (Sept 25, 2013) +* [CB-4889](https://issues.apache.org/jira/browse/CB-4889) bumping&resetting version +* [CB-4903](https://issues.apache.org/jira/browse/CB-4903) File Plugin not loading Windows8 +* [CB-4903](https://issues.apache.org/jira/browse/CB-4903) File Plugin not loading Windows8 +* [CB-4889](https://issues.apache.org/jira/browse/CB-4889) renaming references +* [CB-4889](https://issues.apache.org/jira/browse/CB-4889) renaming org.apache.cordova.core.file to org.apache.cordova.file +* Rename CHANGELOG.md -> RELEASENOTES.md +* [CB-4771](https://issues.apache.org/jira/browse/CB-4771) Expose TEMPORARY and PERSISTENT constants on window. +* Fix compiler/lint warnings +* [CB-4764](https://issues.apache.org/jira/browse/CB-4764) Move DirectoryManager.java into file plugin +* [CB-4763](https://issues.apache.org/jira/browse/CB-4763) Copy FileHelper.java into the plugin. +* [CB-2901](https://issues.apache.org/jira/browse/CB-2901) [BlackBerry10] Automatically unsandbox filesystem if path is not in app sandbox +* [CB-4752](https://issues.apache.org/jira/browse/CB-4752) Incremented plugin version on dev branch. + +### 0.2.1 (Sept 5, 2013) +* [CB-4656](https://issues.apache.org/jira/browse/CB-4656) Don't add newlines in data urls within readAsDataUrl. +* [CB-4514](https://issues.apache.org/jira/browse/CB-4514) Making DirectoryCopy Recursive +* [iOS] Simplify the code in resolveLocalFileSystemURI diff --git a/plugins/cordova-plugin-file/doc/de/README.md b/plugins/cordova-plugin-file/doc/de/README.md new file mode 100644 index 0000000..242a2f7 --- /dev/null +++ b/plugins/cordova-plugin-file/doc/de/README.md @@ -0,0 +1,335 @@ + + +# cordova-plugin-file + +[![Build Status](https://travis-ci.org/apache/cordova-plugin-file.svg)](https://travis-ci.org/apache/cordova-plugin-file) + +Dieses Plugin implementiert eine File-API, die Lese-/Schreibzugriff Zugriff auf Dateien, die auf dem Gerät befinden. + +Dieses Plugin basiert auf mehrere Angaben, einschließlich: die HTML5-File-API + +Die (heute nicht mehr existierenden) Verzeichnisse und System neuesten Erweiterungen: , obwohl die meisten von den Plugin-Code wurde geschrieben, als eine frühere Spec aktuell waren: + +Es implementiert auch die FileWriter Spec: + +Verwendung finden Sie in HTML5 Rocks ausgezeichnete [Dateisystem Artikel.](http://www.html5rocks.com/en/tutorials/file/filesystem/) + +Finden Sie einen Überblick über andere Speicheroptionen Cordovas [Speicher-Führer](http://cordova.apache.org/docs/en/edge/cordova_storage_storage.md.html). + +Dieses Plugin wird global `cordova.file`-Objekt definiert. + +Obwohl im globalen Gültigkeitsbereich, steht es nicht bis nach dem `deviceready`-Ereignis. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(cordova.file); + } + + +## Installation + + cordova plugin add cordova-plugin-file + + +## Unterstützte Plattformen + + * Amazon Fire OS + * Android + * BlackBerry 10 + * Firefox OS + * iOS + * Windows Phone 7 und 8 * + * Windows 8 * + * Windows* + * Browser + +\* *These platforms do not support `FileReader.readAsArrayBuffer` nor `FileWriter.write(blob)`.* + +## Wo Dateien gespeichert + +Stand: V1 werden URLs auf wichtige Datei-System-Verzeichnisse zur Verfügung gestellt. Jede URL in der Form *file:///path/to/spot/* ist, und ein `DirectoryEntry` mit `window.resolveLocalFileSystemURL()` konvertiert werden können. + + * `cordova.file.applicationDirectory`-Die schreibgeschützten Verzeichnis, in dem die Anwendung installiert ist. (*iOS*, *Android*, *BlackBerry 10*) + + * `cordova.file.applicationStorageDirectory`-Root-Verzeichnis der Anwendungs-Sandbox; auf iOS ist schreibgeschützt (aber bestimmte Unterverzeichnisse [wie `/Documents` ] sind Lese-und Schreibzugriff). Alle enthaltene Daten ist für die app privat. ( *iOS*, *Android*, *BlackBerry 10*) + + * `cordova.file.dataDirectory`-Beständige und private Datenspeicherung innerhalb der Anwendungs-Sandbox, die mit internen Speicher (auf Android, externen Speicher verwenden, verwenden Sie `.externalDataDirectory` ). Auf iOS, ist dieses Verzeichnis nicht mit iCloud synchronisiert (verwenden Sie `.syncedDataDirectory` ). (*iOS*, *Android*, *BlackBerry 10*) + + * `cordova.file.cacheDirectory`-Verzeichnis der zwischengespeicherten Daten-Dateien oder Dateien, die Ihre app einfach neu erstellen können. Das Betriebssystem kann diese Dateien löschen, wenn das Gerät auf Speicher knapp wird, dennoch sollten die apps vom Betriebssystem zum Löschen von Dateien hier nicht verlassen. (*iOS*, *Android*, *BlackBerry 10*) + + * `cordova.file.externalApplicationStorageDirectory`-Anwendungsraum auf externen Speicher. (*Android*) + + * `cordova.file.externalDataDirectory`-Wo, app-spezifische Datendateien auf externen Speicher setzen. (*Android*) + + * `cordova.file.externalCacheDirectory`-Anwendungscache auf externen Speicher. (*Android*) + + * `cordova.file.externalRootDirectory`-Externer Speicher (SD-Karte) Stamm. (*Android*, *BlackBerry 10*) + + * `cordova.file.tempDirectory`-Temp-Verzeichnis, dem das OS auf deaktivieren können wird. Verlassen Sie sich nicht auf das Betriebssystem, um dieses Verzeichnis zu löschen; Ihre Anwendung sollte immer Dateien gegebenenfalls entfernen. (*iOS*) + + * `cordova.file.syncedDataDirectory`-Hält app-spezifische Dateien, die (z. B. auf iCloud) synchronisiert werden sollten. (*iOS*) + + * `cordova.file.documentsDirectory`-Dateien für die app, aber privat sind sinnvoll, andere Anwendungen (z.B. Office-Dateien). (*iOS*) + + * `cordova.file.sharedDirectory`-Dateien für alle Anwendungen (*BlackBerry 10* weltweit verfügbar) + +## Dateisystemlayouts + +Obwohl technisch ein Implementierungsdetail, kann es sehr hilfreich zu wissen, wie die `cordova.file.*`-Eigenschaften physikalische Pfade auf einem echten Gerät zugeordnet sein. + +### iOS-Datei-System-Layout + +| Gerätepfad | `Cordova.file.*` | `iosExtraFileSystems` | R/w? | persistent? | OS löscht | Sync | Private | +|:---------------------------------------------- |:--------------------------- |:--------------------- |:----:|:-----------:|:------------:|:----:|:-------:| +| `/ Var/mobile/Applications/< UUID > /` | applicationStorageDirectory | - | r | N/A | N/A | N/A | Ja | +|    `appname.app/` | applicationDirectory | Bundle | r | N/A | N/A | N/A | Ja | +|       `www/` | - | - | r | N/A | N/A | N/A | Ja | +|    `Documents/` | documentsDirectory | Dokumente | R/w | Ja | Nein | Ja | Ja | +|       `NoCloud/` | - | Dokumente-nosync | R/w | Ja | Nein | Nein | Ja | +|    `Library` | - | Bibliothek | R/w | Ja | Nein | Ja? | Ja | +|       `NoCloud/` | dataDirectory | Bibliothek-nosync | R/w | Ja | Nein | Nein | Ja | +|       `Cloud/` | syncedDataDirectory | - | R/w | Ja | Nein | Ja | Ja | +|       `Caches/` | cacheDirectory | Cache | R/w | Ja * | Ja**\* | Nein | Ja | +|    `tmp/` | tempDirectory | - | R/w | Nein** | Ja**\* | Nein | Ja | + +\ * Dateien über app-Neustarts und Upgrades beibehalten, aber dieses Verzeichnis kann gelöscht werden, wenn das OS begehrt. Ihre Anwendung sollte in der Lage, alle Inhalte neu zu erstellen, die gelöscht werden können. + +** -Dateien kann über app-Neustarts beizubehalten, aber verlasse dich nicht auf dieses Verhalten. Dateien sind nicht unbedingt Aktuelles beibehalten. Ihre Anwendung sollte Dateien aus diesem Verzeichnis entfernen, wenn es gilt, diese Dateien werden entfernt, da das OS nicht wann (oder auch wenn) garantiert. + +**\ * The OS kann den Inhalt dieses Verzeichnisses löschen, wann immer es sich anfühlt, ist es erforderlich, aber verlassen Sie sich nicht dazu. Sie sollten dieses Verzeichnis entsprechend Ihrer Anwendung deaktivieren. + +### Android File System-Layout + +| Gerätepfad | `Cordova.file.*` | `AndroidExtraFileSystems` | R/w? | persistent? | OS löscht | Private | +|:------------------------------------------------ |:----------------------------------- |:------------------------- |:----:|:-----------:|:----------:|:-------:| +| `file:///android_asset/` | applicationDirectory | | r | N/A | N/A | Ja | +| `/ Data/Data/< app-Id > /` | applicationStorageDirectory | - | R/w | N/A | N/A | Ja | +|    `cache` | cacheDirectory | Cache | R/w | Ja | Ja\* | Ja | +|    `files` | dataDirectory | Dateien | R/w | Ja | Nein | Ja | +|       `Documents` | | Dokumente | R/w | Ja | Nein | Ja | +| `< Sdcard > /` | externalRootDirectory | sdcard | R/w | Ja | Nein | Nein | +|    `Android/data//` | externalApplicationStorageDirectory | - | R/w | Ja | Nein | Nein | +|       `cache` | externalCacheDirectry | Cache-extern | R/w | Ja | Nein** | Nein | +|       `files` | externalDataDirectory | Dateien-extern | R/w | Ja | Nein | Nein | + +\ * OS kann regelmäßig dieses Verzeichnis zu löschen, aber verlasse dich nicht auf dieses Verhalten. Deaktivieren Sie den Inhalt dieses Verzeichnisses für Ihre Anwendung geeigneten. Ein Benutzer den Cache manuell löschen sollte, werden die Inhalte dieses Verzeichnisses entfernt. + +** Der OS nicht klar dieses Verzeichnis automatisch; Sie sind verantwortlich für die Inhalte selbst verwalten. Der Benutzer den Cache manuell löschen sollte, werden der Inhalt des Verzeichnisses entfernt. + +**Hinweis**: Wenn externe Speichergeräte nicht bereitgestellt werden kann, sind die `cordova.file.external*` Eigenschaften `null`. + +### BlackBerry 10-File-System-Layout + +| Gerätepfad | `Cordova.file.*` | R/w? | persistent? | OS löscht | Private | +|:----------------------------------------------------------- |:--------------------------- |:----:|:-----------:|:---------:|:-------:| +| `file:///Accounts/1000/APPDATA/ < app Id > /` | applicationStorageDirectory | r | N/A | N/A | Ja | +|    `app/native` | applicationDirectory | r | N/A | N/A | Ja | +|    `data/webviews/webfs/temporary/local__0` | cacheDirectory | R/w | Nein | Ja | Ja | +|    `data/webviews/webfs/persistent/local__0` | dataDirectory | R/w | Ja | Nein | Ja | +| `file:///Accounts/1000/Removable/sdcard` | externalRemovableDirectory | R/w | Ja | Nein | Nein | +| `file:///Accounts/1000/Shared` | sharedDirectory | R/w | Ja | Nein | Nein | + +*Hinweis*: Wenn die Anwendung bereitgestellt wird, um Perimeter zu arbeiten, alle Pfade sind relativ /accounts/1000-enterprise. + +## Android Eigenarten + +### Android permanenten Speicherort + +Es gibt mehrere gültige Speicherorte, persistente Dateien auf einem Android-Gerät zu speichern. Finden Sie auf [dieser Seite](http://developer.android.com/guide/topics/data/data-storage.html) eine ausführliche Diskussion über die verschiedenen Möglichkeiten. + +Frühere Versionen des Plugins wählen würde, den Speicherort der temporären und permanenten Dateien beim Start, basierend auf, ob das Gerät behauptete, dass die SD-Karte (oder gleichwertige Speicherpartition) bereitgestellt wurde. Wenn die SD-Karte eingelegt wurde, oder wenn eine große interne Speicherpartition verfügbar war (wie auf Nexus-Geräten) und dann in die Wurzel dieses Raumes, die persistenten Dateien gespeichert werden. Dies bedeutete, dass alle Cordova apps aller verfügbaren Dateien auf der Karte sehen konnte. + +Wenn die SD-Karte nicht verfügbar war, dann Vorgängerversionen Daten unter speichern würde `/data/data/`, die isoliert Anwendungen voneinander, aber möglicherweise noch Ursache Daten zwischen Benutzern freigegeben werden. + +Es ist jetzt möglich, ob Sie Dateien der internen Datei-Speicherort oder unter Verwendung der bisherigen Logik, mit einer Präferenz in der Anwendung-`config.xml`-Datei speichern möchten. Hierzu fügen Sie eine dieser zwei Zeilen zu `"config.xml"`: + + + + + + +Ohne diese Zeile wird das Datei Plugin `Compatibility` als Standard verwenden. Wenn ein Präferenz-Tag vorhanden ist, und nicht einen der folgenden Werte, wird die Anwendung nicht gestartet. + +Wenn Ihre Anwendung für Benutzer zuvor versandt wird, mithilfe eines älteren (Pre-1.0) Version dieses Plugins und gespeicherte Dateien im permanenten Dateisystem hat, dann sollten Sie die Einstellung zur `Compatibility` einstellen. Wechseln die Location auf "Internal" würde bedeuten, dass Benutzer, die aktualisieren Sie ihre Anwendung, möglicherweise nicht auf ihre zuvor gespeicherte Dateien, abhängig von ihrem Gerät zugreifen. + +Wenn Ihre Anwendung neu ist, oder nie zuvor Dateien im Dateisystem persistent gespeichert hat, wird die `Internal` Einstellung in der Regel empfohlen. + +### Langsame rekursive Operationen für /android_asset + +Auflisten von Verzeichnissen Vermögenswert ist wirklich langsam auf Android. Sie können beschleunigen, es oben aber durch `src/android/build-extras.gradle` in das Stammverzeichnis von Ihrem android Projekt hinzufügen (erfordert auch cordova-android@4.0.0 oder größer). + +## iOS Macken + + * `cordova.file.applicationStorageDirectory`ist schreibgeschützt; zum Speichern von Dateien im Stammverzeichnis der Versuch schlägt fehl. Verwenden Sie eine der anderen `cordova.file.*` für iOS definierten Eigenschaften (nur `applicationDirectory` und `applicationStorageDirectory` sind schreibgeschützt). + * `FileReader.readAsText(blob, encoding)` + * Die `encoding` Parameter wird nicht unterstützt und UTF-8-Kodierung ist immer wirksam. + +### iOS permanenten Speicherort + +Es gibt zwei gültige Speicherorte persistente Dateien auf ein iOS-Gerät speichern: das Dokumenten-Verzeichnis und das Verzeichnis Library. Frühere Versionen des Plugins gespeichert immer nur persistente Dateien im Verzeichnis Dokumente. Dies hatte den Nebeneffekt einer Anwendung Dateien in iTunes, die oft unbeabsichtigte, speziell für Anwendungen, die viele kleine Dateien behandeln war, sichtbar zu machen, anstatt komplette Dokumente für den Export, die den beabsichtigten Zweck des Verzeichnisses ist zu produzieren. + +Es ist jetzt möglich, ob Sie Dateien in Dokumente oder Verzeichnis Library mit einer Präferenz in der Anwendung-`config.xml`-Datei speichern möchten. Hierzu fügen Sie eine dieser zwei Zeilen zu `"config.xml"`: + + + + + + +Ohne diese Zeile wird das Datei Plugin `Compatibility` als Standard verwenden. Wenn ein Präferenz-Tag vorhanden ist, und nicht einen der folgenden Werte, wird die Anwendung nicht gestartet. + +Wenn Ihre Anwendung für Benutzer zuvor versandt wird, mithilfe eines älteren (Pre-1.0) Version dieses Plugins und gespeicherte Dateien im permanenten Dateisystem hat, dann sollten Sie die Einstellung zur `Compatibility` einstellen. Standort zur `Library` wechseln würde bedeuten, dass Benutzer, die ihre Anwendung aktualisieren nicht in der Lage wäre, ihre zuvor gespeicherte Dateien zugreifen. + +Wenn die Anwendung neu, oder nie zuvor Dateien im Dateisystem persistent gespeichert hat, wird die Einstellung der `Library` allgemein empfohlen. + +## Firefox OS Macken + +Der Datei-System-API wird von Firefox-OS nicht nativ unterstützt und wird als ein Shim auf IndexedDB implementiert. + + * Schlägt nicht fehl, wenn Sie nicht leere Verzeichnisse entfernen + * Metadaten wird für Verzeichnisse nicht unterstützt. + * Methoden `copyTo` und `moveTo` unterstützen keine Verzeichnisse + +Die folgenden Datenpfade werden unterstützt: * `applicationDirectory` - `xhr` verwendet, um lokale Dateien erhalten, die mit der app verpackt sind. *`dataDirectory` - für persistente app-spezifische Daten-Dateien. *`cacheDirectory` - Cache-Dateien, die app startet überleben sollte (Apps sollten nicht vom Betriebssystem zum Löschen von Dateien hier verlassen). + +## Browser-Eigenheiten + +### Gemeinsamen Macken und Bemerkungen + + * Jeder Browser verwendet ein eigene Sandbox Dateisystem. IE und Firefox verwenden IndexedDB als Basis. Alle Browser verwenden Schrägstrich als Verzeichnistrennzeichen in einem Pfad. + * Directory-Einträge müssen nacheinander erstellt werden. Z. B. der Aufruf `fs.root.getDirectory ("dir1/Ordner2 ', {create:true}, SuccessCallback, ErrorCallback)` schlägt fehl, wenn dir1 nicht existierte. + * Das Plugin fordert Benutzer die Berechtigung zum permanenten Speicher beim ersten Start Anwendung verwenden. + * Plugin unterstützt `Cdvfile://localhost` (lokale Ressourcen) nur. D.h. externe Ressourcen nicht über `Cdvfile` unterstützt. + * Das Plugin folgt nicht ["File System API 8.3 Naming Einschränkungen"](http://www.w3.org/TR/2011/WD-file-system-api-20110419/#naming-restrictions). + * BLOB und Datei "`close`-Funktion wird nicht unterstützt. + * `FileSaver` und `BlobBuilder` werden von diesem Plugin nicht unterstützt und müssen nicht geboren. + * Das Plugin unterstützt keine `RequestAllFileSystems`. Diese Funktion fehlt auch in den Spezifikationen. + * Einträge im Verzeichnis werden nicht entfernt werden, wenn Sie verwenden `create: true` Flag für vorhandenes Verzeichnis. + * Über Konstruktor erstellte Dateien werden nicht unterstützt. Sie sollten stattdessen die entry.file-Methode verwenden. + * Jeder Browser verwendet eine eigene Form für Blob-URL-Verweise. + * `readAsDataURL`-Funktion wird unterstützt, aber die Mediatype in Chrom hängt von der Eintrag Namenerweiterung, Mediatype im IE immer leer ist (das ist dasselbe wie `Text-Plain` gemäß der Spezifikation), Mediatype in Firefox ist immer `Application/Octet-Stream`. Beispielsweise, wenn der Inhalt `Abcdefg` gibt dann Firefox `Daten: Anwendung / Octet-Stream; base64, YWJjZGVmZw ==`, IE gibt `Daten:; base64, YWJjZGVmZw ==`, Chrom gibt `Daten: < Mediatype je nach Erweiterung des Eintragsnamens >; base64, YWJjZGVmZw ==`. + * `ToInternalURL` gibt den Pfad zurück, in der Form `file:///persistent/path/to/entry` (Firefox, IE). Chrom gibt den Pfad zurück, in der Form `cdvfile://localhost/persistent/file`. + +### Chrom-Macken + + * Chrom-Dateisystem ist nicht sofort nach Gerät bereit. Als Workaround können Sie `FilePluginIsReady`-Ereignis abonnieren. Beispiel: + +```javascript +window.addEventListener('filePluginIsReady', function(){ console.log('File plugin is ready');}, false); +``` + +`Window.isFilePluginReadyRaised`-Funktion können Sie überprüfen, ob Ereignis bereits ausgelöst wurde. -window.requestFileSystem temporär und PERSISTENTE Dateisystem-Quoten sind nicht begrenzt, in Chrom. -Um die dauerhafte Speicherung in Chrom zu erhöhen benötigen Sie `window.initPersistentFileSystem`-Methode aufrufen. Permanenter Speicherkontingent beträgt 5 MB standardmäßig. -Chrome erforderlich `--erlauben-Datei-Zugriff-aus-Files` Argument an den Support API via `file:///` Protokoll führen. -`Datei`-Objekt wird nicht geändert werden, wenn Sie Flag verwenden `{create:true}` als einen vorhandenen `Eintrag` zu erhalten. -Veranstaltungen `cancelable`-Eigenschaft festgelegt ist in Chrom wahr. Dies widerspricht der [Spezifikation](http://dev.w3.org/2009/dap/file-system/file-writer.html). -`toURL`-Funktion in Chrome zurück `Dateisystem:`-Pfad je nach Anwendungshost vorangestellt. Z. B. `filesystem:file:///persistent/somefile.txt`, `Filesystem:http://localhost:8080/persistent/somefile.txt`. -`toURL` Funktionsergebnis enthält keine nachgestellten Schrägstrich bei Verzeichniseintrag. Chrom löst Verzeichnisse mit Schrägstrich-gezogene Urls aber korrekt. -`ResolveLocalFileSystemURL`-Methode erfordert die eingehenden `Url` `Dateisystem` Präfix haben. Beispielsweise sollte die `Url`-Parameter für `ResolveLocalFileSystemURL` in der Form `filesystem:file:///persistent/somefile.txt` im Gegensatz zu der Form `file:///persistent/somefile.txt` in Android. -Veraltete `ToNativeURL`-Funktion wird nicht unterstützt und muss keinen Stub. -`SetMetadata`-Funktion ist nicht in den Spezifikationen angegeben und nicht unterstützt. -INVALID_MODIFICATION_ERR (Code: 9) wird ausgelöst, statt SYNTAX_ERR(code: 8) auf anfordern des Dateisystems nicht existent. -INVALID_MODIFICATION_ERR (Code: 9) wird ausgelöst, anstatt PATH_EXISTS_ERR(code: 12) zu versuchen, die ausschließlich eine Datei oder ein Verzeichnis zu erstellen, die bereits vorhanden ist. -INVALID_MODIFICATION_ERR (Code: 9) wird ausgelöst, anstatt NO_MODIFICATION_ALLOWED_ERR(code: 6) zu versuchen, rufen Sie RemoveRecursively auf das Root-Dateisystem. -INVALID_MODIFICATION_ERR (Code: 9) wird ausgelöst, anstatt NOT_FOUND_ERR(code: 1) zu versuchen, MoveTo-Verzeichnis, das nicht vorhanden ist. + +### Auf der Grundlage von IndexedDB Impl Macken (Firefox und IE) + + * `.` und `.` werden nicht unterstützt. + * IE unterstützt keine `file:///`-Modus; nur der Modus für gehostete ist unterstützten (Http://localhost:xxxx). + * Firefox Dateisystem Größe ist nicht begrenzt, aber jede 50MB-Erweiterung wird eine Benutzer die Berechtigung anzufordern. IE10 können bis zu 10mb kombinierte AppCache und IndexedDB in Implementierung des Dateisystems verwendet, ohne Aufforderung, sobald Sie dieses Niveau, werden, das Sie aufgefordert werden schlagen, wenn Sie es bis Max 250 mb pro Standort erhöht werden sollen. `Size`-Parameter für `RequestFileSystem` Funktion wirkt also nicht Dateisystem in Firefox und IE. + * `ReadAsBinaryString` Funktion heißt es nicht in die Angaben und in IE nicht unterstützt und muss keinen Stub. + * `file.Type` ist immer null. + * Sie sollten nicht erstellen Eintrag mit DirectoryEntry Instanz Rückrufergebnis, die gelöscht wurde. Andernfalls erhalten Sie einen "hängende Eintrag". + * Bevor Sie eine Datei lesen können, die gerade geschrieben wurde, müssen Sie eine neue Instanz dieser Datei erhalten. + * `SetMetadata`-Funktion, die nicht in den Specs genannt unterstützt Feldänderung nur `ModificationTime`. + * `CopyTo` und `MoveTo`-Funktionen unterstützen keine Verzeichnisse. + * Verzeichnisse-Metadaten werden nicht unterstützt. + * Beide Entry.remove und directoryEntry.removeRecursively nicht scheitern, wenn nicht leere Verzeichnisse entfernen - Verzeichnisse entfernt werden stattdessen zusammen mit Inhalt gereinigt. + * `abort` und `truncate`-Funktionen werden nicht unterstützt. + * Progress-Ereignisse werden nicht ausgelöst. Beispielsweise wird dieser Handler nicht ausgeführt werden: + +```javascript +writer.onprogress = function() { /*commands*/ }; +``` + +## Upgrade Notes + +In v1.0.0 dieses Plugins haben die `FileEntry` und `DirectoryEntry` Strukturen geändert, um mehr im Einklang mit der veröffentlichten Spezifikation sein. + +Vorgängerversionen (Pre-1.0.0) des Plugins den Gerät-Absolute-Dateispeicherort in der Eigenschaft `fullPath` `Entry` Objekte gespeichert. Diese Pfade würde in der Regel aussehen + + /var/mobile/Applications//Documents/path/to/file (iOS) + /storage/emulated/0/path/to/file (Android) + + +Diese Pfade wurden auch von der `toURL()`-Methode der `Entry` Objekte zurückgegeben. + +Mit v1.0.0 ist das `fullPath`-Attribut den Pfad zu der Datei, *relativ zum Stammverzeichnis des Dateisystems HTML*. Also, würde die oben genannten Wege jetzt beide durch ein `FileEntry`-Objekt mit einem `fullPath` von dargestellt werden + + /path/to/file + + +Wenn Ihre Anwendung mit absoluter Gerätepfade arbeitet und Sie zuvor diese Pfade durch die Eigenschaft `fullPath` `Entry` Objekte abgerufen, sollten dann Sie den Code, um stattdessen `entry.toURL()` verwenden aktualisieren. + +Für rückwärts Kompatibilität, die `resolveLocalFileSystemURL()`-Methode wird einen Absolute-Gerätepfad zu akzeptieren und kehrt ein `Entry`-Objekt entspricht, solange diese Datei in den `TEMPORARY` oder `PERSISTENT` Dateisysteme existiert. + +Dies wurde vor allem ein Problem mit dem File-Transfer-Plugin, die zuvor-Absolute-Gerätepfade verwendet (und kann damit noch einverstanden). Es wurde überarbeitet, um mit Dateisystem-URLs korrekt zu arbeiten, damit ersetzen `entry.fullPath` mit `entry.toURL()` immer das Plugin zum Arbeiten mit Dateien auf dem Gerät Probleme lösen sollte. + +In v1.1.0 wurde der Rückgabewert von `toURL()` (siehe \[CB-6394\] (https://issues.apache.org/jira/browse/CB-6394)) geändert, um eine absolute "file://" URL zurückgeben. wo immer möglich. Sicherstellung einer ' Cdvfile:'-URL können Sie an `toInternalURL()`. Diese Methode gibt jetzt Dateisystem URLs der Form zurück. + + cdvfile://localhost/persistent/path/to/file + + +die benutzt werden können, um die Datei eindeutig zu identifizieren. + +## Liste der Fehlercodes und Bedeutungen + +Wenn ein Fehler ausgelöst wird, wird eines der folgenden Codes verwendet werden. + +| Code | Konstante | +| ----:|:----------------------------- | +| 1 | `NOT_FOUND_ERR` | +| 2 | `SECURITY_ERR` | +| 3 | `ABORT_ERR` | +| 4 | `NOT_READABLE_ERR` | +| 5 | `ENCODING_ERR` | +| 6 | `NO_MODIFICATION_ALLOWED_ERR` | +| 7 | `INVALID_STATE_ERR` | +| 8 | `SYNTAX_ERR` | +| 9 | `INVALID_MODIFICATION_ERR` | +| 10 | `QUOTA_EXCEEDED_ERR` | +| 11 | `TYPE_MISMATCH_ERR` | +| 12 | `PATH_EXISTS_ERR` | + +## Konfigurieren das Plugin (Optional) + +Die Menge der verfügbaren Dateisysteme kann pro Plattform konfiguriert sein. Erkennen von iOS und Android ein Tag in `"config.xml"` die Namen der Dateisysteme installiert werden. Standardmäßig sind alle Datei-System-Roots aktiviert. + + + + + +### Android + + * `files`: interne Datei-Speicher-Verzeichnis der Anwendung + * `files-external`: Verzeichnis der Anwendung externe Datei Speicher + * `sdcard`: das externe Globaldatei-Speicherverzeichnis (Dies ist die Wurzel der SD-Karte, sofern installiert). Sie benötigen die Berechtigung zur Verwendung dieses `android.permission.WRITE_EXTERNAL_STORAGE`. + * `cache`: internen Cache-Verzeichnis der Anwendung + * `cache-external`: externer Cache-Verzeichnis der Anwendung + * `root`: das gesamte Gerät-Dateisystem + +Android unterstützt auch eine spezielle Dateisystem mit dem Namen "documents", die ein Unterverzeichnis "/Documents/" die "files" Dateisystem darstellt. + +### iOS + + * `library`: Bibliothek-Verzeichnis der Anwendung + * `documents`: Dokumente-Verzeichnis der Anwendung + * `cache`: Cache-Verzeichnis der Anwendung + * `bundle`: die Anwendung Bündel; den Speicherort der die app selbst auf dem Datenträger (schreibgeschützt) + * `root`: das gesamte Gerät-Dateisystem + +Standardmäßig können die Bibliothek und Dokumenten-Verzeichnisse mit iCloud synchronisiert werden. Sie können auch verlangen, zwei zusätzliche Dateisysteme, `library-nosync` und `documents-nosync`, die einem speziellen nicht synchronisierten Verzeichnis innerhalb darstellen der `/Library` oder `/Documents`-Dateisystem. \ No newline at end of file diff --git a/plugins/cordova-plugin-file/doc/de/index.md b/plugins/cordova-plugin-file/doc/de/index.md new file mode 100644 index 0000000..2a51695 --- /dev/null +++ b/plugins/cordova-plugin-file/doc/de/index.md @@ -0,0 +1,338 @@ + + +# cordova-plugin-file + +Dieses Plugin implementiert eine File-API, die Lese-/Schreibzugriff Zugriff auf Dateien, die auf dem Gerät befinden. + +Dieses Plugin basiert auf mehrere Angaben, einschließlich: die HTML5-File-API + +Die (heute nicht mehr existierenden) Verzeichnisse und System neuesten Erweiterungen: , obwohl die meisten von den Plugin-Code wurde geschrieben, als eine frühere Spec aktuell waren: + +Es implementiert auch die FileWriter Spec: + +Verwendung finden Sie in HTML5 Rocks ausgezeichnete [Dateisystem Artikel.][1] + + [1]: http://www.html5rocks.com/en/tutorials/file/filesystem/ + +Finden Sie einen Überblick über andere Speicheroptionen Cordovas [Speicher-Führer][2]. + + [2]: http://cordova.apache.org/docs/en/edge/cordova_storage_storage.md.html + +Dieses Plugin wird global `cordova.file`-Objekt definiert. + +Obwohl im globalen Gültigkeitsbereich, steht es nicht bis nach dem `deviceready`-Ereignis. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(cordova.file); + } + + +## Installation + + cordova plugin add cordova-plugin-file + + +## Unterstützte Plattformen + +* Amazon Fire OS +* Android +* BlackBerry 10 +* Firefox OS +* iOS +* Windows Phone 7 und 8 * +* Windows 8 * +* Browser + +* *Diese Plattformen unterstützen nicht `FileReader.readAsArrayBuffer` noch `FileWriter.write(blob)`.* + +## Wo Dateien gespeichert + +Stand: V1 werden URLs auf wichtige Datei-System-Verzeichnisse zur Verfügung gestellt. Jede URL in der Form *file:///path/to/spot/* ist, und ein `DirectoryEntry` mit `window.resolveLocalFileSystemURL()` konvertiert werden können. + +* `cordova.file.applicationDirectory`-Die schreibgeschützten Verzeichnis, in dem die Anwendung installiert ist. (*iOS*, *Android*, *BlackBerry 10*) + +* `cordova.file.applicationStorageDirectory`-Root-Verzeichnis der Anwendungs-Sandbox; auf iOS ist schreibgeschützt (aber bestimmte Unterverzeichnisse [wie `/Documents` ] sind Lese-und Schreibzugriff). Alle enthaltene Daten ist für die app privat. ( *iOS*, *Android*, *BlackBerry 10*) + +* `cordova.file.dataDirectory`-Beständige und private Datenspeicherung innerhalb der Anwendungs-Sandbox, die mit internen Speicher (auf Android, externen Speicher verwenden, verwenden Sie `.externalDataDirectory` ). Auf iOS, ist dieses Verzeichnis nicht mit iCloud synchronisiert (verwenden Sie `.syncedDataDirectory` ). (*iOS*, *Android*, *BlackBerry 10*) + +* `cordova.file.cacheDirectory`-Verzeichnis der zwischengespeicherten Daten-Dateien oder Dateien, die Ihre app einfach neu erstellen können. Das Betriebssystem kann diese Dateien löschen, wenn das Gerät auf Speicher knapp wird, dennoch sollten die apps vom Betriebssystem zum Löschen von Dateien hier nicht verlassen. (*iOS*, *Android*, *BlackBerry 10*) + +* `cordova.file.externalApplicationStorageDirectory`-Anwendungsraum auf externen Speicher. (*Android*) + +* `cordova.file.externalDataDirectory`-Wo, app-spezifische Datendateien auf externen Speicher setzen. (*Android*) + +* `cordova.file.externalCacheDirectory`-Anwendungscache auf externen Speicher. (*Android*) + +* `cordova.file.externalRootDirectory`-Externer Speicher (SD-Karte) Stamm. (*Android*, *BlackBerry 10*) + +* `cordova.file.tempDirectory`-Temp-Verzeichnis, dem das OS auf deaktivieren können wird. Verlassen Sie sich nicht auf das Betriebssystem, um dieses Verzeichnis zu löschen; Ihre Anwendung sollte immer Dateien gegebenenfalls entfernen. (*iOS*) + +* `cordova.file.syncedDataDirectory`-Hält app-spezifische Dateien, die (z. B. auf iCloud) synchronisiert werden sollten. (*iOS*) + +* `cordova.file.documentsDirectory`-Dateien für die app, aber privat sind sinnvoll, andere Anwendungen (z.B. Office-Dateien). (*iOS*) + +* `cordova.file.sharedDirectory`-Dateien für alle Anwendungen (*BlackBerry 10* weltweit verfügbar) + +## Dateisystemlayouts + +Obwohl technisch ein Implementierungsdetail, kann es sehr hilfreich zu wissen, wie die `cordova.file.*`-Eigenschaften physikalische Pfade auf einem echten Gerät zugeordnet sein. + +### iOS-Datei-System-Layout + +| Gerätepfad | `Cordova.file.*` | `iosExtraFileSystems` | R/w? | persistent? | OS löscht | Sync | Private | +|:-------------------------------------------- |:--------------------------- |:--------------------- |:----:|:-----------:|:----------:|:----:|:-------:| +| `/ Var/mobile/Applications/< UUID > /` | applicationStorageDirectory | - | r | N/A | N/A | N/A | Ja | +|    `appname.app/` | applicationDirectory | Bundle | r | N/A | N/A | N/A | Ja | +|       `www/` | - | - | r | N/A | N/A | N/A | Ja | +|    `Documents/` | documentsDirectory | Dokumente | R/w | Ja | Nein | Ja | Ja | +|       `NoCloud/` | - | Dokumente-nosync | R/w | Ja | Nein | Nein | Ja | +|    `Library` | - | Bibliothek | R/w | Ja | Nein | Ja? | Ja | +|       `NoCloud/` | dataDirectory | Bibliothek-nosync | R/w | Ja | Nein | Nein | Ja | +|       `Cloud/` | syncedDataDirectory | - | R/w | Ja | Nein | Ja | Ja | +|       `Caches/` | cacheDirectory | Cache | R/w | Ja * | Ja * * *| | Nein | Ja | +|    `tmp/` | tempDirectory | - | R/w | Nicht * * | Ja * * *| | Nein | Ja | + +* Dateien werden hinweg app Neustarts und Upgrades beibehalten, aber dieses Verzeichnis kann gelöscht werden, wenn das OS begehrt. Ihre Anwendung sollte in der Lage, Inhalte zu erschaffen, die möglicherweise gelöscht werden. + +* *-Dateien kann über app-Neustarts beizubehalten, aber verlasse dich nicht auf dieses Verhalten. Dateien sind nicht unbedingt Aktuelles beibehalten. Ihre Anwendung sollte Dateien aus diesem Verzeichnis entfernen, wenn es gilt, diese Dateien werden entfernt, da das OS nicht wann (oder auch wenn) garantiert. + +* * *| The OS kann den Inhalt dieses Verzeichnisses löschen, wenn es sich anfühlt, ist es erforderlich, aber verlassen Sie sich nicht dazu. Sie sollten dieses Verzeichnis entsprechend Ihrer Anwendung deaktivieren. + +### Android File System-Layout + +| Gerätepfad | `Cordova.file.*` | `AndroidExtraFileSystems` | R/w? | persistent? | OS löscht | Private | +|:--------------------------------- |:----------------------------------- |:------------------------- |:----:|:-----------:|:---------:|:-------:| +| `file:///android_asset/` | applicationDirectory | | r | N/A | N/A | Ja | +| `/ Data/Data/< app-Id > /` | applicationStorageDirectory | - | R/w | N/A | N/A | Ja | +|    `cache` | cacheDirectory | Cache | R/w | Ja | Ja * | Ja | +|    `files` | dataDirectory | Dateien | R/w | Ja | Nein | Ja | +|       `Documents` | | Dokumente | R/w | Ja | Nein | Ja | +| `< Sdcard > /` | externalRootDirectory | sdcard | R/w | Ja | Nein | Nein | +|    `Android/data//` | externalApplicationStorageDirectory | - | R/w | Ja | Nein | Nein | +|       `cache` | externalCacheDirectry | Cache-extern | R/w | Ja | Nicht * * | Nein | +|       `files` | externalDataDirectory | Dateien-extern | R/w | Ja | Nein | Nein | + +* Das Betriebssystem kann regelmäßig dieses Verzeichnis zu löschen, aber verlasse dich nicht auf dieses Verhalten. Deaktivieren Sie den Inhalt dieses Verzeichnisses für Ihre Anwendung geeigneten. Ein Benutzer den Cache manuell löschen sollte, werden die Inhalte dieses Verzeichnisses entfernt. + +* * The OS nicht klar dieses Verzeichnis automatisch; Sie sind verantwortlich für die Inhalte selbst verwalten. Der Benutzer den Cache manuell löschen sollte, werden der Inhalt des Verzeichnisses entfernt. + +**Hinweis**: Wenn externe Speichergeräte nicht bereitgestellt werden kann, sind die `cordova.file.external*` Eigenschaften `null`. + +### BlackBerry 10-File-System-Layout + +| Gerätepfad | `Cordova.file.*` | R/w? | persistent? | OS löscht | Private | +|:--------------------------------------------------- |:--------------------------- |:----:|:-----------:|:---------:|:-------:| +| `file:///Accounts/1000/APPDATA/ < app Id > /` | applicationStorageDirectory | r | N/A | N/A | Ja | +|    `app/native` | applicationDirectory | r | N/A | N/A | Ja | +|    `data/webviews/webfs/temporary/local__0` | cacheDirectory | R/w | Nein | Ja | Ja | +|    `data/webviews/webfs/persistent/local__0` | dataDirectory | R/w | Ja | Nein | Ja | +| `file:///Accounts/1000/Removable/sdcard` | externalRemovableDirectory | R/w | Ja | Nein | Nein | +| `file:///Accounts/1000/Shared` | sharedDirectory | R/w | Ja | Nein | Nein | + +*Hinweis*: Wenn die Anwendung bereitgestellt wird, um Perimeter zu arbeiten, alle Pfade sind relativ /accounts/1000-enterprise. + +## Android Eigenarten + +### Android permanenten Speicherort + +Es gibt mehrere gültige Speicherorte, persistente Dateien auf einem Android-Gerät zu speichern. Finden Sie auf [dieser Seite][3] eine ausführliche Diskussion über die verschiedenen Möglichkeiten. + + [3]: http://developer.android.com/guide/topics/data/data-storage.html + +Frühere Versionen des Plugins wählen würde, den Speicherort der temporären und permanenten Dateien beim Start, basierend auf, ob das Gerät behauptete, dass die SD-Karte (oder gleichwertige Speicherpartition) bereitgestellt wurde. Wenn die SD-Karte eingelegt wurde, oder wenn eine große interne Speicherpartition verfügbar war (wie auf Nexus-Geräten) und dann in die Wurzel dieses Raumes, die persistenten Dateien gespeichert werden. Dies bedeutete, dass alle Cordova apps aller verfügbaren Dateien auf der Karte sehen konnte. + +Wenn die SD-Karte nicht verfügbar war, dann Vorgängerversionen Daten unter speichern würde `/data/data/`, die isoliert Anwendungen voneinander, aber möglicherweise noch Ursache Daten zwischen Benutzern freigegeben werden. + +Es ist jetzt möglich, ob Sie Dateien der internen Datei-Speicherort oder unter Verwendung der bisherigen Logik, mit einer Präferenz in der Anwendung-`config.xml`-Datei speichern möchten. Hierzu fügen Sie eine dieser zwei Zeilen zu `"config.xml"`: + + + + + + +Ohne diese Zeile wird das Datei Plugin `Compatibility` als Standard verwenden. Wenn ein Präferenz-Tag vorhanden ist, und nicht einen der folgenden Werte, wird die Anwendung nicht gestartet. + +Wenn Ihre Anwendung für Benutzer zuvor versandt wird, mithilfe eines älteren (Pre-1.0) Version dieses Plugins und gespeicherte Dateien im permanenten Dateisystem hat, dann sollten Sie die Einstellung zur `Compatibility` einstellen. Wechseln die Location auf "Internal" würde bedeuten, dass Benutzer, die aktualisieren Sie ihre Anwendung, möglicherweise nicht auf ihre zuvor gespeicherte Dateien, abhängig von ihrem Gerät zugreifen. + +Wenn Ihre Anwendung neu ist, oder nie zuvor Dateien im Dateisystem persistent gespeichert hat, wird die `Internal` Einstellung in der Regel empfohlen. + +## iOS Macken + +* `cordova.file.applicationStorageDirectory`ist schreibgeschützt; zum Speichern von Dateien im Stammverzeichnis der Versuch schlägt fehl. Verwenden Sie eine der anderen `cordova.file.*` für iOS definierten Eigenschaften (nur `applicationDirectory` und `applicationStorageDirectory` sind schreibgeschützt). +* `FileReader.readAsText(blob, encoding)` + * Die `encoding` Parameter wird nicht unterstützt und UTF-8-Kodierung ist immer wirksam. + +### iOS permanenten Speicherort + +Es gibt zwei gültige Speicherorte persistente Dateien auf ein iOS-Gerät speichern: das Dokumenten-Verzeichnis und das Verzeichnis Library. Frühere Versionen des Plugins gespeichert immer nur persistente Dateien im Verzeichnis Dokumente. Dies hatte den Nebeneffekt einer Anwendung Dateien in iTunes, die oft unbeabsichtigte, speziell für Anwendungen, die viele kleine Dateien behandeln war, sichtbar zu machen, anstatt komplette Dokumente für den Export, die den beabsichtigten Zweck des Verzeichnisses ist zu produzieren. + +Es ist jetzt möglich, ob Sie Dateien in Dokumente oder Verzeichnis Library mit einer Präferenz in der Anwendung-`config.xml`-Datei speichern möchten. Hierzu fügen Sie eine dieser zwei Zeilen zu `"config.xml"`: + + + + + + +Ohne diese Zeile wird das Datei Plugin `Compatibility` als Standard verwenden. Wenn ein Präferenz-Tag vorhanden ist, und nicht einen der folgenden Werte, wird die Anwendung nicht gestartet. + +Wenn Ihre Anwendung für Benutzer zuvor versandt wird, mithilfe eines älteren (Pre-1.0) Version dieses Plugins und gespeicherte Dateien im permanenten Dateisystem hat, dann sollten Sie die Einstellung zur `Compatibility` einstellen. Standort zur `Library` wechseln würde bedeuten, dass Benutzer, die ihre Anwendung aktualisieren nicht in der Lage wäre, ihre zuvor gespeicherte Dateien zugreifen. + +Wenn die Anwendung neu, oder nie zuvor Dateien im Dateisystem persistent gespeichert hat, wird die Einstellung der `Library` allgemein empfohlen. + +## Firefox OS Macken + +Der Datei-System-API wird von Firefox-OS nicht nativ unterstützt und wird als ein Shim auf IndexedDB implementiert. + +* Schlägt nicht fehl, wenn Sie nicht leere Verzeichnisse entfernen +* Metadaten wird für Verzeichnisse nicht unterstützt. +* Methoden `copyTo` und `moveTo` unterstützen keine Verzeichnisse + +Die folgenden Datenpfade werden unterstützt: * `applicationDirectory` - `xhr` verwendet, um lokale Dateien erhalten, die mit der app verpackt sind. *`dataDirectory` - für persistente app-spezifische Daten-Dateien. *`cacheDirectory` - Cache-Dateien, die app startet überleben sollte (Apps sollten nicht vom Betriebssystem zum Löschen von Dateien hier verlassen). + +## Browser-Eigenheiten + +### Gemeinsamen Macken und Bemerkungen + +* Jeder Browser verwendet ein eigene Sandbox Dateisystem. IE und Firefox verwenden IndexedDB als Basis. Alle Browser verwenden Schrägstrich als Verzeichnistrennzeichen in einem Pfad. +* Directory-Einträge müssen nacheinander erstellt werden. Z. B. der Aufruf `fs.root.getDirectory ("dir1/Ordner2 ', {create:true}, SuccessCallback, ErrorCallback)` schlägt fehl, wenn dir1 nicht existierte. +* Das Plugin fordert Benutzer die Berechtigung zum permanenten Speicher beim ersten Start Anwendung verwenden. +* Plugin unterstützt `Cdvfile://localhost` (lokale Ressourcen) nur. D.h. externe Ressourcen nicht über `Cdvfile` unterstützt. +* Das Plugin folgt nicht ["File System API 8.3 Naming Einschränkungen"][4]. +* BLOB und Datei "`close`-Funktion wird nicht unterstützt. +* `FileSaver` und `BlobBuilder` werden von diesem Plugin nicht unterstützt und müssen nicht geboren. +* Das Plugin unterstützt keine `RequestAllFileSystems`. Diese Funktion fehlt auch in den Spezifikationen. +* Einträge im Verzeichnis werden nicht entfernt werden, wenn Sie verwenden `create: true` Flag für vorhandenes Verzeichnis. +* Über Konstruktor erstellte Dateien werden nicht unterstützt. Sie sollten stattdessen die entry.file-Methode verwenden. +* Jeder Browser verwendet eine eigene Form für Blob-URL-Verweise. +* `readAsDataURL`-Funktion wird unterstützt, aber die Mediatype in Chrom hängt von der Eintrag Namenerweiterung, Mediatype im IE immer leer ist (das ist dasselbe wie `Text-Plain` gemäß der Spezifikation), Mediatype in Firefox ist immer `Application/Octet-Stream`. Beispielsweise, wenn der Inhalt `Abcdefg` gibt dann Firefox `Daten: Anwendung / Octet-Stream; base64, YWJjZGVmZw ==`, IE gibt `Daten:; base64, YWJjZGVmZw ==`, Chrom gibt `Daten: < Mediatype je nach Erweiterung des Eintragsnamens >; base64, YWJjZGVmZw ==`. +* `ToInternalURL` gibt den Pfad zurück, in der Form `file:///persistent/path/to/entry` (Firefox, IE). Chrom gibt den Pfad zurück, in der Form `cdvfile://localhost/persistent/file`. + + [4]: http://www.w3.org/TR/2011/WD-file-system-api-20110419/#naming-restrictions + +### Chrom-Macken + +* Chrom-Dateisystem ist nicht sofort nach Gerät bereit. Als Workaround können Sie `FilePluginIsReady`-Ereignis abonnieren. Beispiel: + + javascript + window.addEventListener('filePluginIsReady', function(){ console.log('File plugin is ready');}, false); + + +`Window.isFilePluginReadyRaised`-Funktion können Sie überprüfen, ob Ereignis bereits ausgelöst wurde. -window.requestFileSystem temporär und PERSISTENTE Dateisystem-Quoten sind nicht begrenzt, in Chrom. -Um die dauerhafte Speicherung in Chrom zu erhöhen benötigen Sie `window.initPersistentFileSystem`-Methode aufrufen. Permanenter Speicherkontingent beträgt 5 MB standardmäßig. -Chrome erforderlich `--erlauben-Datei-Zugriff-aus-Files` Argument an den Support API via `file:///` Protokoll führen. -`Datei`-Objekt wird nicht geändert werden, wenn Sie Flag verwenden `{create:true}` als einen vorhandenen `Eintrag` zu erhalten. -Veranstaltungen `cancelable`-Eigenschaft festgelegt ist in Chrom wahr. Dies widerspricht der [Spezifikation][5]. -`toURL`-Funktion in Chrome zurück `Dateisystem:`-Pfad je nach Anwendungshost vorangestellt. Z. B. `filesystem:file:///persistent/somefile.txt`, `Filesystem:http://localhost:8080/persistent/somefile.txt`. -`toURL` Funktionsergebnis enthält keine nachgestellten Schrägstrich bei Verzeichniseintrag. Chrom löst Verzeichnisse mit Schrägstrich-gezogene Urls aber korrekt. -`ResolveLocalFileSystemURL`-Methode erfordert die eingehenden `Url` `Dateisystem` Präfix haben. Beispielsweise sollte die `Url`-Parameter für `ResolveLocalFileSystemURL` in der Form `filesystem:file:///persistent/somefile.txt` im Gegensatz zu der Form `file:///persistent/somefile.txt` in Android. -Veraltete `ToNativeURL`-Funktion wird nicht unterstützt und muss keinen Stub. -`SetMetadata`-Funktion ist nicht in den Spezifikationen angegeben und nicht unterstützt. -INVALID_MODIFICATION_ERR (Code: 9) wird ausgelöst, statt SYNTAX_ERR(code: 8) auf anfordern des Dateisystems nicht existent. -INVALID_MODIFICATION_ERR (Code: 9) wird ausgelöst, anstatt PATH_EXISTS_ERR(code: 12) zu versuchen, die ausschließlich eine Datei oder ein Verzeichnis zu erstellen, die bereits vorhanden ist. -INVALID_MODIFICATION_ERR (Code: 9) wird ausgelöst, anstatt NO_MODIFICATION_ALLOWED_ERR(code: 6) zu versuchen, rufen Sie RemoveRecursively auf das Root-Dateisystem. -INVALID_MODIFICATION_ERR (Code: 9) wird ausgelöst, anstatt NOT_FOUND_ERR(code: 1) zu versuchen, MoveTo-Verzeichnis, das nicht vorhanden ist. + + [5]: http://dev.w3.org/2009/dap/file-system/file-writer.html + +### Auf der Grundlage von IndexedDB Impl Macken (Firefox und IE) + +* `.` und `.` werden nicht unterstützt. +* IE unterstützt keine `file:///`-Modus; nur der Modus für gehostete ist unterstützten (Http://localhost:xxxx). +* Firefox Dateisystem Größe ist nicht begrenzt, aber jede 50MB-Erweiterung wird eine Benutzer die Berechtigung anzufordern. IE10 können bis zu 10mb kombinierte AppCache und IndexedDB in Implementierung des Dateisystems verwendet, ohne Aufforderung, sobald Sie dieses Niveau, werden, das Sie aufgefordert werden schlagen, wenn Sie es bis Max 250 mb pro Standort erhöht werden sollen. `Size`-Parameter für `RequestFileSystem` Funktion wirkt also nicht Dateisystem in Firefox und IE. +* `ReadAsBinaryString` Funktion heißt es nicht in die Angaben und in IE nicht unterstützt und muss keinen Stub. +* `file.Type` ist immer null. +* Sie sollten nicht erstellen Eintrag mit DirectoryEntry Instanz Rückrufergebnis, die gelöscht wurde. Andernfalls erhalten Sie einen "hängende Eintrag". +* Bevor Sie eine Datei lesen können, die gerade geschrieben wurde, müssen Sie eine neue Instanz dieser Datei erhalten. +* `SetMetadata`-Funktion, die nicht in den Specs genannt unterstützt Feldänderung nur `ModificationTime`. +* `CopyTo` und `MoveTo`-Funktionen unterstützen keine Verzeichnisse. +* Verzeichnisse-Metadaten werden nicht unterstützt. +* Beide Entry.remove und directoryEntry.removeRecursively nicht scheitern, wenn nicht leere Verzeichnisse entfernen - Verzeichnisse entfernt werden stattdessen zusammen mit Inhalt gereinigt. +* `abort` und `truncate`-Funktionen werden nicht unterstützt. +* Progress-Ereignisse werden nicht ausgelöst. Beispielsweise wird dieser Handler nicht ausgeführt werden: + + javascript + writer.onprogress = function() { /*commands*/ }; + + +## Upgrade Notes + +In v1.0.0 dieses Plugins haben die `FileEntry` und `DirectoryEntry` Strukturen geändert, um mehr im Einklang mit der veröffentlichten Spezifikation sein. + +Vorgängerversionen (Pre-1.0.0) des Plugins den Gerät-Absolute-Dateispeicherort in der Eigenschaft `fullPath` `Entry` Objekte gespeichert. Diese Pfade würde in der Regel aussehen + + /var/mobile/Applications//Documents/path/to/file (iOS) + /storage/emulated/0/path/to/file (Android) + + +Diese Pfade wurden auch von der `toURL()`-Methode der `Entry` Objekte zurückgegeben. + +Mit v1.0.0 ist das `fullPath`-Attribut den Pfad zu der Datei, *relativ zum Stammverzeichnis des Dateisystems HTML*. Also, würde die oben genannten Wege jetzt beide durch ein `FileEntry`-Objekt mit einem `fullPath` von dargestellt werden + + /path/to/file + + +Wenn Ihre Anwendung mit absoluter Gerätepfade arbeitet und Sie zuvor diese Pfade durch die Eigenschaft `fullPath` `Entry` Objekte abgerufen, sollten dann Sie den Code, um stattdessen `entry.toURL()` verwenden aktualisieren. + +Für rückwärts Kompatibilität, die `resolveLocalFileSystemURL()`-Methode wird einen Absolute-Gerätepfad zu akzeptieren und kehrt ein `Entry`-Objekt entspricht, solange diese Datei in den `TEMPORARY` oder `PERSISTENT` Dateisysteme existiert. + +Dies wurde vor allem ein Problem mit dem File-Transfer-Plugin, die zuvor-Absolute-Gerätepfade verwendet (und kann damit noch einverstanden). Es wurde überarbeitet, um mit Dateisystem-URLs korrekt zu arbeiten, damit ersetzen `entry.fullPath` mit `entry.toURL()` immer das Plugin zum Arbeiten mit Dateien auf dem Gerät Probleme lösen sollte. + +In v1.1.0 wurde der Rückgabewert von `toURL()` (siehe \[CB-6394\] (https://issues.apache.org/jira/browse/CB-6394)) geändert, um eine absolute "file://" URL zurückgeben. wo immer möglich. Sicherstellung einer ' Cdvfile:'-URL können Sie an `toInternalURL()`. Diese Methode gibt jetzt Dateisystem URLs der Form zurück. + + cdvfile://localhost/persistent/path/to/file + + +die benutzt werden können, um die Datei eindeutig zu identifizieren. + +## Liste der Fehlercodes und Bedeutungen + +Wenn ein Fehler ausgelöst wird, wird eines der folgenden Codes verwendet werden. + +| Code | Konstante | +| ----:|:----------------------------- | +| 1 | `NOT_FOUND_ERR` | +| 2 | `SECURITY_ERR` | +| 3 | `ABORT_ERR` | +| 4 | `NOT_READABLE_ERR` | +| 5 | `ENCODING_ERR` | +| 6 | `NO_MODIFICATION_ALLOWED_ERR` | +| 7 | `INVALID_STATE_ERR` | +| 8 | `SYNTAX_ERR` | +| 9 | `INVALID_MODIFICATION_ERR` | +| 10 | `QUOTA_EXCEEDED_ERR` | +| 11 | `TYPE_MISMATCH_ERR` | +| 12 | `PATH_EXISTS_ERR` | + +## Konfigurieren das Plugin (Optional) + +Die Menge der verfügbaren Dateisysteme kann pro Plattform konfiguriert sein. Erkennen von iOS und Android ein Tag in `"config.xml"` die Namen der Dateisysteme installiert werden. Standardmäßig sind alle Datei-System-Roots aktiviert. + + + + + +### Android + +* `files`: interne Datei-Speicher-Verzeichnis der Anwendung +* `files-external`: Verzeichnis der Anwendung externe Datei Speicher +* `sdcard`: das externe Globaldatei-Speicherverzeichnis (Dies ist die Wurzel der SD-Karte, sofern installiert). Sie benötigen die Berechtigung zur Verwendung dieses `android.permission.WRITE_EXTERNAL_STORAGE`. +* `cache`: internen Cache-Verzeichnis der Anwendung +* `cache-external`: externer Cache-Verzeichnis der Anwendung +* `root`: das gesamte Gerät-Dateisystem + +Android unterstützt auch eine spezielle Dateisystem mit dem Namen "documents", die ein Unterverzeichnis "/Documents/" die "files" Dateisystem darstellt. + +### iOS + +* `library`: Bibliothek-Verzeichnis der Anwendung +* `documents`: Dokumente-Verzeichnis der Anwendung +* `cache`: Cache-Verzeichnis der Anwendung +* `bundle`: die Anwendung Bündel; den Speicherort der die app selbst auf dem Datenträger (schreibgeschützt) +* `root`: das gesamte Gerät-Dateisystem + +Standardmäßig können die Bibliothek und Dokumenten-Verzeichnisse mit iCloud synchronisiert werden. Sie können auch verlangen, zwei zusätzliche Dateisysteme, `library-nosync` und `documents-nosync`, die einem speziellen nicht synchronisierten Verzeichnis innerhalb darstellen der `/Library` oder `/Documents`-Dateisystem. diff --git a/plugins/cordova-plugin-file/doc/de/plugins.md b/plugins/cordova-plugin-file/doc/de/plugins.md new file mode 100644 index 0000000..8887d7a --- /dev/null +++ b/plugins/cordova-plugin-file/doc/de/plugins.md @@ -0,0 +1,101 @@ + + +# Hinweise für Plugin-Entwickler + +Diese Notizen sind hauptsächlich für Android und iOS-Entwickler, die Plugins welche Schnittstelle mit dem Dateisystem, mit dem Plugin Datei schreiben möchten. + +## Arbeiten mit Cordova-Datei-System-URLs + +Seit der Version 1.0.0, wurde dieses Plugin verwendet URLs mit einer `cdvfile` Regelung für die gesamte Kommunikation über die Brücke, sondern als raw-Device Dateisystempfade zu JavaScript auszusetzen. + +Auf der Seite JavaScript bedeutet dies, dass FileEntries und DirectoryEntry-Objekt ein FullPath-Attribut haben, die relativ zum Stammverzeichnis des Dateisystems HTML ist. Wenn Ihr Plugins-JavaScript-API ein FileEntries oder DirectoryEntry-Objekt akzeptiert, rufen Sie `.toURL()` auf das Objekt vor der Übergabe an systemeigenen Code über die Brücke. + +### Konvertieren von Cdvfile: / / URLs auf Fileystem Pfade + +Plugins, die auf das Dateisystem schreiben müssen, sollten eine empfangene Datei-System-URL auf eine tatsächliche Stelle des Dateisystems zu konvertieren. Es gibt mehrere Wege, dies zu tun, je nach einheitlichen Plattform. + +Es ist wichtig, daran erinnern, dass nicht alle `cdvfile://` URLs sind zuweisbaren real Dateien auf das Gerät. Einige URLs verweisen auf Vermögenswerte auf Gerät nicht durch Dateien dargestellt werden, oder sogar auf Remoteressourcen verweisen können. Aufgrund dieser Möglichkeiten sollten Plugins immer testen, ob sie ein sinnvolles Ergebnis zu erhalten, wieder bei dem Versuch, die URLs in Pfade umwandeln. + +#### Android + +Auf Android, konvertiert die einfachste Methode eine `cdvfile://` URL zu einem Dateisystempfad zu verwenden ist `org.apache.cordova.CordovaResourceApi` . `CordovaResourceApi`verfügt über mehrere Methoden der verarbeiten kann `cdvfile://` URLs: + + WebView ist Mitglied der Plugin-Klasse CordovaResourceApi ResourceApi = webView.getResourceApi(); + + Erhalten eine file:/// URL, diese Datei auf dem Gerät / / oder die gleiche URL unverändert, wenn es eine Datei-Uri FileURL zugeordnet werden kann nicht = resourceApi.remapUri(Uri.parse(cdvfileURL)); + + +Es ist auch möglich, das Plugin Datei direkt zu verwenden: + + Import org.apache.cordova.file.FileUtils; + Import org.apache.cordova.file.FileSystem; + Import Java.net.MalformedURLException:; + + Erhalten Sie das Datei-Plugin aus dem Plugin-Manager FileUtils FilePlugin = (FileUtils)webView.pluginManager.getPlugin("File"); + + Angesichts eine URL, einen Pfad zu erhalten, denn es versuchen {String Pfad = filePlugin.filesystemPathForURL(cdvfileURL);} catch (MalformedURLException e) {/ / die Dateisystem-Url war nicht erkannt} + + +Aus einem Pfad zu konvertieren eine `cdvfile://` URL: + + Import org.apache.cordova.file.LocalFilesystemURL; + + Rufen Sie ein LocalFilesystemURL-Objekt für einen Gerätepfad / / oder null, wenn sie nicht als URL Cdvfile dargestellt wird. + LocalFilesystemURL Url = filePlugin.filesystemURLforLocalPath(path); + Erhalten Sie die Zeichenfolgendarstellung der URL Objekt String CdvfileURL = url.toString(); + + +Wenn Ihr Plugin eine Datei erstellt, und Sie dafür ein FileEntries-Objekt zurückgeben möchten, verwenden Sie das Datei-Plugin: + + Zurückgeben eine JSON-Struktur geeignet für die Rückgabe an JavaScript, / / oder null, wenn diese Datei nicht als URL Cdvfile darstellbar ist. + JSONObject Eintrag = filePlugin.getEntryForFile(file); + + +#### iOS + +Cordova auf iOS verwendet nicht das gleiche `CordovaResourceApi` Konzept als Android. Auf iOS sollten Sie das Datei-Plugin verwenden, zum Konvertieren von URLs und Dateisystem-Pfaden. + + Rufen Sie ein CDVFilesystem URL-Objekt von einer URL-Zeichenfolge CDVFilesystemURL * Url = [CDVFilesystemURL FileSystemURLWithString:cdvfileURL]; + Erhalten Sie einen Pfad für die URL-Objekt oder NULL, wenn es einen Dateipfad NSString * zugeordnet werden kann nicht = [FilePlugin FilesystemPathForURL:url]; + + + Eine CDVFilesystem URL-Objekt für einen Gerätepfad abrufen oder / / gleich NULL, wenn sie nicht als URL Cdvfile dargestellt wird. + CDVFilesystemURL-Url = [FilePlugin FileSystemURLforLocalPath:path]; + Erhalten Sie die Zeichenfolgendarstellung der URL Objekt NSString * CdvfileURL = [Url AbsoluteString]; + + +Wenn Ihr Plugin eine Datei erstellt, und Sie dafür ein FileEntries-Objekt zurückgeben möchten, verwenden Sie das Datei-Plugin: + + Eine CDVFilesystem URL-Objekt für einen Gerätepfad abrufen oder / / gleich NULL, wenn sie nicht als URL Cdvfile dargestellt wird. + CDVFilesystemURL-Url = [FilePlugin FileSystemURLforLocalPath:path]; + Erhalten eine Struktur zurück nach JavaScript NSDictionary * Eintrag = [FilePlugin MakeEntryForLocalURL:url] + + +#### JavaScript + +In JavaScript, bekommen eine `cdvfile://` URL aus einem FileEntries oder DirectoryEntry-Objekt, rufen Sie einfach `.toURL()` drauf: + + Var CdvfileURL = entry.toURL(); + + +Im Plugin Antwort Handler zur Konvertierung von einer zurückgegebenen FileEntries-Struktur in einem tatsächlichen Eintrag-Objekt sollte Handlercode importieren die Datei-Erweiterung und ein neues Objekt zu erstellen: + + Erstellen Sie entsprechenden Eintrag Objekt Var Eintrag; + Wenn (entryStruct.isDirectory) {Eintrag = neues DirectoryEntry (entryStruct.name, entryStruct.fullPath, neue FileSystem(entryStruct.filesystemName));} sonst {Eintrag = neue FileEntries (entryStruct.name, entryStruct.fullPath, neue FileSystem(entryStruct.filesystemName));} \ No newline at end of file diff --git a/plugins/cordova-plugin-file/doc/es/README.md b/plugins/cordova-plugin-file/doc/es/README.md new file mode 100644 index 0000000..2a653bf --- /dev/null +++ b/plugins/cordova-plugin-file/doc/es/README.md @@ -0,0 +1,335 @@ + + +# cordova-plugin-file + +[![Build Status](https://travis-ci.org/apache/cordova-plugin-file.svg)](https://travis-ci.org/apache/cordova-plugin-file) + +Este plugin implementa una API de archivo que permite acceso de lectura/escritura a los archivos que residen en el dispositivo. + +Este plugin se basa en varias especificaciones, incluyendo: el HTML5 archivo API + +Los directorios (ahora extinto) y sistema de extensiones más recientes: aunque la mayor parte del código del plugin fue escrito cuando una especificación anterior era actual: + +También implementa la especificación de FileWriter: + +Para el uso, por favor, consulte 'HTML5 Rocks excelente [FileSystem artículo.](http://www.html5rocks.com/en/tutorials/file/filesystem/) + +Para tener una visión general de otras opciones de almacenamiento, consulte [Guía de almacenamiento Cordova](http://cordova.apache.org/docs/en/edge/cordova_storage_storage.md.html). + +Este plugin define global `cordova.file` objeto. + +Aunque en el ámbito global, no estará disponible hasta después de la `deviceready` evento. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(cordova.file); + } + + +## Instalación + + cordova plugin add cordova-plugin-file + + +## Plataformas soportadas + + * Amazon fire OS + * Android + * BlackBerry 10 + * Firefox OS + * iOS + * Windows Phone 7 y 8 * + * Windows 8 * + * Windows* + * Explorador + +\* *These platforms do not support `FileReader.readAsArrayBuffer` nor `FileWriter.write(blob)`.* + +## Donde almacenar los archivos + +A partir de v1.2.0, URLs a directorios de sistema de archivos importantes son proporcionadas. Cada dirección URL está en la forma *file:///path/to/spot/*y se puede convertir en un `DirectoryEntry` usando`window.resolveLocalFileSystemURL()`. + + * `cordova.file.applicationDirectory`-Directorio Read-only donde está instalada la aplicación. (*iOS*, *Android*, *BlackBerry 10*) + + * `cordova.file.applicationStorageDirectory`-Directorio del entorno limitado de la aplicación; en iOS esta ubicación es de sólo lectura (pero subdirectorios específicos [como `/Documents` ] son de lectura y escritura). Todos los datos contenidos dentro es privado para la aplicación. ( *iOS*, *Android*, *BlackBerry 10*) + + * `cordova.file.dataDirectory`-Almacenamiento de datos persistente y privadas dentro de entorno limitado de la aplicación utilizando la memoria interna (en Android, si necesitas usar memoria externa, use `.externalDataDirectory` ). En iOS, este directorio no está sincronizado con iCloud (utilice `.syncedDataDirectory` ). (*iOS*, *Android*, *BlackBerry 10*) + + * `cordova.file.cacheDirectory`-Directorio para los archivos de datos almacenados en caché o los archivos que su aplicación puede volver a crear fácilmente. El sistema operativo puede borrar estos archivos cuando el dispositivo se agota en almacenamiento de información, sin embargo, aplicaciones no deben confiar en el sistema operativo para eliminar los archivos de aquí. (*iOS*, *Android*, *BlackBerry 10*) + + * `cordova.file.externalApplicationStorageDirectory`-Espacio aplicación de almacenamiento externo. (*Android*) + + * `cordova.file.externalDataDirectory`¿Dónde poner los archivos de datos específicos de la aplicación de almacenamiento externo. (*Android*) + + * `cordova.file.externalCacheDirectory`-Caché aplicación de almacenamiento externo. (*Android*) + + * `cordova.file.externalRootDirectory`-Raíz de almacenamiento externo (tarjeta SD). (*Android*, *BlackBerry 10*) + + * `cordova.file.tempDirectory`-Directorio temporal que puede borrar el sistema operativo en sí. No confíe en el sistema operativo para borrar este directorio; su aplicación siempre debe eliminar archivos según corresponda. (*iOS*) + + * `cordova.file.syncedDataDirectory`-Contiene los archivos de la aplicación específica que deben ser sincronizados (e.g. a iCloud). (*iOS*) + + * `cordova.file.documentsDirectory`-Archivos privados a la aplicación, pero que son significativos para otra aplicación (por ejemplo archivos de Office). (*iOS*) + + * `cordova.file.sharedDirectory`-Archivos disponibles globalmente para todas las aplicaciones (*BlackBerry 10*) + +## Diseños de sistema de archivo + +Aunque técnicamente un detalle de la implementación, puede ser muy útil saber cómo la `cordova.file.*` mapa de propiedades en trazados físicos en un dispositivo real. + +### iOS diseño de sistema de archivo + +| Ruta de dispositivo | `Cordova.file.*` | `iosExtraFileSystems` | ¿r/w? | ¿persistente? | OS despeja | sincronización | privado | +|:---------------------------------------------- |:--------------------------- |:--------------------- |:-----:|:-------------:|:-------------:|:--------------:|:-------:| +| `/ var/mobile/Applications/< UUID > /` | applicationStorageDirectory | - | r | N / A | N / A | N / A | Sí | +|    `appname.app/` | applicationDirectory | Bundle | r | N / A | N / A | N / A | Sí | +|       `www/` | - | - | r | N / A | N / A | N / A | Sí | +|    `Documents/` | documentsDirectory | documentos | r/w | Sí | No | Sí | Sí | +|       `NoCloud/` | - | documentos-nosync | r/w | Sí | No | No | Sí | +|    `Library` | - | Biblioteca | r/w | Sí | No | ¿Sí? | Sí | +|       `NoCloud/` | dataDirectory | Biblioteca-nosync | r/w | Sí | No | No | Sí | +|       `Cloud/` | syncedDataDirectory | - | r/w | Sí | No | Sí | Sí | +|       `Caches/` | cacheDirectory | caché | r/w | Sí * | Yes**\* | No | Sí | +|    `tmp/` | tempDirectory | - | r/w | No** | Yes**\* | No | Sí | + +\ * Archivos persisten a través de reinicios de aplicación y actualizaciones, pero este directorio puede ser despejó cuando el OS deseos. Su aplicación debe ser capaz de recrear cualquier contenido que puede ser eliminado. + +** Archivos puede persistir a través de la aplicación se reinicia, pero no confiar en este comportamiento. Los archivos no se garantizan que persisten a través de actualizaciones. Su aplicación debe eliminar los archivos de este directorio cuando es aplicable, como el sistema operativo no garantiza cuando (o incluso si) estos archivos se quitan. + +**\ * OS la puede borrar el contenido de este directorio siempre que se siente es necesario, pero no dependen de esto. Debe borrar este directorio según sea apropiado para su aplicación. + +### Disposición del sistema Android File + +| Ruta de dispositivo | `Cordova.file.*` | `AndroidExtraFileSystems` | ¿r/w? | ¿persistente? | OS despeja | privado | +|:------------------------------------------------ |:----------------------------------- |:------------------------- |:-----:|:-------------:|:----------:|:-------:| +| `File:///android_asset/` | applicationDirectory | | r | N / A | N / A | Sí | +| `/Data/data/< id de aplicación > /` | applicationStorageDirectory | - | r/w | N / A | N / A | Sí | +|    `cache` | cacheDirectory | caché | r/w | Sí | Sí \ * | Sí | +|    `files` | dataDirectory | archivos | r/w | Sí | No | Sí | +|       `Documents` | | documentos | r/w | Sí | No | Sí | +| `< sdcard > /` | externalRootDirectory | sdcard | r/w | Sí | No | No | +|    `Android/data//` | externalApplicationStorageDirectory | - | r/w | Sí | No | No | +|       `cache` | externalCacheDirectry | caché-externo | r/w | Sí | No** | No | +|       `files` | externalDataDirectory | archivos externos | r/w | Sí | No | No | + +\ * El sistema operativo periódicamente puede borrar este directorio, pero no confiar en este comportamiento. Borrar el contenido de este directorio según sea apropiado para su aplicación. El contenido de este directorio debe un usuario purga la caché manualmente, se eliminan. + +** El sistema operativo no borrar este directorio automáticamente; usted es responsable de administrar el contenido usted mismo. Deberá el usuario purga la caché manualmente, se extraen los contenidos del directorio. + +**Nota**: Si no se puede montar de almacenamiento externo, el `cordova.file.external*` Propiedades`null`. + +### Disposición del sistema blackBerry 10 archivo + +| Ruta de dispositivo | `Cordova.file.*` | ¿r/w? | ¿persistente? | OS despeja | privado | +|:------------------------------------------------------------- |:--------------------------- |:-----:|:-------------:|:----------:|:-------:| +| `File:///accounts/1000/AppData/ < id de aplicación > /` | applicationStorageDirectory | r | N / A | N / A | Sí | +|    `app/native` | applicationDirectory | r | N / A | N / A | Sí | +|    `data/webviews/webfs/temporary/local__0` | cacheDirectory | r/w | No | Sí | Sí | +|    `data/webviews/webfs/persistent/local__0` | dataDirectory | r/w | Sí | No | Sí | +| `File:///accounts/1000/Removable/sdcard` | externalRemovableDirectory | r/w | Sí | No | No | +| `File:///accounts/1000/shared` | sharedDirectory | r/w | Sí | No | No | + +*Nota*: cuando se implementa la aplicación al trabajo de perímetro, todos los caminos son relativos a /accounts/1000-enterprise. + +## Rarezas Android + +### Ubicación de almacenamiento persistente Android + +Hay múltiples ubicaciones válidas para almacenar archivos persistentes en un dispositivo Android. Vea [esta página](http://developer.android.com/guide/topics/data/data-storage.html) para una extensa discusión de las distintas posibilidades. + +Las versiones anteriores del plugin elegiría la ubicación de los archivos temporales y persistentes en el arranque, basado en si el dispositivo afirmó que fue montado en la tarjeta SD (o partición de almacenamiento equivalente). Si fue montada en la tarjeta SD, o una partición de gran almacenamiento interno estaba disponible (como en dispositivos de Nexus,) y luego los archivos persistentes se almacenaría en la raíz de ese espacio. Esto significaba que todas las apps Cordova podían ver todos los archivos disponibles en la tarjeta. + +Si la tarjeta SD no estaba disponible, entonces versiones anteriores podría almacenar datos debajo de `/data/data/` , que aísla las apps del otro, pero puede todavía causa datos para ser compartido entre los usuarios. + +Ahora es posible elegir si desea almacenar archivos en la ubicación de almacenamiento del archivo interno, o usando la lógica anterior, con una preferencia en de la aplicación `config.xml` archivo. Para ello, añada una de estas dos líneas a `config.xml` : + + + + + + +Sin esta línea, se utilizará el archivo plugin `Compatibility` como valor predeterminado. Si una etiqueta de preferencia está presente y no es uno de estos valores, no se iniciará la aplicación. + +Si su solicitud se ha enviado previamente a los usuarios, usando un mayor (1.0 pre) versión de este plugin y archivos almacenados en el sistema de ficheros persistente, entonces debería establecer la preferencia en `Compatibility` . Cambiar la ubicación para "Internal" significa que los usuarios existentes que actualización su aplicación pueden ser incapaces de acceder a sus archivos previamente almacenadas, dependiendo de su dispositivo. + +Si su solicitud es nuevo, o nunca antes ha almacenado archivos en el sistema de ficheros persistente, entonces el `Internal` generalmente se recomienda el ajuste. + +### Operaciones recursivas lento para /android_asset + +Listado de directorios activos es realmente lento en Android. Usted puede acelerar hacia arriba, agregando `src/android/build-extras.gradle` a la raíz de tu proyecto android (también requiere de cordova-android@4.0.0 o mayor). + +## iOS rarezas + + * `cordova.file.applicationStorageDirectory`es de sólo lectura; intentar almacenar archivos en el directorio raíz fallará. Utilice uno de los `cordova.file.*` las propiedades definidas para iOS (sólo `applicationDirectory` y `applicationStorageDirectory` son de sólo lectura). + * `FileReader.readAsText(blob, encoding)` + * El `encoding` no se admite el parámetro, y codificación UTF-8 es siempre en efecto. + +### iOS ubicación de almacenamiento persistente + +Hay dos ubicaciones válidas para almacenar archivos persistentes en un dispositivo iOS: el directorio de documentos y el directorio de biblioteca. Las versiones anteriores del plugin sólo almacenan archivos persistentes en el directorio de documentos. Esto tenía el efecto secundario de todos los archivos de la aplicación haciendo visible en iTunes, que era a menudo involuntarios, especialmente para aplicaciones que manejan gran cantidad de archivos pequeños, en lugar de producir documentos completos para la exportación, que es la finalidad del directorio. + +Ahora es posible elegir si desea almacenar archivos en los documentos o directorio de bibliotecas, con preferencia en de la aplicación `config.xml` archivo. Para ello, añada una de estas dos líneas a `config.xml` : + + + + + + +Sin esta línea, se utilizará el archivo plugin `Compatibility` como valor predeterminado. Si una etiqueta de preferencia está presente y no es uno de estos valores, no se iniciará la aplicación. + +Si su solicitud se ha enviado previamente a los usuarios, usando un mayor (1.0 pre) versión de este plugin y archivos almacenados en el sistema de ficheros persistente, entonces debería establecer la preferencia en `Compatibility` . Cambiar la ubicación de `Library` significa que los usuarios existentes que actualización su aplicación sería incapaces de acceder a sus archivos previamente almacenadas. + +Si su solicitud es nuevo, o nunca antes ha almacenado archivos en el sistema de ficheros persistente, entonces el `Library` generalmente se recomienda el ajuste. + +## Firefox OS rarezas + +La API de sistema de archivo de forma nativa no es compatible con Firefox OS y se implementa como una cuña en la parte superior indexedDB. + + * No falla cuando eliminar directorios no vacía + * No admite metadatos para directorios + * Los métodos `copyTo` y `moveTo` no son compatibles con directorios + +Se admiten las siguientes rutas de datos: * `applicationDirectory` -usa `xhr` para obtener los archivos locales que están envasados con la aplicación. * `dataDirectory` - Para archivos de datos específicos de aplicación persistente. * `cacheDirectory` -En caché archivos que deben sobrevivir se reinicia la aplicación (aplicaciones no deben confiar en el sistema operativo para eliminar archivos aquí). + +## Navegador rarezas + +### Rarezas y observaciones comunes + + * Cada navegador utiliza su propio sistema de ficheros un espacio aislado. IE y Firefox utilizan IndexedDB como base. Todos los navegadores utilizan diagonal como separador de directorio en un camino. + * Las entradas de directorio deben crearse sucesivamente. Por ejemplo, la llamada `fs.root.getDirectory (' dir1/dir2 ', {create:true}, successCallback, errorCallback)` se producirá un error si no existiera dir1. + * El plugin solicita permiso de usuario para usar almacenamiento persistente en el primer comienzo de la aplicación. + * Plugin soporta `cdvfile://localhost` (recursos locales) solamente. Es decir, no se admiten los recursos externos vía `cdvfile`. + * El plugin no sigue ["Archivo sistema API 8.3 nombrando restricciones"](http://www.w3.org/TR/2011/WD-file-system-api-20110419/#naming-restrictions). + * BLOB y archivo ' `close` la función no es compatible. + * `FileSaver` y `BlobBuilder` no son compatibles con este plugin y no tengo recibos. + * El plugin no es compatible con `requestAllFileSystems`. Esta función también está desaparecida en las especificaciones. + * No se quitarán las entradas de directorio Si utilizas `create: true` bandera de directorio existente. + * No se admiten archivos creados mediante el constructor. Debe utilizar método entry.file en su lugar. + * Cada navegador utiliza su propia forma de blob URL referencias. + * se admite la función `readAsDataURL`, pero el mediatype en cromo depende de la extensión de nombre de entrada, mediatype en IE siempre está vacío (que es lo mismo como `plain-text` según la especificación), el mediatype en Firefox siempre es `application/octet-stream`. Por ejemplo, si el contenido es `abcdefg` entonces Firefox devuelve `datos: aplicación / octet-stream; base64, YWJjZGVmZw ==`, es decir devuelve `datos:; base64, YWJjZGVmZw ==`, cromo devuelve `datos: < mediatype dependiendo de la extensión de nombre de la entrada >; base64, YWJjZGVmZw ==`. + * `toInternalURL` devuelve la ruta de la forma `file:///persistent/path/to/entry` (Firefox, IE). Cromo devuelve la ruta de acceso en el formulario `cdvfile://localhost/persistent/file`. + +### Rarezas de Chrome + + * Filesystem de Chrome no es inmediatamente después de evento ready dispositivo. Como solución temporal puede suscribirse al evento `filePluginIsReady`. Ejemplo: + +```javascript +window.addEventListener('filePluginIsReady', function(){ console.log('File plugin is ready');}, false); +``` + +Puede utilizar la función `window.isFilePluginReadyRaised` para verificar si ya se provoca el evento. -window.requestFileSystem temporal y persistente filesystem cuotas no están limitadas en cromo. -Para aumentar el almacenamiento persistente en cromo necesitas llamar el método `window.initPersistentFileSystem`. Cuota de almacenamiento persistente es de 5 MB por defecto. -Chrome requiere `--permitir-archivo-acceso-de-archivos` ejecutar argumento al soporte API mediante protocolo `file:///`. -`Archivo` objeto no cambiará si utilizas bandera `{create:true}` cuando una `entrada` de existente. -eventos `cancelable` propiedad está establecida en true en cromo. Esto es contrario a la [Especificación](http://dev.w3.org/2009/dap/file-system/file-writer.html). -función de `toURL` en Chrome devuelve `filesystem:`-prefijo camino dependiendo de host de la aplicación. Por ejemplo, `filesystem:file:///persistent/somefile.txt`, `filesystem:http://localhost:8080/persistent/somefile.txt`. -resultado de la función de `toURL` no contiene barra en caso de entrada en el directorio. Cromo resuelve directorios con urls slash-siguió correctamente sin embargo. -método `resolveLocalFileSystemURL` requiere la entrantes `url` que tienen prefijo `filesystem`. Por ejemplo, el parámetro de `url` para `resolveLocalFileSystemURL` debería estar en la forma `filesystem:file:///persistent/somefile.txt` en comparación con la forma `file:///persistent/somefile.txt` en Android. -Obsoleto `toNativeURL` función no es compatible y no tiene un trozo. -función de `setMetadata` no es indicada en las especificaciones y no admite. -INVALID_MODIFICATION_ERR (código: 9) se lanza en lugar de SYNTAX_ERR(code: 8) a petición de un sistema de ficheros inexistentes. -INVALID_MODIFICATION_ERR (código: 9) se lanza en vez de PATH_EXISTS_ERR(code: 12) en intentar exclusivamente crear un archivo o directorio, que ya existe. -INVALID_MODIFICATION_ERR (código: 9) se lanza en lugar de NO_MODIFICATION_ALLOWED_ERR(code: 6) para tratar de llamar a removeRecursively en el sistema de archivos raíz. -INVALID_MODIFICATION_ERR (código: 9) se lanza en vez de NOT_FOUND_ERR(code: 1) en tratar de moveTo directorio que no existe. + +### Impl base IndexedDB rarezas (IE y Firefox) + + * `.` y `..` no son compatibles. + * IE no soporta `file:///`-modo; modo alojado sólo es compatible (http://localhost:xxxx). + * Tamaño del sistema de archivos de Firefox no es limitada pero cada extensión de 50 MB solicitará un permiso de usuario. IE10 permite hasta 10mb de combinados AppCache y IndexedDB utilizados en la implementación del sistema de ficheros sin preguntar, cuando llegas a ese nivel que se le preguntará si desea permitir que ser aumentada hasta un máximo de 250 mb por sitio. Para que `size` parámetro para la función `requestFileSystem` no afecta sistema de ficheros en Firefox y IE. + * la función `readAsBinaryString` no se indica en las especificaciones y no compatible con IE y no tiene un trozo. + * `file.type` siempre es null. + * No debe crear entrada utilizando DirectoryEntry resultado de devolución de llamada de instancia que fue borrado. De lo contrario, obtendrá una entrada' colgar'. + * Antes de que se puede leer un archivo, el cual fue escrito sólo que necesitas una nueva instancia de este archivo. + * la función `setMetadata`, que no es indicada en las especificaciones soporta sólo el cambio de campo `modificationTime`. + * `copyTo` y `moveTo` funciones no son compatibles con directorios. + * Metadatos de directorios no es compatible. + * Tanto Entry.remove y directoryEntry.removeRecursively no fallan al retirar no vacía directorios - directorios de ser eliminados se limpian junto con contenido en su lugar. + * `abort` y `truncate` las funciones no son compatibles. + * eventos de progreso no están despedidos. Por ejemplo, este controlador no ejecutará: + +```javascript +writer.onprogress = function() { /*commands*/ }; +``` + +## Actualización de notas + +En v1.0.0 de este plugin, han cambiado las estructuras `FileEntry` y `DirectoryEntry`, para estar más acorde con las especificaciones publicadas. + +Versiones anteriores (pre-1.0.0) del plugin almacenan el dispositivo-absoluto-archivo-ubicación en la propiedad `fullPath` de objetos de `entrada`. Estos caminos típicamente parecería + + /var/mobile/Applications//Documents/path/to/file (iOS) + /storage/emulated/0/path/to/file (Android) + + +Estas rutas también fueron devueltos por el método `toURL()` de los objetos de `entrada`. + +Con v1.0.0, el atributo `fullPath` es la ruta del archivo, *relativo a la raíz del sistema de archivos HTML*. Así, los caminos más arriba sería ahora ambos ser representado por un objeto `FileEntry` con un `fullPath` de + + /path/to/file + + +Si su aplicación funciona con dispositivo-absoluto-caminos, y previamente obtenido esos caminos a través de la propiedad `fullPath` de objetos de `Entry`, deberá actualizar el código para utilizar `entry.toURL()` en su lugar. + +Para atrás compatibilidad, el método `resolveLocalFileSystemURL()` a aceptar un dispositivo-absoluto-trayectoria y devolverá un objeto de `Entry` correspondiente que, mientras exista ese archivo dentro de los sistemas de ficheros `TEMPORARY` o la `PERSISTENT`. + +Esto ha sido particularmente un problema con el plugin de transferencia de archivos, que anteriormente utilizado dispositivo-absoluto-caminos (y todavía puede aceptarlas). Ha sido actualizado para funcionar correctamente con sistema de ficheros URLs, para reemplazar `entry.fullPath` con `entry.toURL()` debe resolver cualquier problema conseguir ese plugin para trabajar con archivos en el dispositivo. + +En v1.1.0 el valor devuelto por `toURL()` fue cambiado (consulte \[CB-6394\] (https://issues.apache.org/jira/browse/CB-6394)) para devolver una dirección URL absoluta 'file://'. siempre que sea posible. Para asegurar una ' cdvfile:'-URL ahora puede utilizar `toInternalURL()`. Este método devolverá ahora filesystem URLs de la forma + + cdvfile://localhost/persistent/path/to/file + + +que puede utilizarse para identificar el archivo únicamente. + +## Lista de códigos de Error y significados + +Cuando se produce un error, uno de los siguientes códigos se utilizará. + +| Código | Constante | +| ------:|:----------------------------- | +| 1 | `NOT_FOUND_ERR` | +| 2 | `SECURITY_ERR` | +| 3 | `ABORT_ERR` | +| 4 | `NOT_READABLE_ERR` | +| 5 | `ENCODING_ERR` | +| 6 | `NO_MODIFICATION_ALLOWED_ERR` | +| 7 | `INVALID_STATE_ERR` | +| 8 | `SYNTAX_ERR` | +| 9 | `INVALID_MODIFICATION_ERR` | +| 10 | `QUOTA_EXCEEDED_ERR` | +| 11 | `TYPE_MISMATCH_ERR` | +| 12 | `PATH_EXISTS_ERR` | + +## Configurando el Plugin (opcional) + +El conjunto de los sistemas de ficheros disponibles puede ser configurado por plataforma. Tanto iOS y Android reconocen un etiqueta en el `archivo config.xml` que nombra a los sistemas de archivos para ser instalado. De forma predeterminada, se activan todas las raíces del sistema de archivos. + + + + + +### Android + + * `files`: directorio de almacenamiento de archivo interno de la aplicación + * `files-external`: directorio de almacenamiento de archivo externo de la aplicación + * `sdcard`: el directorio de almacenamiento de archivo externo global (esta es la raíz de la tarjeta SD, si uno está instalado). Debe tener el permiso de `android.permission.WRITE_EXTERNAL_STORAGE` a usar esto. + * `cache`: directorio de memoria caché interna de la aplicación + * `cache-external`: directorio de caché externo de la aplicación + * `root`: el sistema de archivos de todo el dispositivo + +Android también es compatible con un sistema de archivos especial llamado "documents", que representa un subdirectorio "/Documents/" dentro del sistema de archivos "archivos". + +### iOS + + * `library`: directorio de bibliotecas de la aplicación + * `documents`: directorio de documentos de la aplicación + * `cache`: directorio de caché de la aplicación + * `bundle`: paquete de la aplicación; la ubicación de la aplicación en sí mismo en el disco (sólo lectura) + * `root`: el sistema de archivos de todo el dispositivo + +De forma predeterminada, los directorios de documentos y la biblioteca pueden ser sincronizados con iCloud. También puede solicitar dos sistemas adicionales, `library-nosync` y `documents-nosync`, que representan un directorio especial no sincronizados dentro de la `/Library` o sistema de ficheros `/Documents`. \ No newline at end of file diff --git a/plugins/cordova-plugin-file/doc/es/index.md b/plugins/cordova-plugin-file/doc/es/index.md new file mode 100644 index 0000000..a9c0264 --- /dev/null +++ b/plugins/cordova-plugin-file/doc/es/index.md @@ -0,0 +1,336 @@ + + +# cordova-plugin-file + +Este plugin implementa una API de archivo que permite acceso de lectura/escritura a los archivos que residen en el dispositivo. + +Este plugin se basa en varias especificaciones, incluyendo: el HTML5 archivo API + +Los directorios (ahora extinto) y sistema de extensiones más recientes: aunque la mayor parte del código del plugin fue escrito cuando una especificación anterior era actual: + +También implementa la especificación de FileWriter: + +Para el uso, por favor, consulte 'HTML5 Rocks excelente [FileSystem artículo.][1] + + [1]: http://www.html5rocks.com/en/tutorials/file/filesystem/ + +Para tener una visión general de otras opciones de almacenamiento, consulte [Guía de almacenamiento Cordova][2]. + + [2]: http://cordova.apache.org/docs/en/edge/cordova_storage_storage.md.html + +Este plugin define global `cordova.file` objeto. + +Aunque en el ámbito global, no estará disponible hasta después de la `deviceready` evento. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(cordova.file); + } + + +## Instalación + + cordova plugin add cordova-plugin-file + + +## Plataformas soportadas + +* Amazon fire OS +* Android +* BlackBerry 10 +* Firefox OS +* iOS +* Windows Phone 7 y 8 * +* Windows 8 * +* Explorador + +* *No son compatibles con estas plataformas `FileReader.readAsArrayBuffer` ni `FileWriter.write(blob)` .* + +## Donde almacenar los archivos + +A partir de v1.2.0, URLs a directorios de sistema de archivos importantes son proporcionadas. Cada dirección URL está en la forma *file:///path/to/spot/*y se puede convertir en un `DirectoryEntry` usando`window.resolveLocalFileSystemURL()`. + +* `cordova.file.applicationDirectory`-Directorio Read-only donde está instalada la aplicación. (*iOS*, *Android*, *BlackBerry 10*) + +* `cordova.file.applicationStorageDirectory`-Directorio del entorno limitado de la aplicación; en iOS esta ubicación es de sólo lectura (pero subdirectorios específicos [como `/Documents` ] son de lectura y escritura). Todos los datos contenidos dentro es privado para la aplicación. ( *iOS*, *Android*, *BlackBerry 10*) + +* `cordova.file.dataDirectory`-Almacenamiento de datos persistente y privadas dentro de entorno limitado de la aplicación utilizando la memoria interna (en Android, si necesitas usar memoria externa, use `.externalDataDirectory` ). En iOS, este directorio no está sincronizado con iCloud (utilice `.syncedDataDirectory` ). (*iOS*, *Android*, *BlackBerry 10*) + +* `cordova.file.cacheDirectory`-Directorio para los archivos de datos almacenados en caché o los archivos que su aplicación puede volver a crear fácilmente. El sistema operativo puede borrar estos archivos cuando el dispositivo se agota en almacenamiento de información, sin embargo, aplicaciones no deben confiar en el sistema operativo para eliminar los archivos de aquí. (*iOS*, *Android*, *BlackBerry 10*) + +* `cordova.file.externalApplicationStorageDirectory`-Espacio aplicación de almacenamiento externo. (*Android*) + +* `cordova.file.externalDataDirectory`¿Dónde poner los archivos de datos específicos de la aplicación de almacenamiento externo. (*Android*) + +* `cordova.file.externalCacheDirectory`-Caché aplicación de almacenamiento externo. (*Android*) + +* `cordova.file.externalRootDirectory`-Raíz de almacenamiento externo (tarjeta SD). (*Android*, *BlackBerry 10*) + +* `cordova.file.tempDirectory`-Directorio temporal que puede borrar el sistema operativo en sí. No confíe en el sistema operativo para borrar este directorio; su aplicación siempre debe eliminar archivos según corresponda. (*iOS*) + +* `cordova.file.syncedDataDirectory`-Contiene los archivos de la aplicación específica que deben ser sincronizados (e.g. a iCloud). (*iOS*) + +* `cordova.file.documentsDirectory`-Archivos privados a la aplicación, pero que son significativos para otra aplicación (por ejemplo archivos de Office). (*iOS*) + +* `cordova.file.sharedDirectory`-Archivos disponibles globalmente para todas las aplicaciones (*BlackBerry 10*) + +## Diseños de sistema de archivo + +Aunque técnicamente un detalle de la implementación, puede ser muy útil saber cómo la `cordova.file.*` mapa de propiedades en trazados físicos en un dispositivo real. + +### iOS diseño de sistema de archivo + +| Ruta de dispositivo | `Cordova.file.*` | `iosExtraFileSystems` | ¿r/w? | ¿persistente? | OS despeja | sincronización | privado | +|:-------------------------------------------- |:--------------------------- |:--------------------- |:-----:|:-------------:|:----------:|:--------------:|:-------:| +| `/ var/mobile/Applications/< UUID > /` | applicationStorageDirectory | - | r | N / A | N / A | N / A | Sí | +|    `appname.app/` | applicationDirectory | Bundle | r | N / A | N / A | N / A | Sí | +|       `www/` | - | - | r | N / A | N / A | N / A | Sí | +|    `Documents/` | documentsDirectory | documentos | r/w | Sí | No | Sí | Sí | +|       `NoCloud/` | - | documentos-nosync | r/w | Sí | No | No | Sí | +|    `Library` | - | Biblioteca | r/w | Sí | No | ¿Sí? | Sí | +|       `NoCloud/` | dataDirectory | Biblioteca-nosync | r/w | Sí | No | No | Sí | +|       `Cloud/` | syncedDataDirectory | - | r/w | Sí | No | Sí | Sí | +|       `Caches/` | cacheDirectory | caché | r/w | Sí * | Si * * *| | No | Sí | +|    `tmp/` | tempDirectory | - | r/w | No * * | Si * * *| | No | Sí | + +* Archivos persisten a través de la aplicación se reinicia y actualizaciones, pero este directorio puede ser despejó cuando el OS desea. Su aplicación debe ser capaz de recrear cualquier contenido que puede ser eliminado. + +* * Archivos pueden persistir a través de la aplicación se reinicia, pero no confiar en este comportamiento. Los archivos no se garantizan que persisten a través de actualizaciones. Su aplicación debe eliminar los archivos de este directorio cuando es aplicable, como el sistema operativo no garantiza cuando (o incluso si) estos archivos se quitan. + +* * *| OS la puede borrar el contenido de este directorio cuando se siente que es necesario, pero no dependen de éste. Debe borrar este directorio según sea apropiado para su aplicación. + +### Disposición del sistema Android File + +| Ruta de dispositivo | `Cordova.file.*` | `AndroidExtraFileSystems` | ¿r/w? | ¿persistente? | OS despeja | privado | +|:----------------------------------------- |:----------------------------------- |:------------------------- |:-----:|:-------------:|:----------:|:-------:| +| `File:///android_asset/` | applicationDirectory | | r | N / A | N / A | Sí | +| `/Data/data/< id de aplicación > /` | applicationStorageDirectory | - | r/w | N / A | N / A | Sí | +|    `cache` | cacheDirectory | caché | r/w | Sí | Sí * | Sí | +|    `files` | dataDirectory | archivos | r/w | Sí | No | Sí | +|       `Documents` | | documentos | r/w | Sí | No | Sí | +| `< sdcard > /` | externalRootDirectory | sdcard | r/w | Sí | No | No | +|    `Android/data//` | externalApplicationStorageDirectory | - | r/w | Sí | No | No | +|       `cache` | externalCacheDirectry | caché-externo | r/w | Sí | No * * | No | +|       `files` | externalDataDirectory | archivos externos | r/w | Sí | No | No | + +* El sistema operativo puede eliminar periódicamente este directorio, pero no dependen de este comportamiento. Borrar el contenido de este directorio según sea apropiado para su aplicación. El contenido de este directorio debe un usuario purga la caché manualmente, se eliminan. + +* * El sistema operativo no borra este directorio automáticamente; Usted es responsable de administrar el contenido mismo. Deberá el usuario purga la caché manualmente, se extraen los contenidos del directorio. + +**Nota**: Si no se puede montar de almacenamiento externo, el `cordova.file.external*` Propiedades`null`. + +### Disposición del sistema blackBerry 10 archivo + +| Ruta de dispositivo | `Cordova.file.*` | ¿r/w? | ¿persistente? | OS despeja | privado | +|:------------------------------------------------------------- |:--------------------------- |:-----:|:-------------:|:----------:|:-------:| +| `File:///accounts/1000/AppData/ < id de aplicación > /` | applicationStorageDirectory | r | N / A | N / A | Sí | +|    `app/native` | applicationDirectory | r | N / A | N / A | Sí | +|    `data/webviews/webfs/temporary/local__0` | cacheDirectory | r/w | No | Sí | Sí | +|    `data/webviews/webfs/persistent/local__0` | dataDirectory | r/w | Sí | No | Sí | +| `File:///accounts/1000/Removable/sdcard` | externalRemovableDirectory | r/w | Sí | No | No | +| `File:///accounts/1000/shared` | sharedDirectory | r/w | Sí | No | No | + +*Nota*: cuando se implementa la aplicación al trabajo de perímetro, todos los caminos son relativos a /accounts/1000-enterprise. + +## Rarezas Android + +### Ubicación de almacenamiento persistente Android + +Hay múltiples ubicaciones válidas para almacenar archivos persistentes en un dispositivo Android. Vea [esta página][3] para una extensa discusión de las distintas posibilidades. + + [3]: http://developer.android.com/guide/topics/data/data-storage.html + +Las versiones anteriores del plugin elegiría la ubicación de los archivos temporales y persistentes en el arranque, basado en si el dispositivo afirmó que fue montado en la tarjeta SD (o partición de almacenamiento equivalente). Si fue montada en la tarjeta SD, o una partición de gran almacenamiento interno estaba disponible (como en dispositivos de Nexus,) y luego los archivos persistentes se almacenaría en la raíz de ese espacio. Esto significaba que todas las apps Cordova podían ver todos los archivos disponibles en la tarjeta. + +Si la tarjeta SD no estaba disponible, entonces versiones anteriores podría almacenar datos debajo de `/data/data/` , que aísla las apps del otro, pero puede todavía causa datos para ser compartido entre los usuarios. + +Ahora es posible elegir si desea almacenar archivos en la ubicación de almacenamiento del archivo interno, o usando la lógica anterior, con una preferencia en de la aplicación `config.xml` archivo. Para ello, añada una de estas dos líneas a `config.xml` : + + < nombre de preferencia = "AndroidPersistentFileLocation" value = "Internal" / >< nombre de preferencia = "AndroidPersistentFileLocation" value = "Compatibilidad" / > + + +Sin esta línea, se utilizará el archivo plugin `Compatibility` como valor predeterminado. Si una etiqueta de preferencia está presente y no es uno de estos valores, no se iniciará la aplicación. + +Si su solicitud se ha enviado previamente a los usuarios, usando un mayor (1.0 pre) versión de este plugin y archivos almacenados en el sistema de ficheros persistente, entonces debería establecer la preferencia en `Compatibility` . Cambiar la ubicación para "Internal" significa que los usuarios existentes que actualización su aplicación pueden ser incapaces de acceder a sus archivos previamente almacenadas, dependiendo de su dispositivo. + +Si su solicitud es nuevo, o nunca antes ha almacenado archivos en el sistema de ficheros persistente, entonces el `Internal` generalmente se recomienda el ajuste. + +## iOS rarezas + +* `cordova.file.applicationStorageDirectory`es de sólo lectura; intentar almacenar archivos en el directorio raíz fallará. Utilice uno de los `cordova.file.*` las propiedades definidas para iOS (sólo `applicationDirectory` y `applicationStorageDirectory` son de sólo lectura). +* `FileReader.readAsText(blob, encoding)` + * El `encoding` no se admite el parámetro, y codificación UTF-8 es siempre en efecto. + +### iOS ubicación de almacenamiento persistente + +Hay dos ubicaciones válidas para almacenar archivos persistentes en un dispositivo iOS: el directorio de documentos y el directorio de biblioteca. Las versiones anteriores del plugin sólo almacenan archivos persistentes en el directorio de documentos. Esto tenía el efecto secundario de todos los archivos de la aplicación haciendo visible en iTunes, que era a menudo involuntarios, especialmente para aplicaciones que manejan gran cantidad de archivos pequeños, en lugar de producir documentos completos para la exportación, que es la finalidad del directorio. + +Ahora es posible elegir si desea almacenar archivos en los documentos o directorio de bibliotecas, con preferencia en de la aplicación `config.xml` archivo. Para ello, añada una de estas dos líneas a `config.xml` : + + + + + + +Sin esta línea, se utilizará el archivo plugin `Compatibility` como valor predeterminado. Si una etiqueta de preferencia está presente y no es uno de estos valores, no se iniciará la aplicación. + +Si su solicitud se ha enviado previamente a los usuarios, usando un mayor (1.0 pre) versión de este plugin y archivos almacenados en el sistema de ficheros persistente, entonces debería establecer la preferencia en `Compatibility` . Cambiar la ubicación de `Library` significa que los usuarios existentes que actualización su aplicación sería incapaces de acceder a sus archivos previamente almacenadas. + +Si su solicitud es nuevo, o nunca antes ha almacenado archivos en el sistema de ficheros persistente, entonces el `Library` generalmente se recomienda el ajuste. + +## Firefox OS rarezas + +La API de sistema de archivo de forma nativa no es compatible con Firefox OS y se implementa como una cuña en la parte superior indexedDB. + +* No falla cuando eliminar directorios no vacía +* No admite metadatos para directorios +* Los métodos `copyTo` y `moveTo` no son compatibles con directorios + +Se admiten las siguientes rutas de datos: * `applicationDirectory` -usa `xhr` para obtener los archivos locales que están envasados con la aplicación. * `dataDirectory` - Para archivos de datos específicos de aplicación persistente. * `cacheDirectory` -En caché archivos que deben sobrevivir se reinicia la aplicación (aplicaciones no deben confiar en el sistema operativo para eliminar archivos aquí). + +## Navegador rarezas + +### Rarezas y observaciones comunes + +* Cada navegador utiliza su propio sistema de ficheros un espacio aislado. IE y Firefox utilizan IndexedDB como base. Todos los navegadores utilizan diagonal como separador de directorio en un camino. +* Las entradas de directorio deben crearse sucesivamente. Por ejemplo, la llamada `fs.root.getDirectory (' dir1/dir2 ', {create:true}, successCallback, errorCallback)` se producirá un error si no existiera dir1. +* El plugin solicita permiso de usuario para usar almacenamiento persistente en el primer comienzo de la aplicación. +* Plugin soporta `cdvfile://localhost` (recursos locales) solamente. Es decir, no se admiten los recursos externos vía `cdvfile`. +* El plugin no sigue ["Archivo sistema API 8.3 nombrando restricciones"][4]. +* BLOB y archivo ' `close` la función no es compatible. +* `FileSaver` y `BlobBuilder` no son compatibles con este plugin y no tengo recibos. +* El plugin no es compatible con `requestAllFileSystems`. Esta función también está desaparecida en las especificaciones. +* No se quitarán las entradas de directorio Si utilizas `create: true` bandera de directorio existente. +* No se admiten archivos creados mediante el constructor. Debe utilizar método entry.file en su lugar. +* Cada navegador utiliza su propia forma de blob URL referencias. +* se admite la función `readAsDataURL`, pero el mediatype en cromo depende de la extensión de nombre de entrada, mediatype en IE siempre está vacío (que es lo mismo como `plain-text` según la especificación), el mediatype en Firefox siempre es `application/octet-stream`. Por ejemplo, si el contenido es `abcdefg` entonces Firefox devuelve `datos: aplicación / octet-stream; base64, YWJjZGVmZw ==`, es decir devuelve `datos:; base64, YWJjZGVmZw ==`, cromo devuelve `datos: < mediatype dependiendo de la extensión de nombre de la entrada >; base64, YWJjZGVmZw ==`. +* `toInternalURL` devuelve la ruta de la forma `file:///persistent/path/to/entry` (Firefox, IE). Cromo devuelve la ruta de acceso en el formulario `cdvfile://localhost/persistent/file`. + + [4]: http://www.w3.org/TR/2011/WD-file-system-api-20110419/#naming-restrictions + +### Rarezas de Chrome + +* Filesystem de Chrome no es inmediatamente después de evento ready dispositivo. Como solución temporal puede suscribirse al evento `filePluginIsReady`. Ejemplo: + + javascript + window.addEventListener('filePluginIsReady', function(){ console.log('File plugin is ready');}, false); + + +Puede utilizar la función `window.isFilePluginReadyRaised` para verificar si ya se provoca el evento. -window.requestFileSystem temporal y persistente filesystem cuotas no están limitadas en cromo. -Para aumentar el almacenamiento persistente en cromo necesitas llamar el método `window.initPersistentFileSystem`. Cuota de almacenamiento persistente es de 5 MB por defecto. -Chrome requiere `--permitir-archivo-acceso-de-archivos` ejecutar argumento al soporte API mediante protocolo `file:///`. -`Archivo` objeto no cambiará si utilizas bandera `{create:true}` cuando una `entrada` de existente. -eventos `cancelable` propiedad está establecida en true en cromo. Esto es contrario a la [Especificación][5]. -función de `toURL` en Chrome devuelve `filesystem:`-prefijo camino dependiendo de host de la aplicación. Por ejemplo, `filesystem:file:///persistent/somefile.txt`, `filesystem:http://localhost:8080/persistent/somefile.txt`. -resultado de la función de `toURL` no contiene barra en caso de entrada en el directorio. Cromo resuelve directorios con urls slash-siguió correctamente sin embargo. -método `resolveLocalFileSystemURL` requiere la entrantes `url` que tienen prefijo `filesystem`. Por ejemplo, el parámetro de `url` para `resolveLocalFileSystemURL` debería estar en la forma `filesystem:file:///persistent/somefile.txt` en comparación con la forma `file:///persistent/somefile.txt` en Android. -Obsoleto `toNativeURL` función no es compatible y no tiene un trozo. -función de `setMetadata` no es indicada en las especificaciones y no admite. -INVALID_MODIFICATION_ERR (código: 9) se lanza en lugar de SYNTAX_ERR(code: 8) a petición de un sistema de ficheros inexistentes. -INVALID_MODIFICATION_ERR (código: 9) se lanza en vez de PATH_EXISTS_ERR(code: 12) en intentar exclusivamente crear un archivo o directorio, que ya existe. -INVALID_MODIFICATION_ERR (código: 9) se lanza en lugar de NO_MODIFICATION_ALLOWED_ERR(code: 6) para tratar de llamar a removeRecursively en el sistema de archivos raíz. -INVALID_MODIFICATION_ERR (código: 9) se lanza en vez de NOT_FOUND_ERR(code: 1) en tratar de moveTo directorio que no existe. + + [5]: http://dev.w3.org/2009/dap/file-system/file-writer.html + +### Impl base IndexedDB rarezas (IE y Firefox) + +* `.` y `..` no son compatibles. +* IE no soporta `file:///`-modo; modo alojado sólo es compatible (http://localhost:xxxx). +* Tamaño del sistema de archivos de Firefox no es limitada pero cada extensión de 50 MB solicitará un permiso de usuario. IE10 permite hasta 10mb de combinados AppCache y IndexedDB utilizados en la implementación del sistema de ficheros sin preguntar, cuando llegas a ese nivel que se le preguntará si desea permitir que ser aumentada hasta un máximo de 250 mb por sitio. Para que `size` parámetro para la función `requestFileSystem` no afecta sistema de ficheros en Firefox y IE. +* la función `readAsBinaryString` no se indica en las especificaciones y no compatible con IE y no tiene un trozo. +* `file.type` siempre es null. +* No debe crear entrada utilizando DirectoryEntry resultado de devolución de llamada de instancia que fue borrado. De lo contrario, obtendrá una entrada' colgar'. +* Antes de que se puede leer un archivo, el cual fue escrito sólo que necesitas una nueva instancia de este archivo. +* la función `setMetadata`, que no es indicada en las especificaciones soporta sólo el cambio de campo `modificationTime`. +* `copyTo` y `moveTo` funciones no son compatibles con directorios. +* Metadatos de directorios no es compatible. +* Tanto Entry.remove y directoryEntry.removeRecursively no fallan al retirar no vacía directorios - directorios de ser eliminados se limpian junto con contenido en su lugar. +* `abort` y `truncate` las funciones no son compatibles. +* eventos de progreso no están despedidos. Por ejemplo, este controlador no ejecutará: + + javascript + writer.onprogress = function() { /*commands*/ }; + + +## Actualización de notas + +En v1.0.0 de este plugin, han cambiado las estructuras `FileEntry` y `DirectoryEntry`, para estar más acorde con las especificaciones publicadas. + +Versiones anteriores (pre-1.0.0) del plugin almacenan el dispositivo-absoluto-archivo-ubicación en la propiedad `fullPath` de objetos de `entrada`. Estos caminos típicamente parecería + + /var/mobile/Applications//Documents/path/to/file (iOS) + /storage/emulated/0/path/to/file (Android) + + +Estas rutas también fueron devueltos por el método `toURL()` de los objetos de `entrada`. + +Con v1.0.0, el atributo `fullPath` es la ruta del archivo, *relativo a la raíz del sistema de archivos HTML*. Así, los caminos más arriba sería ahora ambos ser representado por un objeto `FileEntry` con un `fullPath` de + + /path/to/file + + +Si su aplicación funciona con dispositivo-absoluto-caminos, y previamente obtenido esos caminos a través de la propiedad `fullPath` de objetos de `Entry`, deberá actualizar el código para utilizar `entry.toURL()` en su lugar. + +Para atrás compatibilidad, el método `resolveLocalFileSystemURL()` a aceptar un dispositivo-absoluto-trayectoria y devolverá un objeto de `Entry` correspondiente que, mientras exista ese archivo dentro de los sistemas de ficheros `TEMPORARY` o la `PERSISTENT`. + +Esto ha sido particularmente un problema con el plugin de transferencia de archivos, que anteriormente utilizado dispositivo-absoluto-caminos (y todavía puede aceptarlas). Ha sido actualizado para funcionar correctamente con sistema de ficheros URLs, para reemplazar `entry.fullPath` con `entry.toURL()` debe resolver cualquier problema conseguir ese plugin para trabajar con archivos en el dispositivo. + +En v1.1.0 el valor devuelto por `toURL()` fue cambiado (consulte \[CB-6394\] (https://issues.apache.org/jira/browse/CB-6394)) para devolver una dirección URL absoluta 'file://'. siempre que sea posible. Para asegurar una ' cdvfile:'-URL ahora puede utilizar `toInternalURL()`. Este método devolverá ahora filesystem URLs de la forma + + cdvfile://localhost/persistent/path/to/file + + +que puede utilizarse para identificar el archivo únicamente. + +## Lista de códigos de Error y significados + +Cuando se produce un error, uno de los siguientes códigos se utilizará. + +| Código | Constante | +| ------:|:----------------------------- | +| 1 | `NOT_FOUND_ERR` | +| 2 | `SECURITY_ERR` | +| 3 | `ABORT_ERR` | +| 4 | `NOT_READABLE_ERR` | +| 5 | `ENCODING_ERR` | +| 6 | `NO_MODIFICATION_ALLOWED_ERR` | +| 7 | `INVALID_STATE_ERR` | +| 8 | `SYNTAX_ERR` | +| 9 | `INVALID_MODIFICATION_ERR` | +| 10 | `QUOTA_EXCEEDED_ERR` | +| 11 | `TYPE_MISMATCH_ERR` | +| 12 | `PATH_EXISTS_ERR` | + +## Configurando el Plugin (opcional) + +El conjunto de los sistemas de ficheros disponibles puede ser configurado por plataforma. Tanto iOS y Android reconocen un etiqueta en el `archivo config.xml` que nombra a los sistemas de archivos para ser instalado. De forma predeterminada, se activan todas las raíces del sistema de archivos. + + + + + +### Android + +* `files`: directorio de almacenamiento de archivo interno de la aplicación +* `files-external`: directorio de almacenamiento de archivo externo de la aplicación +* `sdcard`: el directorio de almacenamiento de archivo externo global (esta es la raíz de la tarjeta SD, si uno está instalado). Debe tener el permiso de `android.permission.WRITE_EXTERNAL_STORAGE` a usar esto. +* `cache`: directorio de memoria caché interna de la aplicación +* `cache-external`: directorio de caché externo de la aplicación +* `root`: el sistema de archivos de todo el dispositivo + +Android también es compatible con un sistema de archivos especial llamado "documents", que representa un subdirectorio "/Documents/" dentro del sistema de archivos "archivos". + +### iOS + +* `library`: directorio de bibliotecas de la aplicación +* `documents`: directorio de documentos de la aplicación +* `cache`: directorio de caché de la aplicación +* `bundle`: paquete de la aplicación; la ubicación de la aplicación en sí mismo en el disco (sólo lectura) +* `root`: el sistema de archivos de todo el dispositivo + +De forma predeterminada, los directorios de documentos y la biblioteca pueden ser sincronizados con iCloud. También puede solicitar dos sistemas adicionales, `library-nosync` y `documents-nosync`, que representan un directorio especial no sincronizados dentro de la `/Library` o sistema de ficheros `/Documents`. diff --git a/plugins/cordova-plugin-file/doc/es/plugins.md b/plugins/cordova-plugin-file/doc/es/plugins.md new file mode 100644 index 0000000..dace368 --- /dev/null +++ b/plugins/cordova-plugin-file/doc/es/plugins.md @@ -0,0 +1,101 @@ + + +# Notas para los desarrolladores del plugin + +Estas notas están pensadas principalmente para desarrolladores de Android y el iOS que quieran escribir plugins que interfaz con el sistema de ficheros usando el plugin del archivo. + +## Trabajar con URLs de sistema de archivo de Córdoba + +Desde la versión 1.0.0, este plugin ha utilizado las direcciones URL con un `cdvfile` plan para todas las comunicaciones sobre el puente, en lugar de exponer rutas de sistema de archivos de dispositivos raw para JavaScript. + +En el lado de JavaScript, esto significa que los objetos FileEntry y DirectoryEntry tienen un atributo fullPath que es relativo a la raíz del sistema de archivos HTML. Si JavaScript API de tu plugin acepta un objeto FileEntry o DirectoryEntry, usted debe llamar a `.toURL()` en ese objeto antes de pasar a través del puente al código nativo. + +### Conversión de cdvfile: / / URL al fileystem caminos + +Plugins que necesita escribir en el sistema de archivos puede convertir un archivo recibido sistema URL a una ubicación de sistema de archivos real. Hay varias formas de hacerlo, dependiendo de la plataforma nativa. + +Es importante recordar que no todos `cdvfile://` las direcciones URL son asignables a reales archivos en el dispositivo. Algunas URLs pueden referirse a activos en dispositivos que no están representadas por archivos, o incluso pueden hacer referencia a recursos remotos. Debido a estas posibilidades, plugins siempre debe comprobar si consiguen un resultado significativo cuando tratando de convertir las URL en trazados. + +#### Android + +En Android, el método más simple para convertir un `cdvfile://` URL a una ruta de sistema de archivos es utilizar `org.apache.cordova.CordovaResourceApi` . `CordovaResourceApi`tiene varios métodos que pueden manejar `cdvfile://` URL: + + webView es un miembro de la clase Plugin CordovaResourceApi resourceApi = webView.getResourceApi(); + + Obtener una URL file:/// representando este archivo en el dispositivo, / / o el mismo URL sin cambios si no se puede asignar a un archivo Uri fileURL = resourceApi.remapUri(Uri.parse(cdvfileURL)); + + +También es posible utilizar el plugin de archivos directamente: + + Import org.apache.cordova.file.FileUtils; + Import org.apache.cordova.file.FileSystem; + Import java.net.MalformedURLException; + + Obtener el archivo plugin desde el administrador de plugin FileUtils filePlugin = (FileUtils)webView.pluginManager.getPlugin("File"); + + Dada una URL, haz un camino para tratar de {camino de cadena = filePlugin.filesystemPathForURL(cdvfileURL);} catch (DD e) {/ / el sistema de archivos url no reconocida} + + +Para convertir de una ruta a un `cdvfile://` URL: + + Import org.apache.cordova.file.LocalFilesystemURL; + + Obtener un objeto LocalFilesystemURL para una ruta, / / o null si no se puede representar como una dirección URL cdvfile. + LocalFilesystemURL url = filePlugin.filesystemURLforLocalPath(path); + Obtener la representación string de la URL objeto String cdvfileURL = url.toString(); + + +Si tu plugin crea un archivo y desea devolver un objeto FileEntry para él, usar el plugin de archivos: + + Devolver una estructura JSON adecuado para volver a JavaScript, / / o null si este archivo no es representable como una dirección URL cdvfile. + JSONObject entrada = filePlugin.getEntryForFile(file); + + +#### iOS + +Cordova en iOS no utiliza la misma `CordovaResourceApi` concepto como Android. En iOS, debe usar el archivo plugin para convertir las direcciones URL y rutas de sistema de archivos. + + Obtener un objeto URL CDVFilesystem de una URL string CDVFilesystemURL * url = [CDVFilesystemURL fileSystemURLWithString:cdvfileURL]; + Obtener una ruta de acceso para el objeto URL, o nil si no puede ser asignado a una ruta de archivo NSString * = [filePlugin filesystemPathForURL:url]; + + + Obtener un objeto URL CDVFilesystem para una ruta, o / / nula si no se puede representar como una dirección URL cdvfile. + CDVFilesystemURL * url = [filePlugin fileSystemURLforLocalPath:path]; + Obtener la representación string de la URL objetos NSString * cdvfileURL = [enlace absoluteString]; + + +Si tu plugin crea un archivo y desea devolver un objeto FileEntry para él, usar el plugin de archivos: + + Obtener un objeto URL CDVFilesystem para una ruta, o / / nula si no se puede representar como una dirección URL cdvfile. + CDVFilesystemURL * url = [filePlugin fileSystemURLforLocalPath:path]; + Conseguir una estructura para volver a JavaScript NSDictionary * entrada = [filePlugin makeEntryForLocalURL:url] + + +#### JavaScript + +En JavaScript, para obtener un `cdvfile://` dirección URL de un objeto FileEntry o DirectoryEntry, simplemente llame al `.toURL()` en él: + + var cdvfileURL = entry.toURL(); + + +En manipuladores de la respuesta del plugin, para convertir de una estructura FileEntry devuelta a un objeto real de la entrada, su código de controlador debe importar el archivo plugin y crear un nuevo objeto: + + crear apropiado objeto var ingreso; + Si (entryStruct.isDirectory) {entrada = new DirectoryEntry (entryStruct.name, entryStruct.fullPath, FileSystem(entryStruct.filesystemName)) nuevo;} else {entrada = nuevo FileEntry (entryStruct.name, entryStruct.fullPath, nuevo FileSystem(entryStruct.filesystemName));} \ No newline at end of file diff --git a/plugins/cordova-plugin-file/doc/fr/README.md b/plugins/cordova-plugin-file/doc/fr/README.md new file mode 100644 index 0000000..6296a84 --- /dev/null +++ b/plugins/cordova-plugin-file/doc/fr/README.md @@ -0,0 +1,328 @@ + + +# cordova-plugin-file + +[![Build Status](https://travis-ci.org/apache/cordova-plugin-file.svg)](https://travis-ci.org/apache/cordova-plugin-file) + +Ce plugin implémente une API de fichier permettant l'accès en lecture/écriture aux fichiers qui résident sur le périphérique. + +Ce plugin est basé sur plusieurs spécifications, y compris : l'API de fichier HTML5 + +Les répertoires (aujourd'hui disparue) et le système des extensions plus récentes : bien que la plupart du code du plugin a été écrit quand une technique antérieure était en vigueur : + +Il met également en œuvre la spécification FileWriter : + +Pour son utilisation, veuillez vous reporter au HTML5 Rocks' excellent [article de système de fichiers.](http://www.html5rocks.com/en/tutorials/file/filesystem/) + +Pour un aperçu des autres options de stockage, consultez [guide d'entreposage de Cordova](http://cordova.apache.org/docs/en/edge/cordova_storage_storage.md.html). + +Ce plugin définit global `cordova.file` objet. + +Bien que dans la portée globale, il n'est pas disponible jusqu'après la `deviceready` événement. + + document.addEventListener (« deviceready », onDeviceReady, false) ; + function onDeviceReady() {console.log(cordova.file);} + + +## Installation + + cordova plugin add cordova-plugin-file + + +## Plates-formes supportées + + * Amazon Fire OS + * Android + * BlackBerry 10 + * Firefox OS + * iOS + * Windows Phone 7 et 8 * + * Windows 8 * + * Windows* + * Navigateur + +\* *These platforms do not support `FileReader.readAsArrayBuffer` nor `FileWriter.write(blob)`.* + +## Emplacement de stockage des fichiers + +À partir de v1.2.0, URL vers des répertoires de système de fichiers importants est fournis. Chaque URL est dans la forme *file:///path/to/spot/*et peut être converti en un `DirectoryEntry` à l'aide`window.resolveLocalFileSystemURL()`. + + * `cordova.file.applicationDirectory`-Lecture seule répertoire où l'application est installée. (*iOS*, *Android*, *BlackBerry 10*) + + * `cordova.file.applicationStorageDirectory`-Répertoire racine du bac à sable de l'application ; cet endroit est en lecture seule sur iOS (mais les sous-répertoires spécifiques [comme `/Documents` ] sont en lecture / écriture). Toutes les données qu'il contient est privé de l'application. ( *iOS*, *Android*, *BlackBerry 10*) + + * `cordova.file.dataDirectory`-Stockage des données persistants et privés au sein de bac à sable de l'application à l'aide de la mémoire interne (sur Android, si vous avez besoin d'utiliser une mémoire externe, utilisez `.externalDataDirectory` ). Sur iOS, ce répertoire n'est pas synchronisé avec iCloud (utiliser `.syncedDataDirectory` ). (*iOS*, *Android*, *BlackBerry 10*) + + * `cordova.file.cacheDirectory`-Répertoire pour les fichiers de données en mémoire cache ou les fichiers que votre application peut recréer facilement. L'OS peut supprimer ces fichiers lorsque l'appareil faiblit sur stockage, néanmoins, les applications ne doivent pas compter sur l'OS pour supprimer les fichiers ici. (*iOS*, *Android*, *BlackBerry 10*) + + * `cordova.file.externalApplicationStorageDirectory`-Espace l'application sur le stockage externe. (*Android*) + + * `cordova.file.externalDataDirectory`-Où placer les fichiers de données d'application spécifiques sur le stockage externe. (*Android*) + + * `cordova.file.externalCacheDirectory`-Cache de l'application sur le stockage externe. (*Android*) + + * `cordova.file.externalRootDirectory`-Racine de stockage externe (carte SD). (*Android*, *BlackBerry 10*) + + * `cordova.file.tempDirectory`-Répertoire temp que l'OS peut effacer à volonté. Ne comptez pas sur l'OS pour effacer ce répertoire ; votre application doit toujours supprimer les fichiers selon le cas. (*iOS*) + + * `cordova.file.syncedDataDirectory`-Contient des fichiers d'app spécifique qui doivent se synchroniser (par exemple à iCloud). (*iOS*) + + * `cordova.file.documentsDirectory`-Fichiers privés à l'app, mais qui sont significatives pour l'autre application (par exemple les fichiers Office). (*iOS*) + + * `cordova.file.sharedDirectory`-Fichiers disponibles globalement à toutes les applications (*BlackBerry 10*) + +## Structures de système de fichiers + +Bien que techniquement un détail d'implémentation, il peut être très utile de savoir comment les `cordova.file.*` carte de propriétés à des chemins d'accès physiques sur un périphérique réel. + +### iOS agencement de système de fichier + +| Chemin de l'unité | `Cordova.file.*` | `iosExtraFileSystems` | r/w ? | persistants ? | OS efface | Sync | privé | +|:---------------------------------------------- |:--------------------------- |:--------------------- |:-----:|:-------------:|:-------------:|:-----:|:-----:| +| `/ var/mobile/Applications/< UUID > /` | applicationStorageDirectory | - | r | N/A | N/A | N/A | Oui | +|    `appname.app/` | applicationDirectory | Bundle | r | N/A | N/A | N/A | Oui | +|       `www/` | - | - | r | N/A | N/A | N/A | Oui | +|    `Documents/` | documentsDirectory | documents | r/w | Oui | Non | Oui | Oui | +|       `NoCloud/` | - | documents-nosync | r/w | Oui | Non | Non | Oui | +|    `Library` | - | Bibliothèque | r/w | Oui | Non | Oui ? | Oui | +|       `NoCloud/` | dataDirectory | Bibliothèque-nosync | r/w | Oui | Non | Non | Oui | +|       `Cloud/` | syncedDataDirectory | - | r/w | Oui | Non | Oui | Oui | +|       `Caches/` | cacheDirectory | cache | r/w | Oui * | Oui**\* | Non | Oui | +|    `tmp/` | tempDirectory | - | r/w | Non** | Oui**\* | Non | Oui | + +\ * Fichiers persistent à travers l'application redémarre et mises à niveau, mais ce répertoire peut être effacé à chaque fois que le système d'exploitation désire. Votre application doit être en mesure de recréer tout contenu qui pourrait être supprimé. + +** Fichiers peuvent persister redémarrages de l'application, mais ne vous fiez pas ce comportement. Les fichiers ne sont pas garantis à persister dans l'ensemble de mises à jour. Votre application doit supprimer les fichiers de ce répertoire lorsqu'elle s'applique, comme le système d'exploitation ne garantit pas quand (ou même si) ces fichiers sont supprimés. + +**\ * Le système d'exploitation peut effacer le contenu de ce répertoire chaque fois qu'il se sent il est nécessaire, mais ne comptez pas là-dessus. Vous devez supprimer ce répertoire comme approprié pour votre application. + +### Agencement de système de fichiers Android + +| Chemin de l'unité | `Cordova.file.*` | `AndroidExtraFileSystems` | r/w ? | persistants ? | OS efface | privé | +|:------------------------------------------------ |:----------------------------------- |:------------------------- |:-----:|:-------------:|:---------:|:-----:| +| `file:///android_asset/` | applicationDirectory | | r | N/A | N/A | Oui | +| `/ données/data/app < id > /` | applicationStorageDirectory | - | r/w | N/A | N/A | Oui | +|    `cache` | cacheDirectory | cache | r/w | Oui | Oui\ * | Oui | +|    `files` | dataDirectory | fichiers | r/w | Oui | Non | Oui | +|       `Documents` | | documents | r/w | Oui | Non | Oui | +| `< sdcard > /` | externalRootDirectory | sdcard | r/w | Oui | Non | Non | +|    `Android/data//` | externalApplicationStorageDirectory | - | r/w | Oui | Non | Non | +|       `cache` | externalCacheDirectry | cache-externe | r/w | Oui | Non** | Non | +|       `files` | externalDataDirectory | fichiers externes | r/w | Oui | Non | Non | + +\ * L'OS peut effacer périodiquement ce répertoire, mais ne vous fiez pas ce comportement. Effacer le contenu de ce répertoire comme approprié pour votre application. Un utilisateur doit purger le cache manuellement, le contenu de ce répertoire est supprimé. + +** Le système d'exploitation n'efface pas ce répertoire automatiquement ; vous êtes chargé de gérer le contenu vous-même. L'utilisateur devrait purger le cache manuellement, le contenu du répertoire est supprimé. + +**Remarque**: si le stockage externe ne peut pas être monté, les `cordova.file.external*` sont des propriétés`null`. + +### Configuration du système blackBerry 10 fichier + +| Chemin de l'unité | `Cordova.file.*` | r/w ? | persistants ? | OS efface | privé | +|:----------------------------------------------------------- |:--------------------------- |:-----:|:-------------:|:---------:|:-----:| +| `file:///Accounts/1000/AppData/ < id app > /` | applicationStorageDirectory | r | N/A | N/A | Oui | +|    `app/native` | applicationDirectory | r | N/A | N/A | Oui | +|    `data/webviews/webfs/temporary/local__0` | cacheDirectory | r/w | Non | Oui | Oui | +|    `data/webviews/webfs/persistent/local__0` | dataDirectory | r/w | Oui | Non | Oui | +| `file:///Accounts/1000/Removable/sdcard` | externalRemovableDirectory | r/w | Oui | Non | Non | +| `file:///Accounts/1000/Shared` | sharedDirectory | r/w | Oui | Non | Non | + +*Remarque*: lorsque l'application est déployée dans le périmètre de travail, tous les chemins sont par rapport à /accounts/1000-enterprise. + +## Quirks Android + +### Emplacement de stockage persistant Android + +Il y a plusieurs emplacements valides pour stocker des fichiers persistants sur un appareil Android. Voir [cette page](http://developer.android.com/guide/topics/data/data-storage.html) pour une analyse approfondie des diverses possibilités. + +Les versions précédentes du plugin choisirait l'emplacement des fichiers temporaires et persistantes au démarrage, basé sur la question de savoir si le dispositif réclamé que la carte SD (ou une partition de stockage équivalent) a été montée. Si la carte SD a été montée, ou si une partition de stockage interne importante était disponible (comme sur les appareils Nexus,) puis les fichiers persistants seraient stockés dans la racine de cet espace. Cela signifie que toutes les apps de Cordova pouvaient voir tous les fichiers disponibles sur la carte. + +Si la carte SD n'était pas disponible, les versions précédentes pourraient stocker des données sous `/data/data/` , qui isole des apps de l'autre, mais peut encore cause données à partager entre les utilisateurs. + +Il est maintenant possible de choisir de stocker les fichiers dans l'emplacement de stockage de fichier interne, ou en utilisant la logique précédente, avec une préférence au sein de votre application `config.xml` fichier. Pour ce faire, ajoutez l'un de ces deux lignes de `config.xml` : + + < nom de l'option = « AndroidPersistentFileLocation » value = « Internal » / >< nom de préférence = « AndroidPersistentFileLocation » value = « Compatibilité » / > + + +Sans cette ligne, utilisera le fichier plugin `Compatibility` par défaut. Si une balise de préférence est présente et n'est pas une des valeurs suivantes, l'application ne démarrera pas. + +Si votre application a déjà été expédiée aux utilisateurs, en utilisant une ancienne (avant 1.0) version de ce plugin et dispose des fichiers stockés dans le système de fichiers persistant, alors vous devez définir la préférence au `Compatibility` . Commutation de l'emplacement « Internal » signifierait que les utilisateurs existants qui mettre à niveau leur application peuvent être impossible d'accéder à leurs fichiers déjà enregistrés, selon leur appareil. + +Si votre application est nouvelle ou a jamais précédemment stocké les fichiers dans le système de fichiers persistant, puis la `Internal` réglage est généralement recommandé. + +### Opérations récursives lent pour /android_asset + +Liste des répertoires actifs est vraiment lent sur Android. Vous pouvez accélérer il vers le haut, en ajoutant `src/android/build-extras.gradle` à la racine de votre projet android (requiert également cordova-android@4.0.0 ou supérieur). + +## Notes au sujet d'iOS + + * `cordova.file.applicationStorageDirectory`est en lecture seule ; tentative de stocker des fichiers dans le répertoire racine échoue. Utilisez l'une de l'autre `cordova.file.*` les propriétés définies pour iOS (seulement `applicationDirectory` et `applicationStorageDirectory` sont en lecture seule). + * `FileReader.readAsText(blob, encoding)` + * Le `encoding` paramètre n'est pas pris en charge, et le codage UTF-8 est toujours en vigueur. + +### emplacement de stockage persistant d'iOS + +Il y a deux emplacements valides pour stocker des fichiers persistants sur un appareil iOS : le répertoire de Documents et le répertoire de la bibliothèque. Les versions précédentes du plugin stockaient ne jamais fichiers persistants dans le répertoire de Documents. Cela a eu l'effet secondaire de rendre tous les fichiers de l'application visible dans iTunes, qui était souvent inattendus, en particulier pour les applications qui traitent beaucoup de petits fichiers, plutôt que de produire des documents complets destinés à l'exportation, qui est l'objectif visé par le répertoire. + +Il est maintenant possible de choisir de stocker les fichiers dans le répertoire de bibliothèque, avec une préférence au sein de votre application ou de documents `config.xml` fichier. Pour ce faire, ajoutez l'un de ces deux lignes de `config.xml` : + + < nom de l'option = « iosPersistentFileLocation » value = « Library » / >< nom de préférence = « iosPersistentFileLocation » value = « Compatibilité » / > + + +Sans cette ligne, utilisera le fichier plugin `Compatibility` par défaut. Si une balise de préférence est présente et n'est pas une des valeurs suivantes, l'application ne démarrera pas. + +Si votre application a déjà été expédiée aux utilisateurs, en utilisant une ancienne (avant 1.0) version de ce plugin et dispose des fichiers stockés dans le système de fichiers persistant, alors vous devez définir la préférence au `Compatibility` . Changer l'emplacement de `Library` voudrait dire que les utilisateurs existants qui mettre à niveau leur application serait incapables d'accéder à leurs fichiers déjà enregistrés. + +Si votre application est nouvelle ou a jamais précédemment stocké les fichiers dans le système de fichiers persistant, puis la `Library` réglage est généralement recommandé. + +## Firefox OS Quirks + +L'API de système de fichier n'est pas nativement pris en charge par Firefox OS et est implémentée comme une cale d'épaisseur sur le dessus d'indexedDB. + + * Ne manque pas lors de la suppression des répertoires non vide + * Ne supporte pas les métadonnées pour les répertoires + * Méthodes `copyTo` et `moveTo` ne prennent pas en charge les répertoires + +Les chemins de données suivants sont pris en charge: * `applicationDirectory` -utilise `xhr` pour obtenir des fichiers les qui sont emballées avec l'app. * `dataDirectory` - Pour les fichiers de données persistantes de app spécifique. * `cacheDirectory` -Mise en cache de fichiers qui doivent survivre les redémarrages de l'application (les applications ne doivent pas compter sur le système d'exploitation pour supprimer les fichiers ici). + +## Bizarreries navigateur + +### Commune de bizarreries et de remarques + + * Chaque navigateur utilise son propre système de fichiers en bac à sable. IE et Firefox utilisent IndexedDB comme base. Tous les navigateurs utilisent oblique comme séparateur de répertoire dans un chemin d'accès. + * Entrées d'annuaire doivent être créées successivement. Par exemple, l'appel `fs.root.getDirectory (' dir1/dir2 ', {create:true}, successCallback, errorCallback)` échouera si dir1 n'existait pas. + * Le plugin demande utilisateur l'autorisation d'utiliser le stockage persistant lors du premier démarrage d'application. + * Plugin supporte `cdvfile://localhost` (ressources locales) seulement. C'est-à-dire les ressources externes ne sont pas supportés par l'intermédiaire de `cdvfile`. + * Le plugin ne suit pas les ["Restrictions de nommage des fichiers système API 8.3"](http://www.w3.org/TR/2011/WD-file-system-api-20110419/#naming-restrictions). + * BLOB et le fichier "`close` la fonction n'est pas pris en charge. + * `FileSaver` et `BlobBuilder` ne sont pas pris en charge par ce plugin et n'ont stubs. + * Le plugin ne supporte pas les `requestAllFileSystems`. Cette fonction est également absent dans les cahier des charges. + * Inscriptions dans l'annuaire ne seront pas supprimées si vous utilisez `create: true` drapeau pour le répertoire existant. + * Fichiers créés via le constructeur ne sont pas pris en charge. Vous devez plutôt utiliser entry.file méthode. + * Chaque navigateur utilise sa propre forme de références URL blob. + * `readAsDataURL` fonction est prise en charge, mais le mediatype en Chrome dépend de l'extension entrée, mediatype dans IE est toujours vide (qui est le même que le `texte-plaine` selon la spécification), le mediatype dans Firefox est toujours `application/octet-stream`. Par exemple, si le contenu est `abcdefg` puis Firefox renvoie `données : application / octet-stream ; base64, YWJjZGVmZw ==`, c'est à dire les retours `données:; base64, YWJjZGVmZw ==`, retours de Chrome `données : < mediatype selon l'extension de nom d'entrée > ; base64, YWJjZGVmZw ==`. + * `toInternalURL` retourne le chemin d'accès dans le formulaire `file:///persistent/path/to/entry` (Firefox, IE). Chrome retourne le chemin d'accès dans le formulaire `cdvfile://localhost/persistent/file`. + +### Bizarreries de chrome + + * Chrome filesystem n'est pas prête immédiatement après l'événement ready périphérique. Pour contourner le problème, vous pouvez vous abonner à l'événement `filePluginIsReady`. Exemple : + +```javascript +window.addEventListener('filePluginIsReady', function(){ console.log('File plugin is ready');}, false); +``` + +Vous pouvez utiliser la fonction `window.isFilePluginReadyRaised` pour vérifier si les événement était déjà déclenché. -quotas de window.requestFileSystem temporaire et permanent de système de fichiers ne sont pas limités en Chrome. -Pour augmenter le stockage persistant en Chrome, vous devez appeler la méthode `window.initPersistentFileSystem`. Quota de stockage persistant est 5 Mo par défaut. -Chrome nécessite `--permettre-fichier-accès-de-fichiers` exécuter l'argument au support API via le protocole `file:///`. -`Fichier` objet changera pas si vous utilisez le drapeau `{create:true}` lors du passage d'une `entrée` existante. -événements `annulables` propriété a la valeur true dans Chrome. Il s'agit à l'encontre de la [spécification](http://dev.w3.org/2009/dap/file-system/file-writer.html). -`toURL` renvoie à Chrome `système de fichiers :`-préfixe de chemin d'accès selon l'application hôte. Par exemple, `filesystem:file:///persistent/somefile.txt`, `filesystem:http://localhost:8080/persistent/somefile.txt`. -résultat de la fonction `toURL` ne contient-elle pas de barre oblique dans le cas d'entrée d'annuaire. Chrome résout répertoires avec barre oblique-trainés URL correctement cependant. -`resolveLocalFileSystemURL` méthode nécessite l' entrant `url` préfixe de `système de fichiers`. Par exemple, le paramètre `d'url` pour `resolveLocalFileSystemURL` devrait être dans la forme `filesystem:file:///persistent/somefile.txt` par opposition à la forme `file:///persistent/somefile.txt` dans Android. -Déconseillée `toNativeURL` fonction n'est pas prise en charge et n'est pas une ébauche. -fonction de `setMetadata` n'est pas stipulée dans le devis et pas pris en charge. -INVALID_MODIFICATION_ERR (code: 9) est levée au lieu de SYNTAX_ERR(code: 8) sur la demande d'un système de fichier inexistant. -INVALID_MODIFICATION_ERR (code: 9) est levée au lieu de PATH_EXISTS_ERR(code: 12) à essayer de créer exclusivement un fichier ou un répertoire, qui existe déjà. -INVALID_MODIFICATION_ERR (code: 9) est levée au lieu de NO_MODIFICATION_ALLOWED_ERR(code: 6) à essayer d'appeler removeRecursively sur le système de fichiers racine. -INVALID_MODIFICATION_ERR (code: 9) est levée au lieu de NOT_FOUND_ERR(code: 1) en essayant de moveTo répertoire qui n'existe pas. + +### Base IndexedDB impl bizarreries (Firefox et IE) + + * `.` et `.` ne sont pas pris en charge. + * IE ne prend pas en charge les `file:///`-mode ; seul le mode hébergé est pris en charge (http://localhost:xxxx). + * Taille de système de fichiers de Firefox n'est pas limité, mais chaque extension de 50Mo demandera une autorisation de l'utilisateur. IE10 permet jusqu'à 10 Mo de combiné AppCache et IndexedDB utilisés dans la mise en œuvre du système de fichiers sans demander de confirmation, une fois que vous atteignez ce niveau, Qu'on vous demandera si vous souhaitez lui permettre d'être augmentée jusqu'à un maximum de 250 Mo par site. Si le paramètre de `taille` pour la fonction `requestFileSystem` n'affecte pas le système de fichiers dans Firefox et IE. + * fonction de `readAsBinaryString` n'est pas indiquée dans les spécifications et pas pris en charge dans Internet Explorer et n'a pas une ébauche. + * `file.type` est toujours null. + * Vous ne devez pas créer en utilisant le résultat du callback instance DirectoryEntry qui avait été supprimée. Sinon, vous obtiendrez une « entrée de pendaison ». + * Avant que vous pouvez lire un fichier qui a été écrit juste que vous devez obtenir une nouvelle instance de ce fichier. + * `setMetadata` fonction, qui n'est pas indiquée dans les spécifications supporte `modificationTime` changement de champ seulement. + * fonctions `copyTo` et `moveTo` ne supportent pas les répertoires. + * Répertoires métadonnées ne sont pas pris en charge. + * Les deux Entry.remove et directoryEntry.removeRecursively ne manquent pas lors de la suppression des répertoires non-vides - répertoires retirés sont nettoyés avec contenu au lieu de cela. + * fonctions `abort` et `truncate` ne sont pas supportées. + * événements de progression ne sont pas déclenchés. Par exemple, ce gestionnaire ne sera pas exécuté : + +```javascript +writer.onprogress = function() { /*commands*/ }; +``` + +## Notes de mise à niveau + +V1.0.0 de ce plugin, les structures `FileEntry` et `DirectoryEntry` ont changé, pour être plus conforme à la spécification publiée. + +Les versions précédentes de (pré-1.0.0) du plugin stockaient le dispositif-absolu--emplacement du fichier dans la propriété `fullPath` d'objets `d'entrée`. Ces chemins seraient présente généralement comme + + / var/mobile/Applications/< application UUID >/Documents/chemin/vers/fichier (iOS), /storage/emulated/0/path/to/file (Android) + + +Ces chemins ont été également retournés par la méthode de `toURL()` les objets `d'entrée`. + +Avec v1.0.0, l'attribut `fullPath` est le chemin d'accès au fichier, *par rapport à la racine du système de fichiers HTML*. Ainsi, les chemins d'accès ci-dessus seraient maintenant tous les deux être représentée par un objet `FileEntry` avec un `fullPath` de + + /path/to/file + + +Si votre application fonctionne avec le dispositif-absolu-chemins et que vous avez récupéré précédemment ces chemins d'accès par le biais de la propriété `fullPath` d'objets `d'entrée`, puis vous devez mettre à jour votre code afin d'utiliser `entry.toURL()` à la place. + +Pour vers l'arrière la compatibilité, la méthode `resolveLocalFileSystemURL()` sera un chemin absolu de l'unité et retourne un objet `Entry` correspondant à elle, tant que ce fichier existe au sein des systèmes de fichiers les `TEMPORARY` ou `PERSISTENT`. + +Cela a été particulièrement un problème avec le plugin de transfert de fichiers, qui autrefois périphérique-absolu-chemins (et peut encore accepter). Il a été mis à jour pour fonctionner correctement avec le système de fichiers URL, afin de remplacer `entry.fullPath` par `entry.toURL()` devrait résoudre tout problème obtenir ce plugin pour travailler avec des fichiers sur le périphérique. + +Dans v1.1.0 la valeur de retour de `toURL()` a été changée (voir \[CB-6394\] (https://issues.apache.org/jira/browse/CB-6394)) pour renvoyer une URL absolue "file://". dans la mesure du possible. Pour assurer un ' cdvfile:'-URL, vous pouvez utiliser `toInternalURL()` maintenant. Cette méthode retourne maintenant filesystem URL du formulaire + + cdvfile://localhost/persistent/path/to/file + + +qui peut servir à identifier de manière unique le fichier. + +## Liste des Codes d'erreur et leur signification + +Lorsqu'une erreur est levée, l'un des codes suivants sera utilisé. + +| Code | Constant | +| ----:|:----------------------------- | +| 1 | `NOT_FOUND_ERR` | +| 2 | `SECURITY_ERR` | +| 3 | `ABORT_ERR` | +| 4 | `NOT_READABLE_ERR` | +| 5 | `ENCODING_ERR` | +| 6 | `NO_MODIFICATION_ALLOWED_ERR` | +| 7 | `INVALID_STATE_ERR` | +| 8 | `SYNTAX_ERR` | +| 9 | `INVALID_MODIFICATION_ERR` | +| 10 | `QUOTA_EXCEEDED_ERR` | +| 11 | `TYPE_MISMATCH_ERR` | +| 12 | `PATH_EXISTS_ERR` | + +## Configuration du Plugin (facultatif) + +L'ensemble des systèmes de fichiers disponibles peut être configurée par plate-forme. Les iOS et Android reconnaissent une balise dans le `fichier config.xml` qui nomme les systèmes de fichiers à installer. Par défaut, toutes les racines du système de fichiers sont activées. + + + + + +### Android + + * `files` : répertoire de stockage de fichier interne de l'application + * `files-external` : répertoire de l'application de stockage de fichier externe + * `sdcard` : le répertoire de stockage global fichier externe (c'est la racine de la carte SD, s'il est installé). Vous devez avoir la permission de `android.permission.WRITE_EXTERNAL_STORAGE` de l'utiliser. + * `cache` : répertoire de cache interne de l'application + * `cache-external` : répertoire de cache externe de l'application + * `root` : le système de fichiers de tout dispositif + +Android prend également en charge un système de fichiers spécial nommé « documents », qui représente un sous-répertoire « / Documents / » dans le système de fichiers « files ». + +### iOS + + * `library` : répertoire de bibliothèque de l'application + * `documents` : répertoire de Documents de l'application + * `cache` : répertoire de Cache de l'application + * `bundle` : bundle de l'application ; l'emplacement de l'application elle-même sur disque (lecture seule) + * `root` : le système de fichiers de tout dispositif + +Par défaut, vous peuvent synchroniser les répertoires de la bibliothèque et les documents à iCloud. Vous pouvez également demander des deux systèmes de fichiers supplémentaires, `library-nosync` et `documents-nosync`, qui représentent un répertoire spécial non synchronisées dans le `/Library` ou système de fichiers `/ Documents`. \ No newline at end of file diff --git a/plugins/cordova-plugin-file/doc/fr/index.md b/plugins/cordova-plugin-file/doc/fr/index.md new file mode 100644 index 0000000..7235522 --- /dev/null +++ b/plugins/cordova-plugin-file/doc/fr/index.md @@ -0,0 +1,331 @@ + + +# cordova-plugin-file + +Ce plugin implémente une API de fichier permettant l'accès en lecture/écriture aux fichiers qui résident sur le périphérique. + +Ce plugin est basé sur plusieurs spécifications, y compris : l'API de fichier HTML5 + +Les répertoires (aujourd'hui disparue) et le système des extensions plus récentes : bien que la plupart du code du plugin a été écrit quand une technique antérieure était en vigueur : + +Il met également en œuvre la spécification FileWriter : + +Pour son utilisation, veuillez vous reporter au HTML5 Rocks' excellent [article de système de fichiers.][1] + + [1]: http://www.html5rocks.com/en/tutorials/file/filesystem/ + +Pour un aperçu des autres options de stockage, consultez [guide d'entreposage de Cordova][2]. + + [2]: http://cordova.apache.org/docs/en/edge/cordova_storage_storage.md.html + +Ce plugin définit global `cordova.file` objet. + +Bien que dans la portée globale, il n'est pas disponible jusqu'après la `deviceready` événement. + + document.addEventListener (« deviceready », onDeviceReady, false) ; + function onDeviceReady() {console.log(cordova.file);} + + +## Installation + + Cordova plugin ajouter cordova-plugin-file + + +## Plates-formes prises en charge + +* Amazon Fire OS +* Android +* BlackBerry 10 +* Firefox OS +* iOS +* Windows Phone 7 et 8 * +* Windows 8 * +* Navigateur + +* *Ces plates-formes ne supportent pas `FileReader.readAsArrayBuffer` ni `FileWriter.write(blob)` .* + +## Emplacement de stockage des fichiers + +À partir de v1.2.0, URL vers des répertoires de système de fichiers importants est fournis. Chaque URL est dans la forme *file:///path/to/spot/*et peut être converti en un `DirectoryEntry` à l'aide`window.resolveLocalFileSystemURL()`. + +* `cordova.file.applicationDirectory`-Lecture seule répertoire où l'application est installée. (*iOS*, *Android*, *BlackBerry 10*) + +* `cordova.file.applicationStorageDirectory`-Répertoire racine du bac à sable de l'application ; cet endroit est en lecture seule sur iOS (mais les sous-répertoires spécifiques [comme `/Documents` ] sont en lecture / écriture). Toutes les données qu'il contient est privé de l'application. ( *iOS*, *Android*, *BlackBerry 10*) + +* `cordova.file.dataDirectory`-Stockage des données persistants et privés au sein de bac à sable de l'application à l'aide de la mémoire interne (sur Android, si vous avez besoin d'utiliser une mémoire externe, utilisez `.externalDataDirectory` ). Sur iOS, ce répertoire n'est pas synchronisé avec iCloud (utiliser `.syncedDataDirectory` ). (*iOS*, *Android*, *BlackBerry 10*) + +* `cordova.file.cacheDirectory`-Répertoire pour les fichiers de données en mémoire cache ou les fichiers que votre application peut recréer facilement. L'OS peut supprimer ces fichiers lorsque l'appareil faiblit sur stockage, néanmoins, les applications ne doivent pas compter sur l'OS pour supprimer les fichiers ici. (*iOS*, *Android*, *BlackBerry 10*) + +* `cordova.file.externalApplicationStorageDirectory`-Espace l'application sur le stockage externe. (*Android*) + +* `cordova.file.externalDataDirectory`-Où placer les fichiers de données d'application spécifiques sur le stockage externe. (*Android*) + +* `cordova.file.externalCacheDirectory`-Cache de l'application sur le stockage externe. (*Android*) + +* `cordova.file.externalRootDirectory`-Racine de stockage externe (carte SD). (*Android*, *BlackBerry 10*) + +* `cordova.file.tempDirectory`-Répertoire temp que l'OS peut effacer à volonté. Ne comptez pas sur l'OS pour effacer ce répertoire ; votre application doit toujours supprimer les fichiers selon le cas. (*iOS*) + +* `cordova.file.syncedDataDirectory`-Contient des fichiers d'app spécifique qui doivent se synchroniser (par exemple à iCloud). (*iOS*) + +* `cordova.file.documentsDirectory`-Fichiers privés à l'app, mais qui sont significatives pour l'autre application (par exemple les fichiers Office). (*iOS*) + +* `cordova.file.sharedDirectory`-Fichiers disponibles globalement à toutes les applications (*BlackBerry 10*) + +## Structures de système de fichiers + +Bien que techniquement un détail d'implémentation, il peut être très utile de savoir comment les `cordova.file.*` carte de propriétés à des chemins d'accès physiques sur un périphérique réel. + +### iOS agencement de système de fichier + +| Chemin de l'unité | `Cordova.file.*` | `iosExtraFileSystems` | r/w ? | persistants ? | OS efface | Sync | privé | +|:-------------------------------------------- |:--------------------------- |:--------------------- |:-----:|:-------------:|:-----------:|:-----:|:-----:| +| `/ var/mobile/Applications/< UUID > /` | applicationStorageDirectory | - | r | N/A | N/A | N/A | Oui | +|    `appname.app/` | applicationDirectory | Bundle | r | N/A | N/A | N/A | Oui | +|       `www/` | - | - | r | N/A | N/A | N/A | Oui | +|    `Documents/` | documentsDirectory | documents | r/w | Oui | Non | Oui | Oui | +|       `NoCloud/` | - | documents-nosync | r/w | Oui | Non | Non | Oui | +|    `Library` | - | Bibliothèque | r/w | Oui | Non | Oui ? | Oui | +|       `NoCloud/` | dataDirectory | Bibliothèque-nosync | r/w | Oui | Non | Non | Oui | +|       `Cloud/` | syncedDataDirectory | - | r/w | Oui | Non | Oui | Oui | +|       `Caches/` | cacheDirectory | cache | r/w | Oui * | Oui * * *| | Non | Oui | +|    `tmp/` | tempDirectory | - | r/w | Ne * * | Oui * * *| | Non | Oui | + +* Fichiers persistent à travers les redémarrages de l'application et mises à niveau, mais ce répertoire peut être effacé à chaque fois que les désirs de l'OS. Votre application doit être en mesure de recréer tout contenu qui pourrait être supprimé. + +* * Fichiers peuvent persister redémarrages de l'application, mais ne vous fiez pas ce comportement. Les fichiers ne sont pas garantis à persister dans l'ensemble de mises à jour. Votre application doit supprimer les fichiers de ce répertoire lorsqu'elle s'applique, comme le système d'exploitation ne garantit pas quand (ou même si) ces fichiers sont supprimés. + +* * *| L'OS peut effacer le contenu de ce répertoire chaque fois qu'il se sent il est nécessaire, mais ne comptez pas là-dessus. Vous devez supprimer ce répertoire comme approprié pour votre application. + +### Agencement de système de fichiers Android + +| Chemin de l'unité | `Cordova.file.*` | `AndroidExtraFileSystems` | r/w ? | persistants ? | OS efface | privé | +|:----------------------------------- |:----------------------------------- |:------------------------- |:-----:|:-------------:|:---------:|:-----:| +| `file:///android_asset/` | applicationDirectory | | r | N/A | N/A | Oui | +| `/ données/data/app < id > /` | applicationStorageDirectory | - | r/w | N/A | N/A | Oui | +|    `cache` | cacheDirectory | cache | r/w | Oui | Oui * | Oui | +|    `files` | dataDirectory | fichiers | r/w | Oui | Non | Oui | +|       `Documents` | | documents | r/w | Oui | Non | Oui | +| `< sdcard > /` | externalRootDirectory | sdcard | r/w | Oui | Non | Non | +|    `Android/data//` | externalApplicationStorageDirectory | - | r/w | Oui | Non | Non | +|       `cache` | externalCacheDirectry | cache-externe | r/w | Oui | Ne * * | Non | +|       `files` | externalDataDirectory | fichiers externes | r/w | Oui | Non | Non | + +* Le système d'exploitation peut effacer périodiquement ce répertoire, mais ne vous fiez pas ce comportement. Effacer le contenu de ce répertoire comme approprié pour votre application. Un utilisateur doit purger le cache manuellement, le contenu de ce répertoire est supprimé. + +* * The OS vous n'effacez pas ce répertoire automatiquement ; vous êtes chargé de gérer le contenu vous-même. L'utilisateur devrait purger le cache manuellement, le contenu du répertoire est supprimé. + +**Remarque**: si le stockage externe ne peut pas être monté, les `cordova.file.external*` sont des propriétés`null`. + +### Configuration du système blackBerry 10 fichier + +| Chemin de l'unité | `Cordova.file.*` | r/w ? | persistants ? | OS efface | privé | +|:--------------------------------------------------- |:--------------------------- |:-----:|:-------------:|:---------:|:-----:| +| `file:///Accounts/1000/AppData/ < id app > /` | applicationStorageDirectory | r | N/A | N/A | Oui | +|    `app/native` | applicationDirectory | r | N/A | N/A | Oui | +|    `data/webviews/webfs/temporary/local__0` | cacheDirectory | r/w | Non | Oui | Oui | +|    `data/webviews/webfs/persistent/local__0` | dataDirectory | r/w | Oui | Non | Oui | +| `file:///Accounts/1000/Removable/sdcard` | externalRemovableDirectory | r/w | Oui | Non | Non | +| `file:///Accounts/1000/Shared` | sharedDirectory | r/w | Oui | Non | Non | + +*Remarque*: lorsque l'application est déployée dans le périmètre de travail, tous les chemins sont par rapport à /accounts/1000-enterprise. + +## Quirks Android + +### Emplacement de stockage persistant Android + +Il y a plusieurs emplacements valides pour stocker des fichiers persistants sur un appareil Android. Voir [cette page][3] pour une analyse approfondie des diverses possibilités. + + [3]: http://developer.android.com/guide/topics/data/data-storage.html + +Les versions précédentes du plugin choisirait l'emplacement des fichiers temporaires et persistantes au démarrage, basé sur la question de savoir si le dispositif réclamé que la carte SD (ou une partition de stockage équivalent) a été montée. Si la carte SD a été montée, ou si une partition de stockage interne importante était disponible (comme sur les appareils Nexus,) puis les fichiers persistants seraient stockés dans la racine de cet espace. Cela signifie que toutes les apps de Cordova pouvaient voir tous les fichiers disponibles sur la carte. + +Si la carte SD n'était pas disponible, les versions précédentes pourraient stocker des données sous `/data/data/` , qui isole des apps de l'autre, mais peut encore cause données à partager entre les utilisateurs. + +Il est maintenant possible de choisir de stocker les fichiers dans l'emplacement de stockage de fichier interne, ou en utilisant la logique précédente, avec une préférence au sein de votre application `config.xml` fichier. Pour ce faire, ajoutez l'un de ces deux lignes de `config.xml` : + + < nom de l'option = « AndroidPersistentFileLocation » value = « Internal » / >< nom de préférence = « AndroidPersistentFileLocation » value = « Compatibilité » / > + + +Sans cette ligne, utilisera le fichier plugin `Compatibility` par défaut. Si une balise de préférence est présente et n'est pas une des valeurs suivantes, l'application ne démarrera pas. + +Si votre application a déjà été expédiée aux utilisateurs, en utilisant une ancienne (avant 1.0) version de ce plugin et dispose des fichiers stockés dans le système de fichiers persistant, alors vous devez définir la préférence au `Compatibility` . Commutation de l'emplacement « Internal » signifierait que les utilisateurs existants qui mettre à niveau leur application peuvent être impossible d'accéder à leurs fichiers déjà enregistrés, selon leur appareil. + +Si votre application est nouvelle ou a jamais précédemment stocké les fichiers dans le système de fichiers persistant, puis la `Internal` réglage est généralement recommandé. + +## iOS Quirks + +* `cordova.file.applicationStorageDirectory`est en lecture seule ; tentative de stocker des fichiers dans le répertoire racine échoue. Utilisez l'une de l'autre `cordova.file.*` les propriétés définies pour iOS (seulement `applicationDirectory` et `applicationStorageDirectory` sont en lecture seule). +* `FileReader.readAsText(blob, encoding)` + * Le `encoding` paramètre n'est pas pris en charge, et le codage UTF-8 est toujours en vigueur. + +### emplacement de stockage persistant d'iOS + +Il y a deux emplacements valides pour stocker des fichiers persistants sur un appareil iOS : le répertoire de Documents et le répertoire de la bibliothèque. Les versions précédentes du plugin stockaient ne jamais fichiers persistants dans le répertoire de Documents. Cela a eu l'effet secondaire de rendre tous les fichiers de l'application visible dans iTunes, qui était souvent inattendus, en particulier pour les applications qui traitent beaucoup de petits fichiers, plutôt que de produire des documents complets destinés à l'exportation, qui est l'objectif visé par le répertoire. + +Il est maintenant possible de choisir de stocker les fichiers dans le répertoire de bibliothèque, avec une préférence au sein de votre application ou de documents `config.xml` fichier. Pour ce faire, ajoutez l'un de ces deux lignes de `config.xml` : + + < nom de l'option = « iosPersistentFileLocation » value = « Library » / >< nom de préférence = « iosPersistentFileLocation » value = « Compatibilité » / > + + +Sans cette ligne, utilisera le fichier plugin `Compatibility` par défaut. Si une balise de préférence est présente et n'est pas une des valeurs suivantes, l'application ne démarrera pas. + +Si votre application a déjà été expédiée aux utilisateurs, en utilisant une ancienne (avant 1.0) version de ce plugin et dispose des fichiers stockés dans le système de fichiers persistant, alors vous devez définir la préférence au `Compatibility` . Changer l'emplacement de `Library` voudrait dire que les utilisateurs existants qui mettre à niveau leur application serait incapables d'accéder à leurs fichiers déjà enregistrés. + +Si votre application est nouvelle ou a jamais précédemment stocké les fichiers dans le système de fichiers persistant, puis la `Library` réglage est généralement recommandé. + +## Firefox OS Quirks + +L'API de système de fichier n'est pas nativement pris en charge par Firefox OS et est implémentée comme une cale d'épaisseur sur le dessus d'indexedDB. + +* Ne manque pas lors de la suppression des répertoires non vide +* Ne supporte pas les métadonnées pour les répertoires +* Méthodes `copyTo` et `moveTo` ne prennent pas en charge les répertoires + +Les chemins de données suivants sont pris en charge: * `applicationDirectory` -utilise `xhr` pour obtenir des fichiers les qui sont emballées avec l'app. * `dataDirectory` - Pour les fichiers de données persistantes de app spécifique. * `cacheDirectory` -Mise en cache de fichiers qui doivent survivre les redémarrages de l'application (les applications ne doivent pas compter sur le système d'exploitation pour supprimer les fichiers ici). + +## Bizarreries navigateur + +### Commune de bizarreries et de remarques + +* Chaque navigateur utilise son propre système de fichiers en bac à sable. IE et Firefox utilisent IndexedDB comme base. Tous les navigateurs utilisent oblique comme séparateur de répertoire dans un chemin d'accès. +* Entrées d'annuaire doivent être créées successivement. Par exemple, l'appel `fs.root.getDirectory (' dir1/dir2 ', {create:true}, successCallback, errorCallback)` échouera si dir1 n'existait pas. +* Le plugin demande utilisateur l'autorisation d'utiliser le stockage persistant lors du premier démarrage d'application. +* Plugin supporte `cdvfile://localhost` (ressources locales) seulement. C'est-à-dire les ressources externes ne sont pas supportés par l'intermédiaire de `cdvfile`. +* Le plugin ne suit pas les ["Restrictions de nommage des fichiers système API 8.3"][4]. +* BLOB et le fichier "`close` la fonction n'est pas pris en charge. +* `FileSaver` et `BlobBuilder` ne sont pas pris en charge par ce plugin et n'ont stubs. +* Le plugin ne supporte pas les `requestAllFileSystems`. Cette fonction est également absent dans les cahier des charges. +* Inscriptions dans l'annuaire ne seront pas supprimées si vous utilisez `create: true` drapeau pour le répertoire existant. +* Fichiers créés via le constructeur ne sont pas pris en charge. Vous devez plutôt utiliser entry.file méthode. +* Chaque navigateur utilise sa propre forme de références URL blob. +* `readAsDataURL` fonction est prise en charge, mais le mediatype en Chrome dépend de l'extension entrée, mediatype dans IE est toujours vide (qui est le même que le `texte-plaine` selon la spécification), le mediatype dans Firefox est toujours `application/octet-stream`. Par exemple, si le contenu est `abcdefg` puis Firefox renvoie `données : application / octet-stream ; base64, YWJjZGVmZw ==`, c'est à dire les retours `données:; base64, YWJjZGVmZw ==`, retours de Chrome `données : < mediatype selon l'extension de nom d'entrée > ; base64, YWJjZGVmZw ==`. +* `toInternalURL` retourne le chemin d'accès dans le formulaire `file:///persistent/path/to/entry` (Firefox, IE). Chrome retourne le chemin d'accès dans le formulaire `cdvfile://localhost/persistent/file`. + + [4]: http://www.w3.org/TR/2011/WD-file-system-api-20110419/#naming-restrictions + +### Bizarreries de chrome + +* Chrome filesystem n'est pas prête immédiatement après l'événement ready périphérique. Pour contourner le problème, vous pouvez vous abonner à l'événement `filePluginIsReady`. Exemple : + + javascript + window.addEventListener('filePluginIsReady', function(){ console.log('File plugin is ready');}, false); + + +Vous pouvez utiliser la fonction `window.isFilePluginReadyRaised` pour vérifier si les événement était déjà déclenché. -quotas de window.requestFileSystem temporaire et permanent de système de fichiers ne sont pas limités en Chrome. -Pour augmenter le stockage persistant en Chrome, vous devez appeler la méthode `window.initPersistentFileSystem`. Quota de stockage persistant est 5 Mo par défaut. -Chrome nécessite `--permettre-fichier-accès-de-fichiers` exécuter l'argument au support API via le protocole `file:///`. -`Fichier` objet changera pas si vous utilisez le drapeau `{create:true}` lors du passage d'une `entrée` existante. -événements `annulables` propriété a la valeur true dans Chrome. Il s'agit à l'encontre de la [spécification][5]. -`toURL` renvoie à Chrome `système de fichiers :`-préfixe de chemin d'accès selon l'application hôte. Par exemple, `filesystem:file:///persistent/somefile.txt`, `filesystem:http://localhost:8080/persistent/somefile.txt`. -résultat de la fonction `toURL` ne contient-elle pas de barre oblique dans le cas d'entrée d'annuaire. Chrome résout répertoires avec barre oblique-trainés URL correctement cependant. -`resolveLocalFileSystemURL` méthode nécessite l' entrant `url` préfixe de `système de fichiers`. Par exemple, le paramètre `d'url` pour `resolveLocalFileSystemURL` devrait être dans la forme `filesystem:file:///persistent/somefile.txt` par opposition à la forme `file:///persistent/somefile.txt` dans Android. -Déconseillée `toNativeURL` fonction n'est pas prise en charge et n'est pas une ébauche. -fonction de `setMetadata` n'est pas stipulée dans le devis et pas pris en charge. -INVALID_MODIFICATION_ERR (code: 9) est levée au lieu de SYNTAX_ERR(code: 8) sur la demande d'un système de fichier inexistant. -INVALID_MODIFICATION_ERR (code: 9) est levée au lieu de PATH_EXISTS_ERR(code: 12) à essayer de créer exclusivement un fichier ou un répertoire, qui existe déjà. -INVALID_MODIFICATION_ERR (code: 9) est levée au lieu de NO_MODIFICATION_ALLOWED_ERR(code: 6) à essayer d'appeler removeRecursively sur le système de fichiers racine. -INVALID_MODIFICATION_ERR (code: 9) est levée au lieu de NOT_FOUND_ERR(code: 1) en essayant de moveTo répertoire qui n'existe pas. + + [5]: http://dev.w3.org/2009/dap/file-system/file-writer.html + +### Base IndexedDB impl bizarreries (Firefox et IE) + +* `.` et `.` ne sont pas pris en charge. +* IE ne prend pas en charge les `file:///`-mode ; seul le mode hébergé est pris en charge (http://localhost:xxxx). +* Taille de système de fichiers de Firefox n'est pas limité, mais chaque extension de 50Mo demandera une autorisation de l'utilisateur. IE10 permet jusqu'à 10 Mo de combiné AppCache et IndexedDB utilisés dans la mise en œuvre du système de fichiers sans demander de confirmation, une fois que vous atteignez ce niveau, Qu'on vous demandera si vous souhaitez lui permettre d'être augmentée jusqu'à un maximum de 250 Mo par site. Si le paramètre de `taille` pour la fonction `requestFileSystem` n'affecte pas le système de fichiers dans Firefox et IE. +* fonction de `readAsBinaryString` n'est pas indiquée dans les spécifications et pas pris en charge dans Internet Explorer et n'a pas une ébauche. +* `file.type` est toujours null. +* Vous ne devez pas créer en utilisant le résultat du callback instance DirectoryEntry qui avait été supprimée. Sinon, vous obtiendrez une « entrée de pendaison ». +* Avant que vous pouvez lire un fichier qui a été écrit juste que vous devez obtenir une nouvelle instance de ce fichier. +* `setMetadata` fonction, qui n'est pas indiquée dans les spécifications supporte `modificationTime` changement de champ seulement. +* fonctions `copyTo` et `moveTo` ne supportent pas les répertoires. +* Répertoires métadonnées ne sont pas pris en charge. +* Les deux Entry.remove et directoryEntry.removeRecursively ne manquent pas lors de la suppression des répertoires non-vides - répertoires retirés sont nettoyés avec contenu au lieu de cela. +* fonctions `abort` et `truncate` ne sont pas supportées. +* événements de progression ne sont pas déclenchés. Par exemple, ce gestionnaire ne sera pas exécuté : + + javascript + writer.onprogress = function() { /*commands*/ }; + + +## Notes de mise à niveau + +V1.0.0 de ce plugin, les structures `FileEntry` et `DirectoryEntry` ont changé, pour être plus conforme à la spécification publiée. + +Les versions précédentes de (pré-1.0.0) du plugin stockaient le dispositif-absolu--emplacement du fichier dans la propriété `fullPath` d'objets `d'entrée`. Ces chemins seraient présente généralement comme + + / var/mobile/Applications/< application UUID >/Documents/chemin/vers/fichier (iOS), /storage/emulated/0/path/to/file (Android) + + +Ces chemins ont été également retournés par la méthode de `toURL()` les objets `d'entrée`. + +Avec v1.0.0, l'attribut `fullPath` est le chemin d'accès au fichier, *par rapport à la racine du système de fichiers HTML*. Ainsi, les chemins d'accès ci-dessus seraient maintenant tous les deux être représentée par un objet `FileEntry` avec un `fullPath` de + + /path/to/file + + +Si votre application fonctionne avec le dispositif-absolu-chemins et que vous avez récupéré précédemment ces chemins d'accès par le biais de la propriété `fullPath` d'objets `d'entrée`, puis vous devez mettre à jour votre code afin d'utiliser `entry.toURL()` à la place. + +Pour vers l'arrière la compatibilité, la méthode `resolveLocalFileSystemURL()` sera un chemin absolu de l'unité et retourne un objet `Entry` correspondant à elle, tant que ce fichier existe au sein des systèmes de fichiers les `TEMPORARY` ou `PERSISTENT`. + +Cela a été particulièrement un problème avec le plugin de transfert de fichiers, qui autrefois périphérique-absolu-chemins (et peut encore accepter). Il a été mis à jour pour fonctionner correctement avec le système de fichiers URL, afin de remplacer `entry.fullPath` par `entry.toURL()` devrait résoudre tout problème obtenir ce plugin pour travailler avec des fichiers sur le périphérique. + +Dans v1.1.0 la valeur de retour de `toURL()` a été changée (voir \[CB-6394\] (https://issues.apache.org/jira/browse/CB-6394)) pour renvoyer une URL absolue "file://". dans la mesure du possible. Pour assurer un ' cdvfile:'-URL, vous pouvez utiliser `toInternalURL()` maintenant. Cette méthode retourne maintenant filesystem URL du formulaire + + cdvfile://localhost/persistent/path/to/file + + +qui peut servir à identifier de manière unique le fichier. + +## Liste des Codes d'erreur et leur signification + +Lorsqu'une erreur est levée, l'un des codes suivants sera utilisé. + +| Code | Constant | +| ----:|:----------------------------- | +| 1 | `NOT_FOUND_ERR` | +| 2 | `SECURITY_ERR` | +| 3 | `ABORT_ERR` | +| 4 | `NOT_READABLE_ERR` | +| 5 | `ENCODING_ERR` | +| 6 | `NO_MODIFICATION_ALLOWED_ERR` | +| 7 | `INVALID_STATE_ERR` | +| 8 | `SYNTAX_ERR` | +| 9 | `INVALID_MODIFICATION_ERR` | +| 10 | `QUOTA_EXCEEDED_ERR` | +| 11 | `TYPE_MISMATCH_ERR` | +| 12 | `PATH_EXISTS_ERR` | + +## Configuration du Plugin (facultatif) + +L'ensemble des systèmes de fichiers disponibles peut être configurée par plate-forme. Les iOS et Android reconnaissent une balise dans le `fichier config.xml` qui nomme les systèmes de fichiers à installer. Par défaut, toutes les racines du système de fichiers sont activées. + + + + + +### Android + +* `files` : répertoire de stockage de fichier interne de l'application +* `files-external` : répertoire de l'application de stockage de fichier externe +* `sdcard` : le répertoire de stockage global fichier externe (c'est la racine de la carte SD, s'il est installé). Vous devez avoir la permission de `android.permission.WRITE_EXTERNAL_STORAGE` de l'utiliser. +* `cache` : répertoire de cache interne de l'application +* `cache-external` : répertoire de cache externe de l'application +* `root` : le système de fichiers de tout dispositif + +Android prend également en charge un système de fichiers spécial nommé « documents », qui représente un sous-répertoire « / Documents / » dans le système de fichiers « files ». + +### iOS + +* `library` : répertoire de bibliothèque de l'application +* `documents` : répertoire de Documents de l'application +* `cache` : répertoire de Cache de l'application +* `bundle` : bundle de l'application ; l'emplacement de l'application elle-même sur disque (lecture seule) +* `root` : le système de fichiers de tout dispositif + +Par défaut, vous peuvent synchroniser les répertoires de la bibliothèque et les documents à iCloud. Vous pouvez également demander des deux systèmes de fichiers supplémentaires, `library-nosync` et `documents-nosync`, qui représentent un répertoire spécial non synchronisées dans le `/Library` ou système de fichiers `/ Documents`. diff --git a/plugins/cordova-plugin-file/doc/fr/plugins.md b/plugins/cordova-plugin-file/doc/fr/plugins.md new file mode 100644 index 0000000..b04e17f --- /dev/null +++ b/plugins/cordova-plugin-file/doc/fr/plugins.md @@ -0,0 +1,101 @@ + + +# Notes pour les développeurs de plugins + +Ces notes sont principalement destinés à des développeurs Android et iOS qui veulent écrire des plugins qui interface avec le système de fichiers en utilisant le fichier plugin. + +## Travailler avec Cordova fichier système URL + +Depuis la version 1.0.0, ce plugin utilise des URL avec un `cdvfile` guichet pour toutes les communications sur le pont, plutôt que d'exposer des chemins de système de fichiers de périphérique brut à JavaScript. + +Du côté du JavaScript, cela signifie que les objets FileEntry et DirectoryEntry ont un attribut fullPath qui est relatif à la racine du système de fichiers HTML. Si votre plugin JavaScript API accepte un objet FileEntry ou DirectoryEntry, vous devez appeler `.toURL()` sur cet objet avant de le passer sur le pont en code natif. + +### Conversion de cdvfile: / / URL aux chemins d'accès fileystem + +Plugins qui ont besoin d'écrire dans le système de fichiers pouvez convertir un fichier reçu système URL vers un emplacement de système de fichiers réels. Il y a plusieurs façons de le faire, selon la plate-forme native. + +Il est important de rappeler que pas tous les `cdvfile://` URL sont cartographiables à des fichiers sur le périphérique. Certaines URL peut faire référence aux actifs sur les périphériques qui ne sont pas représentés par des fichiers, ou peuvent même faire référence aux ressources distantes. En raison de ces possibilités, plugins devraient toujours tester si ils obtiennent un résultat significatif retour lorsque vous essayez de convertir les URL aux chemins d'accès. + +#### Androïde + +Sur Android, la méthode la plus simple pour convertir un `cdvfile://` URL vers un chemin d'accès de système de fichiers est d'utiliser `org.apache.cordova.CordovaResourceApi` . `CordovaResourceApi`possède plusieurs méthodes qui peuvent gérer `cdvfile://` URL : + + webView est membre de la Plugin classe CordovaResourceApi resourceApi = webView.getResourceApi() ; + + Obtenir une URL file:/// représentant ce fichier sur le périphérique, / / ou le même URL inchangée si elle ne peut pas être mappée à un fichier Uri fileURL = resourceApi.remapUri(Uri.parse(cdvfileURL)) ; + + +Il est également possible d'utiliser le fichier plugin directement : + + Import org.apache.cordova.file.FileUtils ; + Import org.apache.cordova.file.FileSystem ; + java.net.MalformedURLException d'importation ; + + Téléchargez le fichier plugin depuis le gestionnaire de plugin FileUtils filePlugin = (FileUtils)webView.pluginManager.getPlugin("File") ; + + En donnant une URL, obtenir un chemin d'accès pour essayer {String path = filePlugin.filesystemPathForURL(cdvfileURL);} catch (MalformedURLException e) {/ / l'url du système de fichiers n'a pas été reconnu} + + +Pour convertir un chemin d'accès à un `cdvfile://` URL : + + Import org.apache.cordova.file.LocalFilesystemURL ; + + Obtenir un objet LocalFilesystemURL pour un chemin de périphérique, / / ou null si elle ne peut être représentée sous forme d'URL cdvfile. + LocalFilesystemURL url = filePlugin.filesystemURLforLocalPath(path) ; + Obtenir la chaîne représentant l'URL objet String cdvfileURL = url.toString() ; + + +Si votre plugin crée un fichier et que vous souhaitez renvoyer un objet FileEntry pour cela, utilisez le fichier plugin : + + Retourne une structure JSON approprié pour revenir en JavaScript, / / ou null si ce fichier n'est pas représentable sous forme d'URL cdvfile. + JSONObject entrée = filePlugin.getEntryForFile(file) ; + + +#### iOS + +Cordova sur iOS n'utilise pas le même `CordovaResourceApi` concept d'Android. Sur iOS, vous devez utiliser le fichier plugin pour convertir entre les URL et les chemins d'accès de système de fichiers. + + Obtenir un objet URL CDVFilesystem partir d'une chaîne d'URL CDVFilesystemURL * url = [CDVFilesystemURL fileSystemURLWithString:cdvfileURL] ; + Obtenir un chemin d'accès de l'objet URL, ou zéro si elle ne peut pas être mappée à un chemin de fichier NSString * = [filePlugin filesystemPathForURL:url] ; + + + Obtenir un objet CDVFilesystem URL pour un chemin de périphérique, ou / / zéro si elle ne peut être représentée sous forme d'URL cdvfile. + CDVFilesystemURL * url = [filePlugin fileSystemURLforLocalPath:path] ; + Obtenir la représentation de chaîne de l'objet NSString * cdvfileURL URL = [url absoluteString] ; + + +Si votre plugin crée un fichier et que vous souhaitez renvoyer un objet FileEntry pour cela, utilisez le fichier plugin : + + Obtenir un objet CDVFilesystem URL pour un chemin de périphérique, ou / / zéro si elle ne peut être représentée sous forme d'URL cdvfile. + CDVFilesystemURL * url = [filePlugin fileSystemURLforLocalPath:path] ; + Obtenir une structure pour revenir à JavaScript NSDictionary * entrée = [filePlugin makeEntryForLocalURL:url] + + +#### JavaScript + +En JavaScript, pour obtenir un `cdvfile://` URL d'un objet FileEntry ou DirectoryEntry, il suffit d'appeler `.toURL()` à ce sujet : + + var cdvfileURL = entry.toURL() ; + + +Dans gestionnaires de plugin de réponse, pour convertir une structure FileEntry retournée vers un objet réel de l'entrée, votre code de gestionnaire doit importer le fichier plugin et créer un nouvel objet : + + créer l'entrée de var d'objet entrée appropriée ; + Si (entryStruct.isDirectory) {entrée = new DirectoryEntry (entryStruct.name, entryStruct.fullPath, nouveau FileSystem(entryStruct.filesystemName));} else {entrée = nouvelle FileEntry (entryStruct.name, entryStruct.fullPath, nouvelle FileSystem(entryStruct.filesystemName));} \ No newline at end of file diff --git a/plugins/cordova-plugin-file/doc/it/README.md b/plugins/cordova-plugin-file/doc/it/README.md new file mode 100644 index 0000000..f8e302f --- /dev/null +++ b/plugins/cordova-plugin-file/doc/it/README.md @@ -0,0 +1,335 @@ + + +# cordova-plugin-file + +[![Build Status](https://travis-ci.org/apache/cordova-plugin-file.svg)](https://travis-ci.org/apache/cordova-plugin-file) + +Questo plugin implementa un API File permettendo l'accesso di lettura/scrittura ai file che risiedono sul dispositivo. + +Questo plugin si basa su diverse specifiche, tra cui: The HTML5 File API + +Le directory (ormai defunta) e il sistema delle estensioni più recenti: anche se la maggior parte del codice plugin è stato scritto quando una spec precedenti era corrente: + +Implementa inoltre FileWriter spec: + +Per l'utilizzo, fare riferimento a HTML5 Rocks' eccellente [articolo FileSystem.](http://www.html5rocks.com/en/tutorials/file/filesystem/) + +Per una panoramica delle altre opzioni di archiviazione, consultare [Guida di archiviazione di Cordova](http://cordova.apache.org/docs/en/edge/cordova_storage_storage.md.html). + +Questo plugin definisce oggetto global `cordova.file`. + +Anche se in ambito globale, non è disponibile fino a dopo l'evento `deviceready`. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(cordova.file); + } + + +## Installazione + + cordova plugin add cordova-plugin-file + + +## Piattaforme supportate + + * Amazon fuoco OS + * Android + * BlackBerry 10 + * Firefox OS + * iOS + * Windows Phone 7 e 8 * + * Windows 8 * + * Windows* + * Browser + +\* *These platforms do not support `FileReader.readAsArrayBuffer` nor `FileWriter.write(blob)`.* + +## Dove memorizzare i file + +A partire dalla v 1.2.0, vengono forniti gli URL per le directory importanti file di sistema. Ogni URL è nella forma *file:///path/to/spot/* e può essere convertito in un `DirectoryEntry` utilizzando `window.resolveLocalFileSystemURL()`. + + * `cordova.file.applicationDirectory`-Sola lettura directory dove è installato l'applicazione. (*iOS*, *Android*, *BlackBerry 10*) + + * `cordova.file.applicationStorageDirectory`-Directory radice di sandbox dell'applicazione; su iOS questa posizione è in sola lettura (ma sottodirectory specifiche [come `/Documents` ] sono di sola lettura). Tutti i dati contenuti all'interno è privato all'app. ( *iOS*, *Android*, *BlackBerry 10*) + + * `cordova.file.dataDirectory`-Archiviazione dati persistente e privati nella sandbox dell'applicazione utilizzando la memoria interna (su Android, se è necessario utilizzare la memoria esterna, utilizzare `.externalDataDirectory` ). IOS, questa directory non è sincronizzata con iCloud (utilizzare `.syncedDataDirectory` ). (*iOS*, *Android*, *BlackBerry 10*) + + * `cordova.file.cacheDirectory`-Directory per i file memorizzati nella cache di dati o qualsiasi file che app possibile ricreare facilmente. L'OS può eliminare questi file quando il dispositivo viene eseguito basso sull'archiviazione, tuttavia, apps non deve basarsi sul sistema operativo per cancellare i file qui. (*iOS*, *Android*, *BlackBerry 10*) + + * `cordova.file.externalApplicationStorageDirectory`-Spazio applicazione su storage esterno. (*Android*) + + * `cordova.file.externalDataDirectory`-Dove mettere i file di dati specifico app su storage esterno. (*Android*) + + * `cordova.file.externalCacheDirectory`-Cache applicazione su storage esterno. (*Android*) + + * `cordova.file.externalRootDirectory`-Radice di archiviazione esterna (scheda SD). (*Android*, *BlackBerry, 10*) + + * `cordova.file.tempDirectory`-Temp directory che l'OS è possibile cancellare a volontà. Non fare affidamento sul sistema operativo per cancellare questa directory; l'app deve sempre rimuovere file come applicabile. (*iOS*) + + * `cordova.file.syncedDataDirectory`-Contiene i file app specifiche che devono essere sincronizzati (per esempio a iCloud). (*iOS*) + + * `cordova.file.documentsDirectory`-I file privati per le app, ma che sono significativi per altre applicazioni (ad esempio i file di Office). (*iOS*) + + * `cordova.file.sharedDirectory`-File disponibili globalmente a tutte le applicazioni (*BlackBerry 10*) + +## Layout dei file di sistema + +Anche se tecnicamente un dettaglio di implementazione, può essere molto utile per conoscere come le proprietà `cordova.file.*` mappa di percorsi fisici su un dispositivo reale. + +### iOS File sistema Layout + +| Percorso dispositivo | `Cordova.file.*` | `iosExtraFileSystems` | r/w? | persistente? | OS cancella | sincronizzazione | privato | +|:---------------------------------------------- |:--------------------------- |:--------------------- |:----:|:------------:|:------------:|:----------------:|:-------:| +| `/ var/mobile/Applications/< UUID > /` | applicationStorageDirectory | - | r | N/A | N/A | N/A | Sì | +|    `appname.app/` | applicationDirectory | bundle | r | N/A | N/A | N/A | Sì | +|       `www/` | - | - | r | N/A | N/A | N/A | Sì | +|    `Documents/` | documentsDirectory | documenti | r/w | Sì | No | Sì | Sì | +|       `NoCloud/` | - | nosync-documenti | r/w | Sì | No | No | Sì | +|    `Library` | - | libreria | r/w | Sì | No | Sì? | Sì | +|       `NoCloud/` | dataDirectory | nosync-libreria | r/w | Sì | No | No | Sì | +|       `Cloud/` | syncedDataDirectory | - | r/w | Sì | No | Sì | Sì | +|       `Caches/` | cacheDirectory | cache | r/w | Sì * | Sì**\* | No | Sì | +|    `tmp/` | tempDirectory | - | r/w | No** | Sì**\* | No | Sì | + +\ * File persistono tra riavvii app e aggiornamenti, ma questa directory può essere cancellata ogni volta che il sistema operativo desideri. L'app dovrebbe essere in grado di ricreare qualsiasi contenuto che potrebbe essere eliminato. + +** File possono persistere riavvii del app, ma non fare affidamento su questo comportamento. I file non sono garantiti a persistere attraverso gli aggiornamenti. L'app deve rimuovere i file dalla directory quando è applicabile, come il sistema operativo non garantisce quando (o anche se) questi file vengono rimossi. + +**\ * The OS può cancellare il contenuto di questa directory ogni volta che si sente è necessario, ma non fare affidamento su questo. Si dovrebbe cancellare questa directory come adatto per l'applicazione. + +### Layout sistema Android File + +| Percorso dispositivo | `Cordova.file.*` | `AndroidExtraFileSystems` | r/w? | persistente? | OS cancella | privato | +|:------------------------------------------------ |:----------------------------------- |:------------------------- |:----:|:------------:|:-----------:|:-------:| +| `File:///android_asset/` | applicationDirectory | | r | N/A | N/A | Sì | +| `< app-id > /dati/dati / /` | applicationStorageDirectory | - | r/w | N/A | N/A | Sì | +|    `cache` | cacheDirectory | cache | r/w | Sì | Sì\* | Sì | +|    `files` | dataDirectory | file | r/w | Sì | No | Sì | +|       `Documents` | | documenti | r/w | Sì | No | Sì | +| `< sdcard > /` | externalRootDirectory | sdcard | r/w | Sì | No | No | +|    `Android/data//` | externalApplicationStorageDirectory | - | r/w | Sì | No | No | +|       `cache` | externalCacheDirectry | cache-esterno | r/w | Sì | No** | No | +|       `files` | externalDataDirectory | file-esterno | r/w | Sì | No | No | + +\ * Il sistema operativo può cancellare periodicamente questa directory, ma non fare affidamento su questo comportamento. Cancellare il contenuto di questa directory come adatto per l'applicazione. Il contenuto di questa directory dovrebbe un utente eliminare manualmente la cache, vengono rimossi. + +** Il sistema operativo non cancella questa directory automaticamente; Siete responsabili di gestire i contenuti da soli. Il contenuto della directory dovrebbe l'utente eliminare manualmente la cache, vengono rimossi. + +**Nota**: se la memorizzazione esterna non può essere montato, le proprietà `cordova.file.external*` sono `null`. + +### BlackBerry 10 File sistema Layout + +| Percorso dispositivo | `Cordova.file.*` | r/w? | persistente? | OS cancella | privato | +|:----------------------------------------------------------- |:--------------------------- |:----:|:------------:|:-----------:|:-------:| +| `File:///accounts/1000/AppData/ < id app > /` | applicationStorageDirectory | r | N/A | N/A | Sì | +|    `app/native` | applicationDirectory | r | N/A | N/A | Sì | +|    `data/webviews/webfs/temporary/local__0` | cacheDirectory | r/w | No | Sì | Sì | +|    `data/webviews/webfs/persistent/local__0` | dataDirectory | r/w | Sì | No | Sì | +| `File:///accounts/1000/Removable/sdcard` | externalRemovableDirectory | r/w | Sì | No | No | +| `File:///accounts/1000/Shared` | sharedDirectory | r/w | Sì | No | No | + +*Nota*: quando l'applicazione viene distribuita a lavorare perimetrale, tutti i percorsi sono relativi a /accounts/1000-enterprise. + +## Stranezze Android + +### Posizione di archiviazione persistente Android + +Ci sono più percorsi validi per memorizzare i file persistenti su un dispositivo Android. Vedi [questa pagina](http://developer.android.com/guide/topics/data/data-storage.html) per un'ampia discussione delle varie possibilità. + +Versioni precedenti del plugin avrebbe scelto il percorso dei file temporanei e permanenti su avvio, in base se il dispositivo ha sostenuto che la scheda SD (o partizione storage equivalente) è stato montato. Se è stata montata sulla scheda SD o una partizione di storage interno grande era disponibile (come sui dispositivi Nexus,) allora saranno memorizzati i file persistenti nella radice di quello spazio. Questo significava che tutte le apps di Cordova poteva vedere tutti i file disponibili sulla carta. + +Se la scheda SD non era disponibile, poi versioni precedenti vuoi memorizzare dati sotto `/data/data/`, che isola i apps da altro, ma può ancora causa dati da condividere tra gli utenti. + +Ora è possibile scegliere se memorizzare i file nel percorso di archiviazione di file interno o utilizzando la logica precedente, con una preferenza nel file `config. xml` dell'applicazione. Per fare questo, aggiungere una di queste due linee al `file config. xml`: + + + + + + +Senza questa linea, il File del plugin utilizzerà la `Compatibility` come predefinito. Se è presente un tag di preferenza e non è uno di questi valori, l'applicazione non si avvia. + +Se l'applicazione è stato spedito in precedenza agli utenti, utilizzando un vecchio (pre-1.0) versione di questo plugin e ha i file memorizzati nel filesystem persistente, allora si dovrebbe impostare la preferenza di `Compatibility`. La posizione su "Interno" di commutazione significherebbe che gli utenti esistenti che aggiornare la loro applicazione potrebbero essere Impossibile accedere ai loro file precedentemente memorizzati, a seconda del loro dispositivo. + +Se l'applicazione è nuova, o ha mai precedentemente memorizzati i file nel filesystem persistente, è generalmente consigliato l'impostazione `Internal`. + +### Operazioni ricorsive lento per /android_asset + +L'elencazione delle directory asset è veramente lento su Android. È possibile velocizzare e fino anche se, con l'aggiunta di `src/android/build-extras.gradle` alla radice del tuo progetto android (richiede anche cordova-android@4.0.0 o superiore). + +## iOS stranezze + + * `cordova.file.applicationStorageDirectory`è di sola lettura; tentativo di memorizzare i file all'interno della directory radice avrà esito negativo. Utilizzare uno degli altri `cordova.file.*` proprietà definite per iOS (solo `applicationDirectory` e `applicationStorageDirectory` sono di sola lettura). + * `FileReader.readAsText(blob, encoding)` + * Il `encoding` parametro non è supportato, e codifica UTF-8 è sempre attivo. + +### posizione di archiviazione persistente di iOS + +Ci sono due percorsi validi per memorizzare i file persistenti su un dispositivo iOS: la directory documenti e la biblioteca. Precedenti versioni del plugin archiviati solo mai persistenti file nella directory documenti. Questo ha avuto l'effetto collaterale di tutti i file di un'applicazione che rende visibili in iTunes, che era spesso involontaria, soprattutto per le applicazioni che gestiscono un sacco di piccoli file, piuttosto che produrre documenti completi per l'esportazione, che è la destinazione della directory. + +Ora è possibile scegliere se memorizzare i file nella directory di libreria, con una preferenza nel file `config. xml` dell'applicazione o documenti. Per fare questo, aggiungere una di queste due linee al `file config. xml`: + + + + + + +Senza questa linea, il File del plugin utilizzerà la `Compatibility` come predefinito. Se è presente un tag di preferenza e non è uno di questi valori, l'applicazione non si avvia. + +Se l'applicazione è stato spedito in precedenza agli utenti, utilizzando un vecchio (pre-1.0) versione di questo plugin e ha i file memorizzati nel filesystem persistente, allora si dovrebbe impostare la preferenza di `Compatibility`. La posizione di commutazione alla `libreria` significherebbe che gli utenti esistenti che aggiornare la loro applicazione è in grado di accedere ai loro file precedentemente memorizzati. + +Se l'applicazione è nuova, o ha mai precedentemente memorizzati i file nel filesystem persistente, è generalmente consigliato l'impostazione della `Library`. + +## Firefox OS stranezze + +L'API di sistema del File non è supportato nativamente dal sistema operativo Firefox e viene implementato come uno spessore in cima indexedDB. + + * Non manca quando si rimuove le directory non vuota + * Non supporta i metadati per le directory + * Metodi `copyTo` e `moveTo` non supporta le directory + +Sono supportati i seguenti percorsi di dati: * `applicationDirectory` - utilizza `xhr` per ottenere i file locali che sono confezionati con l'app. *`dataDirectory` - per i file di dati persistenti app specifiche. *`cacheDirectory` - file memorizzati nella cache che dovrebbe sopravvivere si riavvia app (applicazioni non devono basarsi sull'OS di eliminare i file qui). + +## Stranezze browser + +### Stranezze e osservazioni comuni + + * Ogni browser utilizza il proprio filesystem in modalità sandbox. IE e Firefox utilizzare IndexedDB come base. Tutti i browser utilizzano barra come separatore di directory in un percorso. + * Le voci di directory devono essere creato successivamente. Ad esempio, la chiamata `fs.root.getDirectory (' dir1/dir2 ', {create:true}, successCallback, errorCallback)` non riuscirà se non esistesse dir1. + * Il plugin richiede autorizzazione utente per utilizzare un archivio permanente presso il primo avvio dell'applicazione. + * Plugin supporta `cdvfile://localhost` (risorse locali) solo. Cioè risorse esterne non sono supportate tramite `cdvfile`. + * Il plugin non segue ["Limitazioni di denominazione 8.3 File sistema API"](http://www.w3.org/TR/2011/WD-file-system-api-20110419/#naming-restrictions). + * BLOB e File' `close` la funzione non è supportata. + * `FileSaver` e `BlobBuilder` non sono supportati da questo plugin e non hanno gli stub. + * Il plugin non supporta `requestAllFileSystems`. Questa funzione manca anche nelle specifiche. + * Entrate nella directory non verranno rimossi se si utilizza `create: true` bandiera per directory esistente. + * Non sono supportati i file creati tramite il costruttore. È invece necessario utilizzare il metodo entry.file. + * Ogni browser utilizza la propria forma per riferimenti URL blob. + * `readAsDataURL` funzione è supportata, ma il mediatype in Chrome dipende dall'estensione di voce, mediatype in IE è sempre vuota (che è lo stesso come `text-plain` secondo la specifica), il mediatype in Firefox è sempre `application/octet-stream`. Ad esempio, se il contenuto è `abcdefg` quindi Firefox restituisce `dati: applicazione / octet-stream; base64, YWJjZGVmZw = =`, cioè restituisce `dati:; base64, YWJjZGVmZw = =`, Chrome restituisce `dati: < mediatype a seconda dell'estensione del nome della voce >; base64, YWJjZGVmZw = =`. + * `toInternalURL` restituisce il percorso in forma `file:///persistent/path/to/entry` (Firefox, IE). Chrome restituisce il percorso nella forma `cdvfile://localhost/persistent/file`. + +### Stranezze di cromo + + * Cromo filesystem non è subito pronto dopo evento ready dispositivo. Come soluzione alternativa, è possibile iscriversi all'evento `filePluginIsReady`. Esempio: + +```javascript +window.addEventListener('filePluginIsReady', function(){ console.log('File plugin is ready');}, false); +``` + +È possibile utilizzare la funzione `window.isFilePluginReadyRaised` per verificare se evento già è stato generato. -quote di filesystem TEMPORARY e PERSISTENT window.requestFileSystem non sono limitate in Chrome. -Per aumentare la memoria persistente in Chrome è necessario chiamare il metodo `window.initPersistentFileSystem`. Quota di archiviazione persistente è di 5 MB per impostazione predefinita. -Chrome richiede `-consentire-file-accesso-da-file` eseguire argomento a supporto API tramite protocollo `file:///`. -`File` oggetto non cambierà se si utilizza il flag `{create:true}` quando ottenendo un' esistente `entrata`. -eventi `cancelable` è impostata su true in Chrome. Ciò è in contrasto con la [specifica](http://dev.w3.org/2009/dap/file-system/file-writer.html). -funzione `toURL` Chrome restituisce `filesystem:`-premessi percorso a seconda dell'applicazione host. Ad esempio, `filesystem:file:///persistent/somefile.txt`, `filesystem:http://localhost:8080/persistent/somefile.txt`. -`toURL` risultato di funzione non contiene una barra finale in caso di voce di directory. Chrome risolve le directory con gli URL slash-trainati però correttamente. -`resolveLocalFileSystemURL` metodo richiede in ingresso `url` avere il prefisso del `file System`. Ad esempio, il parametro `url` per `resolveLocalFileSystemURL` dovrebbe essere nella forma `filesystem:file:///persistent/somefile.txt` in contrasto con la forma `file:///persistent/somefile.txt` in Android. -Obsoleto `toNativeURL` funzione non è supportata e non dispone di uno stub. -funzione `setMetadata` non è indicato nelle specifiche e non supportato. -INVALID_MODIFICATION_ERR (codice: 9) viene generata invece di SYNTAX_ERR(code: 8) su richiesta di un filesystem inesistente. -INVALID_MODIFICATION_ERR (codice: 9) viene generata invece di PATH_EXISTS_ERR(code: 12) sul tentativo di creare esclusivamente un file o una directory, che esiste già. -INVALID_MODIFICATION_ERR (codice: 9) viene generata invece di NO_MODIFICATION_ALLOWED_ERR(code: 6) sul tentativo di chiamare removeRecursively su file system root. -INVALID_MODIFICATION_ERR (codice: 9) viene generata invece di NOT_FOUND_ERR(code: 1) sul tentativo moveTo directory che non esiste. + +### Stranezze impl IndexedDB-basato (Firefox e IE) + + * `.` e `.` non sono supportati. + * IE non supporta `file:///`-modalità; modalità solo ospitata è supportato (http://localhost:xxxx). + * Dimensione filesystem Firefox non è limitata, ma ogni estensione 50MB sarà richiesta un'autorizzazione dell'utente. IE10 consente fino a 10mb di combinato AppCache e IndexedDB utilizzato nell'implementazione del filesystem senza chiedere conferma, una volta premuto quel livello che vi verrà chiesto se si desidera consentire ad essere aumentata fino a un max di 250 mb per ogni sito. Quindi la `size` parametro per la funzione `requestFileSystem` non influisce il filesystem in Firefox e IE. + * `readAsBinaryString` funzione non è indicato nelle specifiche e non supportati in IE e non dispone di uno stub. + * `file.Type` è sempre null. + * Non è necessario creare la voce utilizzando il risultato del callback istanza DirectoryEntry che è stato eliminato. In caso contrario, si otterrà una 'voce di sospensione'. + * Prima è possibile leggere un file che è stato appena scritto è necessario ottenere una nuova istanza di questo file. + * supporta la funzione `setMetadata`, che non è indicato nelle specifiche `modificationTime` cambiamento di campo solo. + * funzioni `copyTo` e `moveTo` non supporta le directory. + * Le directory metadati non sono supportato. + * Sia Entry.remove e directoryEntry.removeRecursively non fallire quando si rimuove le directory non vuota - directory da rimuovere vengono pulite invece insieme al contenuto. + * `abort` e `truncate` le funzioni non sono supportate. + * non vengono generati eventi di progresso. Ad esempio, questo gestore verrà non eseguito: + +```javascript +writer.onprogress = function() { /*commands*/ }; +``` + +## Note di aggiornamento + +In v 1.0.0 di questo plugin, le strutture `FileEntry` e `DirectoryEntry` sono cambiati, per essere più in linea con le specifiche pubblicate. + +Versioni precedenti (pre-1.0.0) del plugin archiviati il dispositivo-assoluto--percorso del file nella proprietà `fullPath` di oggetti della `voce`. In genere questi percorsi si sarebbe simile + + /var/mobile/Applications//Documents/path/to/file (iOS) + /storage/emulated/0/path/to/file (Android) + + +Questi percorsi sono stati anche restituiti dal metodo `toURL()` degli oggetti `Entry`. + +Con v 1.0.0, l'attributo `fullPath` è il percorso del file, *rispetto alla radice del filesystem HTML*. Così, i percorsi sopra sarebbe ora sia rappresentato da un oggetto `FileEntry` con un `fullPath` di + + /path/to/file + + +Se l'applicazione funziona con dispositivo-assoluto-percorsi, e precedentemente recuperato quei percorsi attraverso la proprietà `fullPath` della `voce` oggetti, è necessario aggiornare il codice per utilizzare `entry.toURL()` invece. + +Per indietro la compatibilità, il metodo `resolveLocalFileSystemURL()` verrà accettare un dispositivo-assoluto-percorso e restituirà un oggetto di `entrata` corrispondente ad essa, fintanto che il file esiste all'interno del filesystem la `temporanea` o `permanente`. + +Questo particolare è stato un problema con il plugin di trasferimento File, che in precedenza utilizzati percorsi-dispositivo-assoluto (e ancora può accoglierli). Esso è stato aggiornato per funzionare correttamente con gli URL di FileSystem, così sostituendo `entry.fullPath` con `entry.toURL()` dovrebbe risolvere eventuali problemi ottenendo quel plugin per lavorare con i file nel dispositivo. + +In v 1.1.0 il valore restituito di `toURL()` è stato cambiato (vedere \[CB-6394\] (https://issues.apache.org/jira/browse/CB-6394)) per restituire un URL assoluto 'file://'. ove possibile. Per assicurare un ' cdvfile:'-URL, è possibile utilizzare `toInternalURL()` ora. Questo metodo restituirà ora filesystem URL del modulo + + cdvfile://localhost/persistent/path/to/file + + +che può essere utilizzato per identificare univocamente il file. + +## Elenco dei codici di errore e significati + +Quando viene generato un errore, uno dei seguenti codici da utilizzare. + +| Codice | Costante | +| ------:|:----------------------------- | +| 1 | `NOT_FOUND_ERR` | +| 2 | `SECURITY_ERR` | +| 3 | `ABORT_ERR` | +| 4 | `NOT_READABLE_ERR` | +| 5 | `ENCODING_ERR` | +| 6 | `NO_MODIFICATION_ALLOWED_ERR` | +| 7 | `INVALID_STATE_ERR` | +| 8 | `SYNTAX_ERR` | +| 9 | `INVALID_MODIFICATION_ERR` | +| 10 | `QUOTA_EXCEEDED_ERR` | +| 11 | `TYPE_MISMATCH_ERR` | +| 12 | `PATH_EXISTS_ERR` | + +## Configurare il Plugin (opzionale) + +Il set di filesystem disponibili può essere configurato per ogni piattaforma. Sia iOS che Android riconoscere un Tag nel `file config. xml` che nomina il filesystem per essere installato. Per impostazione predefinita, tutte le radici del file system sono abilitate. + + + + + +### Android + + * `files`: directory di archiviazione di file interno dell'applicazione + * `files-external`: directory di archiviazione dell'applicazione file esterno + * `sdcard`: la directory di archiviazione di file esterni globale (questa è la radice della scheda SD, se uno è installato). È necessario disporre dell'autorizzazione `android.permission.WRITE_EXTERNAL_STORAGE` utilizzare questo. + * `cache`: la cache interna directory applicazione + * `cache-external`: directory di cache esterna dell'applicazione + * `root`: il dispositivo intero filesystem + +Android supporta anche un filesystem speciale denominato "documenti", che rappresenta una sottodirectory "/ documenti /" all'interno del filesystem "files". + +### iOS + + * `library`: la directory dell'applicazione libreria + * `documents`: la directory dell'applicazione documenti + * `cache`: la Cache directory applicazione + * `bundle`: bundle dell'applicazione; la posizione dell'app sul disco (sola lettura) + * `root`: il dispositivo intero filesystem + +Per impostazione predefinita, la directory di libreria e documenti può essere sincronizzata a iCloud. È anche possibile richiedere due filesystem aggiuntivi, `library-nosync` e `documents-nosync`, che rappresentano una speciale directory non sincronizzati entro il `/Library` o filesystem `/Documents`. \ No newline at end of file diff --git a/plugins/cordova-plugin-file/doc/it/index.md b/plugins/cordova-plugin-file/doc/it/index.md new file mode 100644 index 0000000..f3cd731 --- /dev/null +++ b/plugins/cordova-plugin-file/doc/it/index.md @@ -0,0 +1,338 @@ + + +# cordova-plugin-file + +Questo plugin implementa un API File permettendo l'accesso di lettura/scrittura ai file che risiedono sul dispositivo. + +Questo plugin si basa su diverse specifiche, tra cui: The HTML5 File API + +Le directory (ormai defunta) e il sistema delle estensioni più recenti: anche se la maggior parte del codice plugin è stato scritto quando una spec precedenti era corrente: + +Implementa inoltre FileWriter spec: + +Per l'utilizzo, fare riferimento a HTML5 Rocks' eccellente [articolo FileSystem.][1] + + [1]: http://www.html5rocks.com/en/tutorials/file/filesystem/ + +Per una panoramica delle altre opzioni di archiviazione, consultare [Guida di archiviazione di Cordova][2]. + + [2]: http://cordova.apache.org/docs/en/edge/cordova_storage_storage.md.html + +Questo plugin definisce oggetto global `cordova.file`. + +Anche se in ambito globale, non è disponibile fino a dopo l'evento `deviceready`. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(cordova.file); + } + + +## Installazione + + cordova plugin add cordova-plugin-file + + +## Piattaforme supportate + +* Amazon fuoco OS +* Android +* BlackBerry 10 +* Firefox OS +* iOS +* Windows Phone 7 e 8 * +* Windows 8 * +* Browser + +* *Queste piattaforme non supportano `FileReader.readAsArrayBuffer` né `FileWriter.write(blob)`.* + +## Dove memorizzare i file + +A partire dalla v 1.2.0, vengono forniti gli URL per le directory importanti file di sistema. Ogni URL è nella forma *file:///path/to/spot/* e può essere convertito in un `DirectoryEntry` utilizzando `window.resolveLocalFileSystemURL()`. + +* `cordova.file.applicationDirectory`-Sola lettura directory dove è installato l'applicazione. (*iOS*, *Android*, *BlackBerry 10*) + +* `cordova.file.applicationStorageDirectory`-Directory radice di sandbox dell'applicazione; su iOS questa posizione è in sola lettura (ma sottodirectory specifiche [come `/Documents` ] sono di sola lettura). Tutti i dati contenuti all'interno è privato all'app. ( *iOS*, *Android*, *BlackBerry 10*) + +* `cordova.file.dataDirectory`-Archiviazione dati persistente e privati nella sandbox dell'applicazione utilizzando la memoria interna (su Android, se è necessario utilizzare la memoria esterna, utilizzare `.externalDataDirectory` ). IOS, questa directory non è sincronizzata con iCloud (utilizzare `.syncedDataDirectory` ). (*iOS*, *Android*, *BlackBerry 10*) + +* `cordova.file.cacheDirectory`-Directory per i file memorizzati nella cache di dati o qualsiasi file che app possibile ricreare facilmente. L'OS può eliminare questi file quando il dispositivo viene eseguito basso sull'archiviazione, tuttavia, apps non deve basarsi sul sistema operativo per cancellare i file qui. (*iOS*, *Android*, *BlackBerry 10*) + +* `cordova.file.externalApplicationStorageDirectory`-Spazio applicazione su storage esterno. (*Android*) + +* `cordova.file.externalDataDirectory`-Dove mettere i file di dati specifico app su storage esterno. (*Android*) + +* `cordova.file.externalCacheDirectory`-Cache applicazione su storage esterno. (*Android*) + +* `cordova.file.externalRootDirectory`-Radice di archiviazione esterna (scheda SD). (*Android*, *BlackBerry, 10*) + +* `cordova.file.tempDirectory`-Temp directory che l'OS è possibile cancellare a volontà. Non fare affidamento sul sistema operativo per cancellare questa directory; l'app deve sempre rimuovere file come applicabile. (*iOS*) + +* `cordova.file.syncedDataDirectory`-Contiene i file app specifiche che devono essere sincronizzati (per esempio a iCloud). (*iOS*) + +* `cordova.file.documentsDirectory`-I file privati per le app, ma che sono significativi per altre applicazioni (ad esempio i file di Office). (*iOS*) + +* `cordova.file.sharedDirectory`-File disponibili globalmente a tutte le applicazioni (*BlackBerry 10*) + +## Layout dei file di sistema + +Anche se tecnicamente un dettaglio di implementazione, può essere molto utile per conoscere come le proprietà `cordova.file.*` mappa di percorsi fisici su un dispositivo reale. + +### iOS File sistema Layout + +| Percorso dispositivo | `Cordova.file.*` | `iosExtraFileSystems` | r/w? | persistente? | OS cancella | sincronizzazione | privato | +|:-------------------------------------------- |:--------------------------- |:--------------------- |:----:|:------------:|:-----------:|:----------------:|:-------:| +| `/ var/mobile/Applications/< UUID > /` | applicationStorageDirectory | - | r | N/A | N/A | N/A | Sì | +|    `appname.app/` | applicationDirectory | bundle | r | N/A | N/A | N/A | Sì | +|       `www/` | - | - | r | N/A | N/A | N/A | Sì | +|    `Documents/` | documentsDirectory | documenti | r/w | Sì | No | Sì | Sì | +|       `NoCloud/` | - | nosync-documenti | r/w | Sì | No | No | Sì | +|    `Library` | - | libreria | r/w | Sì | No | Sì? | Sì | +|       `NoCloud/` | dataDirectory | nosync-libreria | r/w | Sì | No | No | Sì | +|       `Cloud/` | syncedDataDirectory | - | r/w | Sì | No | Sì | Sì | +|       `Caches/` | cacheDirectory | cache | r/w | Sì * | Sì * * *| | No | Sì | +|    `tmp/` | tempDirectory | - | r/w | No * * | Sì * * *| | No | Sì | + +* File persistono attraverso riavvii app e aggiornamenti, ma questa directory può essere azzerata ogni volta che desideri l'OS. L'app dovrebbe essere in grado di ricreare qualsiasi contenuto che potrebbe essere eliminato. + +* * File può persistere attraverso app riavvii, ma non fare affidamento su questo comportamento. I file non sono garantiti a persistere attraverso gli aggiornamenti. L'app deve rimuovere i file dalla directory quando è applicabile, come il sistema operativo non garantisce quando (o anche se) questi file vengono rimossi. + +* * *| Il sistema operativo può cancellare il contenuto di questa directory ogni volta che si sente è necessario, ma non fare affidamento su questo. Si dovrebbe cancellare questa directory come adatto per l'applicazione. + +### Layout sistema Android File + +| Percorso dispositivo | `Cordova.file.*` | `AndroidExtraFileSystems` | r/w? | persistente? | OS cancella | privato | +|:--------------------------------- |:----------------------------------- |:------------------------- |:----:|:------------:|:-----------:|:-------:| +| `File:///android_asset/` | applicationDirectory | | r | N/A | N/A | Sì | +| `< app-id > /dati/dati / /` | applicationStorageDirectory | - | r/w | N/A | N/A | Sì | +|    `cache` | cacheDirectory | cache | r/w | Sì | Sì * | Sì | +|    `files` | dataDirectory | file | r/w | Sì | No | Sì | +|       `Documents` | | documenti | r/w | Sì | No | Sì | +| `< sdcard > /` | externalRootDirectory | sdcard | r/w | Sì | No | No | +|    `Android/data//` | externalApplicationStorageDirectory | - | r/w | Sì | No | No | +|       `cache` | externalCacheDirectry | cache-esterno | r/w | Sì | No * * | No | +|       `files` | externalDataDirectory | file-esterno | r/w | Sì | No | No | + +* Il sistema operativo può cancellare periodicamente questa directory, ma non fare affidamento su questo comportamento. Cancellare il contenuto di questa directory come adatto per l'applicazione. Il contenuto di questa directory dovrebbe un utente eliminare manualmente la cache, vengono rimossi. + +* * Il sistema operativo non cancella questa directory automaticamente; Tu sei responsabile per la gestione dei contenuti da soli. Il contenuto della directory dovrebbe l'utente eliminare manualmente la cache, vengono rimossi. + +**Nota**: se la memorizzazione esterna non può essere montato, le proprietà `cordova.file.external*` sono `null`. + +### BlackBerry 10 File sistema Layout + +| Percorso dispositivo | `Cordova.file.*` | r/w? | persistente? | OS cancella | privato | +|:--------------------------------------------------- |:--------------------------- |:----:|:------------:|:-----------:|:-------:| +| `File:///accounts/1000/AppData/ < id app > /` | applicationStorageDirectory | r | N/A | N/A | Sì | +|    `app/native` | applicationDirectory | r | N/A | N/A | Sì | +|    `data/webviews/webfs/temporary/local__0` | cacheDirectory | r/w | No | Sì | Sì | +|    `data/webviews/webfs/persistent/local__0` | dataDirectory | r/w | Sì | No | Sì | +| `File:///accounts/1000/Removable/sdcard` | externalRemovableDirectory | r/w | Sì | No | No | +| `File:///accounts/1000/Shared` | sharedDirectory | r/w | Sì | No | No | + +*Nota*: quando l'applicazione viene distribuita a lavorare perimetrale, tutti i percorsi sono relativi a /accounts/1000-enterprise. + +## Stranezze Android + +### Posizione di archiviazione persistente Android + +Ci sono più percorsi validi per memorizzare i file persistenti su un dispositivo Android. Vedi [questa pagina][3] per un'ampia discussione delle varie possibilità. + + [3]: http://developer.android.com/guide/topics/data/data-storage.html + +Versioni precedenti del plugin avrebbe scelto il percorso dei file temporanei e permanenti su avvio, in base se il dispositivo ha sostenuto che la scheda SD (o partizione storage equivalente) è stato montato. Se è stata montata sulla scheda SD o una partizione di storage interno grande era disponibile (come sui dispositivi Nexus,) allora saranno memorizzati i file persistenti nella radice di quello spazio. Questo significava che tutte le apps di Cordova poteva vedere tutti i file disponibili sulla carta. + +Se la scheda SD non era disponibile, poi versioni precedenti vuoi memorizzare dati sotto `/data/data/`, che isola i apps da altro, ma può ancora causa dati da condividere tra gli utenti. + +Ora è possibile scegliere se memorizzare i file nel percorso di archiviazione di file interno o utilizzando la logica precedente, con una preferenza nel file `config. xml` dell'applicazione. Per fare questo, aggiungere una di queste due linee al `file config. xml`: + + + + + + +Senza questa linea, il File del plugin utilizzerà la `Compatibility` come predefinito. Se è presente un tag di preferenza e non è uno di questi valori, l'applicazione non si avvia. + +Se l'applicazione è stato spedito in precedenza agli utenti, utilizzando un vecchio (pre-1.0) versione di questo plugin e ha i file memorizzati nel filesystem persistente, allora si dovrebbe impostare la preferenza di `Compatibility`. La posizione su "Interno" di commutazione significherebbe che gli utenti esistenti che aggiornare la loro applicazione potrebbero essere Impossibile accedere ai loro file precedentemente memorizzati, a seconda del loro dispositivo. + +Se l'applicazione è nuova, o ha mai precedentemente memorizzati i file nel filesystem persistente, è generalmente consigliato l'impostazione `Internal`. + +## iOS stranezze + +* `cordova.file.applicationStorageDirectory`è di sola lettura; tentativo di memorizzare i file all'interno della directory radice avrà esito negativo. Utilizzare uno degli altri `cordova.file.*` proprietà definite per iOS (solo `applicationDirectory` e `applicationStorageDirectory` sono di sola lettura). +* `FileReader.readAsText(blob, encoding)` + * Il `encoding` parametro non è supportato, e codifica UTF-8 è sempre attivo. + +### posizione di archiviazione persistente di iOS + +Ci sono due percorsi validi per memorizzare i file persistenti su un dispositivo iOS: la directory documenti e la biblioteca. Precedenti versioni del plugin archiviati solo mai persistenti file nella directory documenti. Questo ha avuto l'effetto collaterale di tutti i file di un'applicazione che rende visibili in iTunes, che era spesso involontaria, soprattutto per le applicazioni che gestiscono un sacco di piccoli file, piuttosto che produrre documenti completi per l'esportazione, che è la destinazione della directory. + +Ora è possibile scegliere se memorizzare i file nella directory di libreria, con una preferenza nel file `config. xml` dell'applicazione o documenti. Per fare questo, aggiungere una di queste due linee al `file config. xml`: + + + + + + +Senza questa linea, il File del plugin utilizzerà la `Compatibility` come predefinito. Se è presente un tag di preferenza e non è uno di questi valori, l'applicazione non si avvia. + +Se l'applicazione è stato spedito in precedenza agli utenti, utilizzando un vecchio (pre-1.0) versione di questo plugin e ha i file memorizzati nel filesystem persistente, allora si dovrebbe impostare la preferenza di `Compatibility`. La posizione di commutazione alla `libreria` significherebbe che gli utenti esistenti che aggiornare la loro applicazione è in grado di accedere ai loro file precedentemente memorizzati. + +Se l'applicazione è nuova, o ha mai precedentemente memorizzati i file nel filesystem persistente, è generalmente consigliato l'impostazione della `Library`. + +## Firefox OS stranezze + +L'API di sistema del File non è supportato nativamente dal sistema operativo Firefox e viene implementato come uno spessore in cima indexedDB. + +* Non manca quando si rimuove le directory non vuota +* Non supporta i metadati per le directory +* Metodi `copyTo` e `moveTo` non supporta le directory + +Sono supportati i seguenti percorsi di dati: * `applicationDirectory` - utilizza `xhr` per ottenere i file locali che sono confezionati con l'app. *`dataDirectory` - per i file di dati persistenti app specifiche. *`cacheDirectory` - file memorizzati nella cache che dovrebbe sopravvivere si riavvia app (applicazioni non devono basarsi sull'OS di eliminare i file qui). + +## Stranezze browser + +### Stranezze e osservazioni comuni + +* Ogni browser utilizza il proprio filesystem in modalità sandbox. IE e Firefox utilizzare IndexedDB come base. Tutti i browser utilizzano barra come separatore di directory in un percorso. +* Le voci di directory devono essere creato successivamente. Ad esempio, la chiamata `fs.root.getDirectory (' dir1/dir2 ', {create:true}, successCallback, errorCallback)` non riuscirà se non esistesse dir1. +* Il plugin richiede autorizzazione utente per utilizzare un archivio permanente presso il primo avvio dell'applicazione. +* Plugin supporta `cdvfile://localhost` (risorse locali) solo. Cioè risorse esterne non sono supportate tramite `cdvfile`. +* Il plugin non segue ["Limitazioni di denominazione 8.3 File sistema API"][4]. +* BLOB e File' `close` la funzione non è supportata. +* `FileSaver` e `BlobBuilder` non sono supportati da questo plugin e non hanno gli stub. +* Il plugin non supporta `requestAllFileSystems`. Questa funzione manca anche nelle specifiche. +* Entrate nella directory non verranno rimossi se si utilizza `create: true` bandiera per directory esistente. +* Non sono supportati i file creati tramite il costruttore. È invece necessario utilizzare il metodo entry.file. +* Ogni browser utilizza la propria forma per riferimenti URL blob. +* `readAsDataURL` funzione è supportata, ma il mediatype in Chrome dipende dall'estensione di voce, mediatype in IE è sempre vuota (che è lo stesso come `text-plain` secondo la specifica), il mediatype in Firefox è sempre `application/octet-stream`. Ad esempio, se il contenuto è `abcdefg` quindi Firefox restituisce `dati: applicazione / octet-stream; base64, YWJjZGVmZw = =`, cioè restituisce `dati:; base64, YWJjZGVmZw = =`, Chrome restituisce `dati: < mediatype a seconda dell'estensione del nome della voce >; base64, YWJjZGVmZw = =`. +* `toInternalURL` restituisce il percorso in forma `file:///persistent/path/to/entry` (Firefox, IE). Chrome restituisce il percorso nella forma `cdvfile://localhost/persistent/file`. + + [4]: http://www.w3.org/TR/2011/WD-file-system-api-20110419/#naming-restrictions + +### Stranezze di cromo + +* Cromo filesystem non è subito pronto dopo evento ready dispositivo. Come soluzione alternativa, è possibile iscriversi all'evento `filePluginIsReady`. Esempio: + + javascript + window.addEventListener('filePluginIsReady', function(){ console.log('File plugin is ready');}, false); + + +È possibile utilizzare la funzione `window.isFilePluginReadyRaised` per verificare se evento già è stato generato. -quote di filesystem TEMPORARY e PERSISTENT window.requestFileSystem non sono limitate in Chrome. -Per aumentare la memoria persistente in Chrome è necessario chiamare il metodo `window.initPersistentFileSystem`. Quota di archiviazione persistente è di 5 MB per impostazione predefinita. -Chrome richiede `-consentire-file-accesso-da-file` eseguire argomento a supporto API tramite protocollo `file:///`. -`File` oggetto non cambierà se si utilizza il flag `{create:true}` quando ottenendo un' esistente `entrata`. -eventi `cancelable` è impostata su true in Chrome. Ciò è in contrasto con la [specifica][5]. -funzione `toURL` Chrome restituisce `filesystem:`-premessi percorso a seconda dell'applicazione host. Ad esempio, `filesystem:file:///persistent/somefile.txt`, `filesystem:http://localhost:8080/persistent/somefile.txt`. -`toURL` risultato di funzione non contiene una barra finale in caso di voce di directory. Chrome risolve le directory con gli URL slash-trainati però correttamente. -`resolveLocalFileSystemURL` metodo richiede in ingresso `url` avere il prefisso del `file System`. Ad esempio, il parametro `url` per `resolveLocalFileSystemURL` dovrebbe essere nella forma `filesystem:file:///persistent/somefile.txt` in contrasto con la forma `file:///persistent/somefile.txt` in Android. -Obsoleto `toNativeURL` funzione non è supportata e non dispone di uno stub. -funzione `setMetadata` non è indicato nelle specifiche e non supportato. -INVALID_MODIFICATION_ERR (codice: 9) viene generata invece di SYNTAX_ERR(code: 8) su richiesta di un filesystem inesistente. -INVALID_MODIFICATION_ERR (codice: 9) viene generata invece di PATH_EXISTS_ERR(code: 12) sul tentativo di creare esclusivamente un file o una directory, che esiste già. -INVALID_MODIFICATION_ERR (codice: 9) viene generata invece di NO_MODIFICATION_ALLOWED_ERR(code: 6) sul tentativo di chiamare removeRecursively su file system root. -INVALID_MODIFICATION_ERR (codice: 9) viene generata invece di NOT_FOUND_ERR(code: 1) sul tentativo moveTo directory che non esiste. + + [5]: http://dev.w3.org/2009/dap/file-system/file-writer.html + +### Stranezze impl IndexedDB-basato (Firefox e IE) + +* `.` e `.` non sono supportati. +* IE non supporta `file:///`-modalità; modalità solo ospitata è supportato (http://localhost:xxxx). +* Dimensione filesystem Firefox non è limitata, ma ogni estensione 50MB sarà richiesta un'autorizzazione dell'utente. IE10 consente fino a 10mb di combinato AppCache e IndexedDB utilizzato nell'implementazione del filesystem senza chiedere conferma, una volta premuto quel livello che vi verrà chiesto se si desidera consentire ad essere aumentata fino a un max di 250 mb per ogni sito. Quindi la `size` parametro per la funzione `requestFileSystem` non influisce il filesystem in Firefox e IE. +* `readAsBinaryString` funzione non è indicato nelle specifiche e non supportati in IE e non dispone di uno stub. +* `file.Type` è sempre null. +* Non è necessario creare la voce utilizzando il risultato del callback istanza DirectoryEntry che è stato eliminato. In caso contrario, si otterrà una 'voce di sospensione'. +* Prima è possibile leggere un file che è stato appena scritto è necessario ottenere una nuova istanza di questo file. +* supporta la funzione `setMetadata`, che non è indicato nelle specifiche `modificationTime` cambiamento di campo solo. +* funzioni `copyTo` e `moveTo` non supporta le directory. +* Le directory metadati non sono supportato. +* Sia Entry.remove e directoryEntry.removeRecursively non fallire quando si rimuove le directory non vuota - directory da rimuovere vengono pulite invece insieme al contenuto. +* `abort` e `truncate` le funzioni non sono supportate. +* non vengono generati eventi di progresso. Ad esempio, questo gestore verrà non eseguito: + + javascript + writer.onprogress = function() { /*commands*/ }; + + +## Note di aggiornamento + +In v 1.0.0 di questo plugin, le strutture `FileEntry` e `DirectoryEntry` sono cambiati, per essere più in linea con le specifiche pubblicate. + +Versioni precedenti (pre-1.0.0) del plugin archiviati il dispositivo-assoluto--percorso del file nella proprietà `fullPath` di oggetti della `voce`. In genere questi percorsi si sarebbe simile + + /var/mobile/Applications//Documents/path/to/file (iOS) + /storage/emulated/0/path/to/file (Android) + + +Questi percorsi sono stati anche restituiti dal metodo `toURL()` degli oggetti `Entry`. + +Con v 1.0.0, l'attributo `fullPath` è il percorso del file, *rispetto alla radice del filesystem HTML*. Così, i percorsi sopra sarebbe ora sia rappresentato da un oggetto `FileEntry` con un `fullPath` di + + /path/to/file + + +Se l'applicazione funziona con dispositivo-assoluto-percorsi, e precedentemente recuperato quei percorsi attraverso la proprietà `fullPath` della `voce` oggetti, è necessario aggiornare il codice per utilizzare `entry.toURL()` invece. + +Per indietro la compatibilità, il metodo `resolveLocalFileSystemURL()` verrà accettare un dispositivo-assoluto-percorso e restituirà un oggetto di `entrata` corrispondente ad essa, fintanto che il file esiste all'interno del filesystem la `temporanea` o `permanente`. + +Questo particolare è stato un problema con il plugin di trasferimento File, che in precedenza utilizzati percorsi-dispositivo-assoluto (e ancora può accoglierli). Esso è stato aggiornato per funzionare correttamente con gli URL di FileSystem, così sostituendo `entry.fullPath` con `entry.toURL()` dovrebbe risolvere eventuali problemi ottenendo quel plugin per lavorare con i file nel dispositivo. + +In v 1.1.0 il valore restituito di `toURL()` è stato cambiato (vedere \[CB-6394\] (https://issues.apache.org/jira/browse/CB-6394)) per restituire un URL assoluto 'file://'. ove possibile. Per assicurare un ' cdvfile:'-URL, è possibile utilizzare `toInternalURL()` ora. Questo metodo restituirà ora filesystem URL del modulo + + cdvfile://localhost/persistent/path/to/file + + +che può essere utilizzato per identificare univocamente il file. + +## Elenco dei codici di errore e significati + +Quando viene generato un errore, uno dei seguenti codici da utilizzare. + +| Codice | Costante | +| ------:|:----------------------------- | +| 1 | `NOT_FOUND_ERR` | +| 2 | `SECURITY_ERR` | +| 3 | `ABORT_ERR` | +| 4 | `NOT_READABLE_ERR` | +| 5 | `ENCODING_ERR` | +| 6 | `NO_MODIFICATION_ALLOWED_ERR` | +| 7 | `INVALID_STATE_ERR` | +| 8 | `SYNTAX_ERR` | +| 9 | `INVALID_MODIFICATION_ERR` | +| 10 | `QUOTA_EXCEEDED_ERR` | +| 11 | `TYPE_MISMATCH_ERR` | +| 12 | `PATH_EXISTS_ERR` | + +## Configurare il Plugin (opzionale) + +Il set di filesystem disponibili può essere configurato per ogni piattaforma. Sia iOS che Android riconoscere un Tag nel `file config. xml` che nomina il filesystem per essere installato. Per impostazione predefinita, tutte le radici del file system sono abilitate. + + + + + +### Android + +* `files`: directory di archiviazione di file interno dell'applicazione +* `files-external`: directory di archiviazione dell'applicazione file esterno +* `sdcard`: la directory di archiviazione di file esterni globale (questa è la radice della scheda SD, se uno è installato). È necessario disporre dell'autorizzazione `android.permission.WRITE_EXTERNAL_STORAGE` utilizzare questo. +* `cache`: la cache interna directory applicazione +* `cache-external`: directory di cache esterna dell'applicazione +* `root`: il dispositivo intero filesystem + +Android supporta anche un filesystem speciale denominato "documenti", che rappresenta una sottodirectory "/ documenti /" all'interno del filesystem "files". + +### iOS + +* `library`: la directory dell'applicazione libreria +* `documents`: la directory dell'applicazione documenti +* `cache`: la Cache directory applicazione +* `bundle`: bundle dell'applicazione; la posizione dell'app sul disco (sola lettura) +* `root`: il dispositivo intero filesystem + +Per impostazione predefinita, la directory di libreria e documenti può essere sincronizzata a iCloud. È anche possibile richiedere due filesystem aggiuntivi, `library-nosync` e `documents-nosync`, che rappresentano una speciale directory non sincronizzati entro il `/Library` o filesystem `/Documents`. diff --git a/plugins/cordova-plugin-file/doc/it/plugins.md b/plugins/cordova-plugin-file/doc/it/plugins.md new file mode 100644 index 0000000..d3f1465 --- /dev/null +++ b/plugins/cordova-plugin-file/doc/it/plugins.md @@ -0,0 +1,101 @@ + + +# Note per gli sviluppatori di plugin + +Queste note sono destinate principalmente per gli sviluppatori di Android e iOS che vogliono scrivere plugin quale interfaccia con il sistema di file utilizzando il File plugin. + +## Lavorando con URL di sistema file di Cordova + +Dalla versione 1.0.0, questo plugin ha utilizzato gli URL con un `cdvfile` schema per tutte le comunicazioni oltre il ponte, piuttosto che esporre i percorsi del file system di dispositivo raw a JavaScript. + +Sul lato JavaScript, questo significa che gli oggetti FileEntry e DirectoryEntry dispongano di un attributo fullPath che è relativo alla directory principale del sistema di file HTML. Se API JavaScript del vostro plugin accetta un oggetto FileEntry o DirectoryEntry, è necessario chiamare `.toURL()` su quell'oggetto prima di passarlo attraverso il ponte in codice nativo. + +### Conversione cdvfile: / / URL ai percorsi fileystem + +Plugin che hanno bisogno di scrivere il filesystem può essere necessario convertire un URL di sistema del file ricevuto in un percorso effettivo filesystem. Ci sono diversi modi di fare questo, a seconda della piattaforma nativa. + +È importante ricordare che non tutti i `cdvfile://` URL sono mappabili ai veri file sul dispositivo. Alcuni URL può riferirsi a beni sul dispositivo che non sono rappresentate da file, o possono anche fare riferimento a risorse remote. A causa di queste possibilità, plugin dovrebbe sempre verificare se ottengono un risultato significativo indietro quando si tenta di convertire gli URL in percorsi. + +#### Android + +Su Android, il metodo più semplice per convertire un `cdvfile://` URL a un percorso di file System è quello di utilizzare `org.apache.cordova.CordovaResourceApi` . `CordovaResourceApi`dispone di diversi metodi che è possono gestire `cdvfile://` URL: + + webView è un membro del Plugin classe CordovaResourceApi resourceApi = webView.getResourceApi(); + + Ottenere un URL file:/// che rappresenta questo file sul dispositivo, / / o lo stesso URL invariata se non può essere mappato a un file Uri fileURL = resourceApi.remapUri(Uri.parse(cdvfileURL)); + + +È anche possibile utilizzare direttamente il File plugin: + + importazione org.apache.cordova.file.FileUtils; + importazione org.apache.cordova.file.FileSystem; + importazione java.net.MalformedURLException; + + Ottenere il File plugin dal gestore plugin FileUtils filePlugin = (FileUtils)webView.pluginManager.getPlugin("File"); + + Dato un URL, ottenere un percorso per esso prova {String path = filePlugin.filesystemPathForURL(cdvfileURL);}} catch (MalformedURLException e) {/ / l'url del file System non è stato riconosciuto} + + +Convertire da un percorso a un `cdvfile://` URL: + + importazione org.apache.cordova.file.LocalFilesystemURL; + + Ottenere un oggetto LocalFilesystemURL per un percorso di dispositivo, / / oppure null se non può essere rappresentata come un URL di cdvfile. + LocalFilesystemURL url = filePlugin.filesystemURLforLocalPath(path); + Ottenere la rappresentazione di stringa dell'URL oggetto String cdvfileURL = url.toString(); + + +Se il vostro plugin crea un file e si desidera restituire un oggetto FileEntry per esso, utilizzare il File plugin: + + Restituire una struttura JSON appropriato per restituire a JavaScript, / / o null se questo file non è rappresentabile come un URL di cdvfile. + Voce di JSONObject = filePlugin.getEntryForFile(file); + + +#### iOS + +Cordova su iOS non utilizza lo stesso `CordovaResourceApi` concetto come Android. Su iOS, si dovrebbe utilizzare il plugin File per convertire tra URL e percorsi di file System. + + Ottenere un oggetto CDVFilesystem URL da una stringa CDVFilesystemURL * url = [CDVFilesystemURL fileSystemURLWithString:cdvfileURL]; + Ottenere un percorso per l'oggetto URL, o zero se non può essere mappato a un percorso di file NSString * = [filePlugin filesystemPathForURL:url]; + + + Ottenere un oggetto CDVFilesystem URL per un percorso di dispositivo, o / / nullo se non può essere rappresentata come un URL di cdvfile. + CDVFilesystemURL * url = [filePlugin fileSystemURLforLocalPath:path]; + Ottenere la rappresentazione di stringa dell'URL oggetto NSString * cdvfileURL = [absoluteString url]; + + +Se il vostro plugin crea un file e si desidera restituire un oggetto FileEntry per esso, utilizzare il File plugin: + + Ottenere un oggetto CDVFilesystem URL per un percorso di dispositivo, o / / nullo se non può essere rappresentata come un URL di cdvfile. + CDVFilesystemURL * url = [filePlugin fileSystemURLforLocalPath:path]; + Ottenere una struttura per tornare alla voce JavaScript NSDictionary * = [filePlugin makeEntryForLocalURL:url] + + +#### JavaScript + +In JavaScript, per ottenere un `cdvfile://` URL da un oggetto FileEntry o DirectoryEntry, semplicemente chiamare `.toURL()` su di esso: + + var cdvfileURL = entry.toURL(); + + +Nei gestori di risposta del plugin, per convertire da una struttura FileEntry restituita in un oggetto reale di voce, il codice del gestore dovrebbe importare il File plugin e creare un nuovo oggetto: + + creare la voce appropriata a voce oggetto var; + Se (entryStruct.isDirectory) {voce = new DirectoryEntry (entryStruct.name, entryStruct.fullPath, nuovo FileSystem(entryStruct.filesystemName));} altro {voce = FileEntry nuovo (entryStruct.name, entryStruct.fullPath, nuovo FileSystem(entryStruct.filesystemName));} \ No newline at end of file diff --git a/plugins/cordova-plugin-file/doc/ja/README.md b/plugins/cordova-plugin-file/doc/ja/README.md new file mode 100644 index 0000000..96e8ff0 --- /dev/null +++ b/plugins/cordova-plugin-file/doc/ja/README.md @@ -0,0 +1,335 @@ + + +# cordova-plugin-file + +[![Build Status](https://travis-ci.org/apache/cordova-plugin-file.svg)](https://travis-ci.org/apache/cordova-plugin-file) + +このプラグインは、デバイス上のファイルへの読み取り/書き込みアクセスを許可するファイル API を実装します。 + +このプラグインを含む、いくつかの仕様に基づいています:、HTML5 File API の + +(今は亡き) ディレクトリとシステムは、最新の拡張機能: プラグインのコードのほとんどはときに、以前の仕様に書かれていたが現在は: + +FileWriter 仕様も実装しています: + +使用法を参照してください HTML5 岩 ' 優秀な[ファイルシステム記事](http://www.html5rocks.com/en/tutorials/file/filesystem/)。 + +他のストレージ オプションの概要については、コルドバの[ストレージ ・ ガイド](http://cordova.apache.org/docs/en/edge/cordova_storage_storage.md.html)を参照してください。. + +このプラグインでは、グローバル `cordova.file` オブジェクトを定義します。 + +グローバル スコープではあるがそれがないまで `deviceready` イベントの後です。 + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(cordova.file); + } + + +## インストール + + cordova plugin add cordova-plugin-file + + +## サポートされているプラットフォーム + + * アマゾン火 OS + * アンドロイド + * ブラックベリー 10 + * Firefox の OS + * iOS + * Windows Phone 7 と 8 * + * Windows 8 * + * Windows* + * ブラウザー + +\* *These platforms do not support `FileReader.readAsArrayBuffer` nor `FileWriter.write(blob)`.* + +## ファイルを保存する場所 + +V1.2.0、現在重要なファイル システム ディレクトリへの Url を提供しています。 各 URL はフォーム *file:///path/to/spot/* で、`window.resolveLocalFileSystemURL()` を使用する `DirectoryEntry` に変換することができます。. + + * `cordova.file.applicationDirectory`-読み取り専用のディレクトリは、アプリケーションがインストールされています。(*iOS*、*アンドロイド*、*ブラックベリー 10*) + + * `cordova.file.applicationStorageDirectory`-アプリケーションのサンド ボックス; のルート ディレクトリiOS でこの場所が読み取り専用 (特定のサブディレクトリが [のような `/Documents` ] は、読み取り/書き込み)。 内に含まれるすべてのデータは、アプリケーションにプライベートです。 ( *iOS*、*アンドロイド*、*ブラックベリー 10*) + + * `cordova.file.dataDirectory`内部メモリを使用して、アプリケーションのサンド ボックス内で永続なプライベート データ ストレージ (外部メモリを使用する必要がある場合使用して Android 上で `.externalDataDirectory` )。 IOS は、このディレクトリは iCloud と同期されません (使用する `.syncedDataDirectory` )。 (*iOS*、*アンドロイド*、*ブラックベリー 10*) + + * `cordova.file.cacheDirectory`-キャッシュされたデータ ファイルやアプリに簡単に再作成できる任意のファイルのディレクトリ。 ストレージ デバイスが不足したときに、OS がこれらのファイルを削除可能性があります、それにもかかわらず、アプリはここにファイルを削除する OS に依存しないでください。 (*iOS*、*アンドロイド*、*ブラックベリー 10*) + + * `cordova.file.externalApplicationStorageDirectory`外部ストレージのアプリケーション領域。(*アンドロイド*) + + * `cordova.file.externalDataDirectory`-外部ストレージ上のアプリ固有のデータ ファイルを配置する場所。(*アンドロイド*) + + * `cordova.file.externalCacheDirectory`外部ストレージにアプリケーション キャッシュ。(*アンドロイド*) + + * `cordova.file.externalRootDirectory`-外部ストレージ (SD カード) ルート。(*アンドロイド*、*ブラックベリー 10*) + + * `cordova.file.tempDirectory`-OS をクリアすることができます temp ディレクトリが。 このディレクトリ; オフに OS に依存しません。アプリが常に該当するファイルを削除します。 (*iOS*) + + * `cordova.file.syncedDataDirectory`-(例えば iCloud) に同期する必要がありますアプリケーション固有のファイルを保持します。(*iOS*) + + * `cordova.file.documentsDirectory`-ファイル、アプリケーションにプライベートは他のアプリケーション (Office ファイルなど) を意味です。(*iOS*) + + * `cordova.file.sharedDirectory`すべてのアプリケーション (*ブラックベリー 10*にグローバルに使用できるファイル) + +## ファイル ・ システム ・ レイアウト + +技術的に実装の詳細、非常にどのように `cordova.file.*` プロパティは、実際のデバイス上の物理パスにマップを知っておくと便利することができます。 + +### iOS ファイル システムのレイアウト + +| デバイス ・ パス | `cordova.file.*` | `iosExtraFileSystems` | r/w ですか? | 永続的なですか? | OS を消去します | 同期 | プライベート | +|:---------------------------------------------- |:--------------------------- |:--------------------- |:--------:|:---------:|:------------:|:------:|:------:| +| `/var/モバイル/アプリケーション/< UUID >/` | applicationStorageDirectory | - | r | N/A | N/A | N/A | はい | +|    `appname.app/` | ディレクトリ | バンドル | r | N/A | N/A | N/A | はい | +|       `www/` | - | - | r | N/A | N/A | N/A | はい | +|    `Documents/` | documentsDirectory | ドキュメント | r/w | はい | いいえ | はい | はい | +|       `NoCloud/` | - | ドキュメント nosync | r/w | はい | いいえ | いいえ | はい | +|    `Library` | - | ライブラリ | r/w | はい | いいえ | はいですか? | はい | +|       `NoCloud/` | dataDirectory | ライブラリ nosync | r/w | はい | いいえ | いいえ | はい | +|       `Cloud/` | syncedDataDirectory | - | r/w | はい | いいえ | はい | はい | +|       `Caches/` | cacheDirectory | キャッシュ | r/w | はい * | はい**\* | いいえ | はい | +|    `tmp/` | tempDirectory | - | r/w | いいえ** | はい**\* | いいえ | はい | + +\ * アプリ再起動やアップグレード、永続化ファイルしますが、OS を希望するたびに、このディレクトリを削除することができます。アプリは削除可能性があります任意のコンテンツを再現することができるはず。 + +**ファイルはアプリ再起動の間続くことがありますが、この動作に依存しないでください。 ファイルは、更新を維持するは保証されません。 アプリが該当する場合このディレクトリからファイルを削除する必要があります、これらのファイルが削除されるとき (または場合でも)、OS は保証しません。 + +**\ * OS はそれ、必要だと感じているときにこのディレクトリの内容を消去可能性があります、これに依存しないようにします。 この適切なディレクトリに、アプリケーションをオフにする必要があります。 + +### 人造人間ファイル ・ システム ・ レイアウト + +| デバイス ・ パス | `cordova.file.*` | `AndroidExtraFileSystems` | r/w ですか? | 永続的なですか? | OS を消去します | プライベート | +|:------------------------------------------------ |:----------------------------------- |:------------------------- |:--------:|:--------:|:---------:|:------:| +| `file:///android_asset/` | ディレクトリ | | r | N/A | N/A | はい | +| `/データ/データ/< app id >/` | applicationStorageDirectory | - | r/w | N/A | N/A | はい | +|    `cache` | cacheDirectory | キャッシュ | r/w | はい | はい\ * | はい | +|    `files` | dataDirectory | ファイル | r/w | はい | いいえ | はい | +|       `Documents` | | ドキュメント | r/w | はい | いいえ | はい | +| `< sd カード >/` | externalRootDirectory | sd カード | r/w | はい | いいえ | いいえ | +|    `Android/data//` | externalApplicationStorageDirectory | - | r/w | はい | いいえ | いいえ | +|       `cache` | externalCacheDirectry | 外部キャッシュ | r/w | はい | いいえ** | いいえ | +|       `files` | externalDataDirectory | 外部ファイル | r/w | はい | いいえ | いいえ | + +\ * OS は定期的にこのディレクトリを消去可能性がありますが、この動作に依存しないでください。 アプリケーションの必要に応じてこのディレクトリの内容をオフにします。 ユーザーは手動でキャッシュを削除する必要があります、このディレクトリの内容が削除されます。 + +** OS はこのディレクトリを自動的にはクリアされません内容を自分で管理する責任があります。 ユーザは手動でキャッシュを消去する必要があります、ディレクトリの内容が削除されます。 + +**注**: 外部記憶装置をマウントできない場合は、`cordova.file.external*` プロパティを `null`. + +### ブラックベリー 10 ファイル ・ システム ・ レイアウト + +| デバイス ・ パス | `cordova.file.*` | r/w ですか? | 永続的なですか? | OS を消去します | プライベート | +|:----------------------------------------------------------- |:--------------------------- |:--------:|:--------:|:---------:|:------:| +| `file:///accounts/1000/appdata/< app id >/` | applicationStorageDirectory | r | N/A | N/A | はい | +|    `app/native` | ディレクトリ | r | N/A | N/A | はい | +|    `data/webviews/webfs/temporary/local__0` | cacheDirectory | r/w | いいえ | はい | はい | +|    `data/webviews/webfs/persistent/local__0` | dataDirectory | r/w | はい | いいえ | はい | +| `file:///accounts/1000/removable/sdcard` | externalRemovableDirectory | r/w | はい | いいえ | いいえ | +| `file:///accounts/1000/shared` | sharedDirectory | r/w | はい | いいえ | いいえ | + +*注*: すべてのパスは/accounts/1000-enterprise 基準に境界を動作するようにアプリケーションを展開するとき。 + +## Android の癖 + +### Android の永続的なストレージの場所 + +Android のデバイスに永続的なファイルを格納する複数の有効な場所があります。 さまざまな可能性について広範な議論のための [このページ](http://developer.android.com/guide/topics/data/data-storage.html) を参照してください。 + +以前のバージョンのプラグインは、デバイスの SD カード (または同等のストレージ パーティション) マウントされていたと主張したかどうかに基づいて、起動時に一時と永続的なファイルの場所を選ぶでしょう。 SD カードがマウントされている場合、または大規模な内部ストレージ パーティションが利用可能な場合 (ようネクサス デバイス上) し、永続的なファイルは、その領域のルートに格納されます。 これはすべての Cordova アプリ見ることができる利用可能なファイルのすべてのカードに意味しました。 + +SD カードがない場合、以前のバージョンがデータを格納する `/data/data/`、お互いからアプリを分離するが、まだ原因可能性がありますユーザー間で共有するデータ。 + +内部ファイルの保存場所やアプリケーションの `config.xml` ファイルに優先順位を持つ以前のロジックを使用してファイルを保存するかどうかを選択することが可能です今。 これを行うに、`config.xml` に次の 2 行のいずれかを追加します。 + + + + + + +この行がなければファイル プラグインはデフォルトとして `Compatibility` を使用します。優先タグが存在し、これらの値の 1 つではない場合、アプリケーションは起動しません。 + +アプリケーションは、ユーザーに以前出荷されている場合、古い (前 1.0) を使用して、このプラグインのバージョンし、永続的なファイルシステムに保存されているファイルには `Compatibility` を設定する必要があります。 自分のアプリケーションをアップグレードする既存のユーザーを彼らの装置によって、以前に保存されたファイルにアクセスすることができることがあることを意味する「内部」に場所をスイッチングします。 + +アプリケーションは、新しい、または永続的なファイルシステムにファイルが格納され以前は決して場合、`内部` 設定一般的に推奨されます。 + +### /Android_asset の低速の再帰的な操作 + +アセット ディレクトリの一覧表示は、人造人間本当に遅いです。 それをスピードアップすることができます`src/android/build-extras.gradle`を android プロジェクトのルートに追加することによって、最大 (また cordova-android@4.0.0 が必要ですまたはそれ以上)。 + +## iOS の癖 + + * `cordova.file.applicationStorageDirectory`読み取り専用;ルート ディレクトリ内のファイルを保存しようは失敗します。 他の 1 つを使用して `cordova.file.*` iOS のため定義されているプロパティ (のみ `applicationDirectory` と `applicationStorageDirectory` は読み取り専用)。 + * `FileReader.readAsText(blob, encoding)` + * `encoding`パラメーターはサポートされていませんし、utf-8 エンコーディングが常に有効です。 + +### iOS の永続的なストレージの場所 + +IOS デバイスに永続的なファイルを格納する 2 つの有効な場所がある: ドキュメントとライブラリのディレクトリ。 プラグインの以前のバージョンは、唯一のこれまでドキュメント ディレクトリに永続的なファイルを格納されます。 これは、ディレクトリの目的は、輸出のための完全なドキュメントを作成するのではなくなかったがしばしば意図されていたり、特に多数の小さいファイルを処理するアプリケーションの場合、iTunes に表示されているすべてのアプリケーションのファイルを作るの副作用があった。 + +ドキュメントまたはアプリケーションの `config.xml` ファイルに優先順位のライブラリ ディレクトリにファイルを保存するかどうかを選択することが可能です今。 これを行うに、`config.xml` に次の 2 行のいずれかを追加します。 + + + + + + +この行がなければファイル プラグインはデフォルトとして `Compatibility` を使用します。優先タグが存在し、これらの値の 1 つではない場合、アプリケーションは起動しません。 + +アプリケーションは、ユーザーに以前出荷されている場合、古い (前 1.0) を使用して、このプラグインのバージョンし、永続的なファイルシステムに保存されているファイルには `Compatibility` を設定する必要があります。 自分のアプリケーションをアップグレードする既存のユーザーを以前に保存されたファイルにアクセスすることができるだろうことを意味する `Library` に場所をスイッチングします。 + +アプリケーションは、新しい、または永続的なファイルシステムにファイルが格納され以前は決して場合、`Library` 設定一般的に推奨されます。 + +## Firefox OS 癖 + +ファイル システム API Firefox OS でネイティブ サポートされていないと、indexedDB の上にシムとして実装されています。 + + * 空でないディレクトリを削除するときに失敗しません + * ディレクトリのメタデータをサポートしていません + * 方法 `copyTo` と `moveTo` ディレクトリをサポートしていません + +次のデータ パスがサポートされています: * `applicationDirectory` - `xhr` を使用して、アプリケーションと共にパッケージ化されるローカル ファイルを取得します。 * `dataDirectory` - 永続的なアプリケーション固有のデータ ファイル。 * `cacheDirectory` - アプリケーションの再起動後も維持する必要がありますキャッシュ ファイル (アプリはここにファイルを削除する OS に依存しないでください)。 + +## ブラウザーの癖 + +### 共通の癖と発言 + + * 各ブラウザーはサンド ボックス化されたファイルシステムを使用します。IE と Firefox IndexedDB をベースとして使用します。すべてのブラウザーは、パスにディレクトリの区切り記号としてスラッシュを使用します。 + * ディレクトリ エントリは連続して作成されなければなりません。 たとえば、コール `fs.root.getDirectory ('dir1 dir2'、{create:true}、successCallback、解り)` dir1 が存在しなかった場合は失敗します。 + * プラグインは、永続的なストレージ アプリケーションの最初の起動時に使用するユーザーのアクセス許可を要求します。 + * プラグインは、`cdvfile://localhost` (ローカル リソース) をサポートしているだけです。すなわち外部リソースは、`cdvfile` を介してサポートされていません. + * プラグインに [制限」のファイル システム API の 8.3 命名規則](http://www.w3.org/TR/2011/WD-file-system-api-20110419/#naming-restrictions) に従っていません。. + * Blob およびファイル ' `close` 関数はサポートされていません。 + * `FileSaver` と `BlobBuilder` このプラグインでサポートされていないスタブを持っていません。 + * プラグインは、`requestAllFileSystems` をサポートしません。この関数は、仕様で行方不明にも。 + * ディレクトリ内のエントリを使用すると削除されません `create: true` 既存ディレクトリのフラグ。 + * コンス トラクターで作成されたファイルはサポートされていません。代わりに entry.file メソッドを使用する必要があります。 + * 各ブラウザーは blob URL 参照の独自のフォームを使用します。 + * `readAsDataURL` 関数はサポートされてがクロムメッキで mediatype エントリ名の拡張子によって異なります、IE でメディアの種類は、常に空 (`text-plain` に従って、仕様と同じである)、Firefox でメディアの種類は常に `アプリケーションまたはオクテット-ストリーム`。 たとえば、コンテンツが場合 `abcdefg` し Firefox を返します `データ: アプリケーション/オクテット ストリーム、base64、YWJjZGVmZw = =`、すなわちを返します `データ:; base64、YWJjZGVmZw = =`、クロムを返します `データ: < エントリ名の拡張子によって mediatype >; base64、YWJjZGVmZw = =`. + * `toInternalURL` フォーム `file:///persistent/path/to/entry` (Firefox、IE) のパスを返します。 クロムの `cdvfile://localhost/persistent/file` フォームのパスを返します. + +### クロムの癖 + + * デバイスの準備ができているイベント後クローム ファイルシステムはすぐに準備ができています。回避策としては `filePluginIsReady` イベントにサブスクライブできます。例: + +```javascript +window.addEventListener('filePluginIsReady', function(){ console.log('File plugin is ready');}, false); +``` + +`window.isFilePluginReadyRaised` 関数を使用して、イベントが既に発生したかどうかを確認できます。 -Chrome に window.requestFileSystem 一時と永続的なファイル ・ システムのクォータの制限はありません。 -クロム内の永続ストレージを増加する `window.initPersistentFileSystem` メソッドを呼び出す必要があります。 永続的な記憶域のクォータは、既定では 5 MB です。 クロムが必要です `--許可-ファイル-アクセス--ファイルから` `file:///` プロトコル経由でサポート API に引数を実行します。 -`ファイル` オブジェクト フラグを使用する場合ない変更されます `{create:true}` 既存の `エントリ` を取得するとき。 -イベント `cancelable` プロパティを設定するクロムの場合は true。 これは [仕様](http://dev.w3.org/2009/dap/file-system/file-writer.html) に反して。 -クロムメッキで `網` 関数を返します `ファイルシステム:`-アプリケーションのホストによってパスのプレフィックスします。 たとえば、`filesystem:file:///persistent/somefile.txt`、`filesystem:http://localhost:8080/persistent/somefile.txt`。 -`toURL` の関数の結果にはディレクトリ エントリ場合末尾にスラッシュが含まれていません。 クロムは、スラッシュ後塵 url を持つディレクトリが正しく解決されるも。 -`resolveLocalFileSystemURL` メソッドは、受信 `url` が `ファイルシステム` のプレフィックスが必要です。 たとえば、`resolveLocalFileSystemURL` の `url` パラメーター フォーム `filesystem:file:///persistent/somefile.txt` で人造人間フォーム `file:///persistent/somefile.txt` とは対照的にする必要があります。 -廃止された `toNativeURL` 関数はサポートされていません、スタブはありません。 -`setMetadata` 関数は、仕様に記載されていないありサポートされていません。 -INVALID_MODIFICATION_ERR (コード: 9) の代わりにスローされた SYNTAX_ERR(code: 8) の非実在しないファイルシステムの依頼を。 -INVALID_MODIFICATION_ERR (コード: 9) の代わりにスローされた PATH_EXISTS_ERR(code: 12)、排他的なファイルまたはディレクトリを作成しようとするが既に存在します。 -INVALID_MODIFICATION_ERR (コード: 9) の代わりにスローされた NO_MODIFICATION_ALLOWED_ERR(code: 6) ルート ・ ファイル ・ システムで removeRecursively を呼び出すをしようとして。 -INVALID_MODIFICATION_ERR (コード: 9) の代わりにスローされた NOT_FOUND_ERR(code: 1) [moveto] ディレクトリが存在しないをしようとして。 + +### IndexedDB ベース インプレ癖 (Firefox と IE) + + * `.` `です。` はサポートされていません。 + * IE は `file:///` をサポートしていません-モード;ホスト モードのみがサポートされている (http://localhost:xxxx) です。 + * Firefox のファイルシステムのサイズは無制限ですが各 50 MB の拡張機能がユーザーのアクセス許可を要求します。 IE10 は最大 10 mb の複合 AppCache と IndexedDB を求めず、サイトごとに 250 mb の最大値まで増加を許可するかどうかをたずねられますそのレベルに当ればファイルシステムの実装で使用することができます。 `RequestFileSystem` 関数の `size` パラメーターは、Firefox と IE のファイルシステムには影響しません。 + * `readAsBinaryString` 関数の仕様に記載されていない、IE でサポートされていないと、スタブを持っていません。 + * `file.type` は、常に null です。 + * 削除された DirectoryEntry インスタンスのコールバックの結果を使用してエントリを作成しないでください。それ以外の場合は、'ハンギングのエントリ' が表示されます。 + * ちょうど書かれていた、ファイルを読むことができます前にこのファイルの新しいインスタンスを取得する必要があります。 + * `setMetadata` 関数は、仕様に記載されていない `modificationTime` フィールド変更のみをサポートします。 + * `copyTo` と `moveTo` 関数ディレクトリをサポートしていません。 + * ディレクトリのメタデータはサポートされていません。 + * 両方の Entry.remove と directoryEntry.removeRecursively は空でないディレクトリを削除するときを失敗しない - 削除されるディレクトリ コンテンツと共にを掃除している代わりに。 + * `abort` し、`truncate` 機能はサポートされていません。 + * 進行状況イベントは起動しません。たとえば、このハンドラーがない実行されます。 + +```javascript +writer.onprogress = function() { /*commands*/ }; +``` + +## ノートをアップグレードします。 + +このプラグインのデベロッパー、公開された仕様に合うように、`認証` と `DirectoryEntry` の構造が変更されました。 + +プラグインの前 (pre 1.0.0) バージョンはデバイス絶対ファイル場所 `エントリ` オブジェクトの `fullPath` プロパティに格納されます。これらのパスはようになります通常 + + /var/mobile/Applications//Documents/path/to/file (iOS) + /storage/emulated/0/path/to/file (Android) + + +これらのパスはまた `Entry` オブジェクトの `toURL()` メソッドによって返されます。 + +デベロッパー、`fullPath` 属性は *HTML ファイルシステムのルートに対する相対パス* のファイルへのパス。 したがって、上記のパスは今両方の `fullPath` と `FileEntry` オブジェクトで表される + + /path/to/file + + +デバイス絶対パスとアプリケーション動作以前 `Entry` オブジェクトの `fullPath` プロパティを使用してこれらのパスを取得した場合は、代わりに `entry.toURL()` を使用するコードを更新する必要があります。 + +下位互換性、`resolveLocalFileSystemURL()` メソッドは、デバイス絶対パスを受け入れるし、は、`TEMPORARY` または `PERSISTENT` ファイル ・ システム内でそのファイルが存在する限り、それに対応する `Entry` オブジェクトを返します。 + +これは特に以前デバイス絶対パスを使用してファイル転送のプラグインで問題となっている (そしてまだそれらを受け入れることができます)。 それがデバイス上のファイルで動作するプラグインを得る問題を解決する必要があります `entry.toURL()` で `entry.fullPath` を置き換えるので、ファイルシステムの Url で正常に動作にアップデートされました。 + +V1.1.0 の `toURL()` の戻り値に変更されました (\[CB-6394\] (https://issues.apache.org/jira/browse/CB-6394) を参照) を絶対 'file://' で始まる URL を返します。 可能な限り。 確保するために、' cdvfile:'-`toInternalURL()` を今すぐ使用できます URL。 このメソッドは、フォームのファイルシステムの Url を返します今 + + cdvfile://localhost/persistent/path/to/file + + +これはファイルを一意に識別するために使用できます。 + +## エラー コードと意味のリスト + +エラーがスローされると、次のコードのいずれかが使用されます。 + +| コード | 定数 | +| ---:|:----------------------------- | +| 1 | `NOT_FOUND_ERR` | +| 2 | `SECURITY_ERR` | +| 3 | `ABORT_ERR` | +| 4 | `NOT_READABLE_ERR` | +| 5 | `ENCODING_ERR` | +| 6 | `NO_MODIFICATION_ALLOWED_ERR` | +| 7 | `INVALID_STATE_ERR` | +| 8 | `SYNTAX_ERR` | +| 9 | `INVALID_MODIFICATION_ERR` | +| 10 | `QUOTA_EXCEEDED_ERR` | +| 11 | `TYPE_MISMATCH_ERR` | +| 12 | `PATH_EXISTS_ERR` | + +## (省略可能) プラグインを構成します。 + +利用可能なファイルシステムのセットは構成されたプラットフォームをすることができます。IOS と Android の両方を認識します。 タグ `config.xml` をインストールするファイルシステムの名前します。既定では、すべてのファイル システムのルートが有効になります。 + + + + + +### アンドロイド + + * `files`: アプリケーションの内部ファイルのストレージ ディレクトリ + * `files-external`: アプリケーションの外部のファイルのストレージ ディレクトリ + * `sdcard`:、グローバル外部ストレージ ディレクトリをファイル (これは SD カードのルートがインストールされている場合)。 これを使用するには、`android.permission.WRITE_EXTERNAL_STORAGE` 権限が必要です。 + * `cache`: アプリケーションの内部キャッシュ ディレクトリ + * `cache-external`: 外部キャッシュのアプリケーションのディレクトリ + * `root`: デバイス全体のファイルシステム + +アンドロイドを「ファイル」ファイルシステム内の"ドキュメント/"サブディレクトリを表す"ドキュメント"という名前の特殊なファイルシステムもサポートしています。 + +### iOS + + * `library`: ライブラリのアプリケーションのディレクトリ + * `documents`: ドキュメントのアプリケーションのディレクトリ + * `cache`: キャッシュのアプリケーションのディレクトリ + * `bundle`: アプリケーションバンドル;アプリ自体 (読み取りのみ) ディスク上の場所 + * `root`: デバイス全体のファイルシステム + +既定では、ライブラリとドキュメント ディレクトリを iCloud に同期できます。 2 つの追加のファイルシステム、`library-nosync` および `documents-nosync` を表す、特別な非同期ディレクトリ内を要求することもできます、`/Library` または `Documents/` ファイルシステム。 \ No newline at end of file diff --git a/plugins/cordova-plugin-file/doc/ja/index.md b/plugins/cordova-plugin-file/doc/ja/index.md new file mode 100644 index 0000000..57fb7d2 --- /dev/null +++ b/plugins/cordova-plugin-file/doc/ja/index.md @@ -0,0 +1,338 @@ + + +# cordova-plugin-file + +このプラグインは、デバイス上のファイルへの読み取り/書き込みアクセスを許可するファイル API を実装します。 + +このプラグインを含む、いくつかの仕様に基づいています:、HTML5 File API の + +(今は亡き) ディレクトリとシステムは、最新の拡張機能: プラグインのコードのほとんどはときに、以前の仕様に書かれていたが現在は: + +FileWriter 仕様も実装しています: + +使用法を参照してください HTML5 岩 ' 優秀な[ファイルシステム記事][1]。 + + [1]: http://www.html5rocks.com/en/tutorials/file/filesystem/ + +他のストレージ オプションの概要については、コルドバの[ストレージ ・ ガイド][2]を参照してください。. + + [2]: http://cordova.apache.org/docs/en/edge/cordova_storage_storage.md.html + +このプラグインでは、グローバル `cordova.file` オブジェクトを定義します。 + +グローバル スコープではあるがそれがないまで `deviceready` イベントの後です。 + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(cordova.file); + } + + +## インストール + + cordova plugin add cordova-plugin-file + + +## サポートされているプラットフォーム + +* アマゾン火 OS +* アンドロイド +* ブラックベリー 10 +* Firefox の OS +* iOS +* Windows Phone 7 と 8 * +* Windows 8 * +* ブラウザー + +* *`FileReader.readAsArrayBuffer` も `FileWriter.write(blob)` もこれらのプラットフォームはサポートしていません*。 + +## ファイルを保存する場所 + +V1.2.0、現在重要なファイル システム ディレクトリへの Url を提供しています。 各 URL はフォーム *file:///path/to/spot/* で、`window.resolveLocalFileSystemURL()` を使用する `DirectoryEntry` に変換することができます。. + +* `cordova.file.applicationDirectory`-読み取り専用のディレクトリは、アプリケーションがインストールされています。(*iOS*、*アンドロイド*、*ブラックベリー 10*) + +* `cordova.file.applicationStorageDirectory`-アプリケーションのサンド ボックス; のルート ディレクトリiOS でこの場所が読み取り専用 (特定のサブディレクトリが [のような `/Documents` ] は、読み取り/書き込み)。 内に含まれるすべてのデータは、アプリケーションにプライベートです。 ( *iOS*、*アンドロイド*、*ブラックベリー 10*) + +* `cordova.file.dataDirectory`内部メモリを使用して、アプリケーションのサンド ボックス内で永続なプライベート データ ストレージ (外部メモリを使用する必要がある場合使用して Android 上で `.externalDataDirectory` )。 IOS は、このディレクトリは iCloud と同期されません (使用する `.syncedDataDirectory` )。 (*iOS*、*アンドロイド*、*ブラックベリー 10*) + +* `cordova.file.cacheDirectory`-キャッシュされたデータ ファイルやアプリに簡単に再作成できる任意のファイルのディレクトリ。 ストレージ デバイスが不足したときに、OS がこれらのファイルを削除可能性があります、それにもかかわらず、アプリはここにファイルを削除する OS に依存しないでください。 (*iOS*、*アンドロイド*、*ブラックベリー 10*) + +* `cordova.file.externalApplicationStorageDirectory`外部ストレージのアプリケーション領域。(*アンドロイド*) + +* `cordova.file.externalDataDirectory`-外部ストレージ上のアプリ固有のデータ ファイルを配置する場所。(*アンドロイド*) + +* `cordova.file.externalCacheDirectory`外部ストレージにアプリケーション キャッシュ。(*アンドロイド*) + +* `cordova.file.externalRootDirectory`-外部ストレージ (SD カード) ルート。(*アンドロイド*、*ブラックベリー 10*) + +* `cordova.file.tempDirectory`-OS をクリアすることができます temp ディレクトリが。 このディレクトリ; オフに OS に依存しません。アプリが常に該当するファイルを削除します。 (*iOS*) + +* `cordova.file.syncedDataDirectory`-(例えば iCloud) に同期する必要がありますアプリケーション固有のファイルを保持します。(*iOS*) + +* `cordova.file.documentsDirectory`-ファイル、アプリケーションにプライベートは他のアプリケーション (Office ファイルなど) を意味です。(*iOS*) + +* `cordova.file.sharedDirectory`すべてのアプリケーション (*ブラックベリー 10*にグローバルに使用できるファイル) + +## ファイル ・ システム ・ レイアウト + +技術的に実装の詳細、非常にどのように `cordova.file.*` プロパティは、実際のデバイス上の物理パスにマップを知っておくと便利することができます。 + +### iOS ファイル システムのレイアウト + +| デバイス ・ パス | `cordova.file.*` | `iosExtraFileSystems` | r/w ですか? | 永続的なですか? | OS を消去します | 同期 | プライベート | +|:------------------------------------ |:--------------------------- |:--------------------- |:--------:|:--------:|:----------:|:------:|:------:| +| `/var/モバイル/アプリケーション/< UUID >/` | applicationStorageDirectory | - | r | N/A | N/A | N/A | はい | +|    `appname.app/` | ディレクトリ | バンドル | r | N/A | N/A | N/A | はい | +|       `www/` | - | - | r | N/A | N/A | N/A | はい | +|    `Documents/` | documentsDirectory | ドキュメント | r/w | はい | いいえ | はい | はい | +|       `NoCloud/` | - | ドキュメント nosync | r/w | はい | いいえ | いいえ | はい | +|    `Library` | - | ライブラリ | r/w | はい | いいえ | はいですか? | はい | +|       `NoCloud/` | dataDirectory | ライブラリ nosync | r/w | はい | いいえ | いいえ | はい | +|       `Cloud/` | syncedDataDirectory | - | r/w | はい | いいえ | はい | はい | +|       `Caches/` | cacheDirectory | キャッシュ | r/w | はい * | はい * * *| | いいえ | はい | +|    `tmp/` | tempDirectory | - | r/w | いいえ * * | はい * * *| | いいえ | はい | + +* アプリを再起動し、アップグレードとの間でファイルを保持が、OS を希望するたびにこのディレクトリを削除することができます。アプリを削除可能性があります任意のコンテンツを再作成することができる必要があります。 + +* * ファイル アプリケーション再起動を渡って続くことがありますが、この動作に依存しないでください。 ファイルは、更新を維持するは保証されません。 アプリが該当する場合このディレクトリからファイルを削除する必要があります、これらのファイルが削除されるとき (または場合でも)、OS は保証しません。 + +* * *| OS はそれ、必要だと感じているときにこのディレクトリの内容を消去可能性がありますが、これに依存しません。 この適切なディレクトリに、アプリケーションをオフにする必要があります。 + +### 人造人間ファイル ・ システム ・ レイアウト + +| デバイス ・ パス | `cordova.file.*` | `AndroidExtraFileSystems` | r/w ですか? | 永続的なですか? | OS を消去します | プライベート | +|:--------------------------------- |:----------------------------------- |:------------------------- |:--------:|:--------:|:---------:|:------:| +| `file:///android_asset/` | ディレクトリ | | r | N/A | N/A | はい | +| `/データ/データ/< app id >/` | applicationStorageDirectory | - | r/w | N/A | N/A | はい | +|    `cache` | cacheDirectory | キャッシュ | r/w | はい | はい * | はい | +|    `files` | dataDirectory | ファイル | r/w | はい | いいえ | はい | +|       `Documents` | | ドキュメント | r/w | はい | いいえ | はい | +| `< sd カード >/` | externalRootDirectory | sd カード | r/w | はい | いいえ | いいえ | +|    `Android/data//` | externalApplicationStorageDirectory | - | r/w | はい | いいえ | いいえ | +|       `cache` | externalCacheDirectry | 外部キャッシュ | r/w | はい | いいえ * * | いいえ | +|       `files` | externalDataDirectory | 外部ファイル | r/w | はい | いいえ | いいえ | + +* OS このディレクトリを定期的に消去可能性がありますが、この動作に依存しないでください。 アプリケーションの必要に応じてこのディレクトリの内容をオフにします。 ユーザーは手動でキャッシュを削除する必要があります、このディレクトリの内容が削除されます。 + +* * OS はこのディレクトリは自動的にクリアされません自分でコンテンツを管理するために責任があります。 ユーザは手動でキャッシュを消去する必要があります、ディレクトリの内容が削除されます。 + +**注**: 外部記憶装置をマウントできない場合は、`cordova.file.external*` プロパティを `null`. + +### ブラックベリー 10 ファイル ・ システム ・ レイアウト + +| デバイス ・ パス | `cordova.file.*` | r/w ですか? | 永続的なですか? | OS を消去します | プライベート | +|:------------------------------------------------- |:--------------------------- |:--------:|:--------:|:---------:|:------:| +| `file:///accounts/1000/appdata/< app id >/` | applicationStorageDirectory | r | N/A | N/A | はい | +|    `app/native` | ディレクトリ | r | N/A | N/A | はい | +|    `data/webviews/webfs/temporary/local__0` | cacheDirectory | r/w | いいえ | はい | はい | +|    `data/webviews/webfs/persistent/local__0` | dataDirectory | r/w | はい | いいえ | はい | +| `file:///accounts/1000/removable/sdcard` | externalRemovableDirectory | r/w | はい | いいえ | いいえ | +| `file:///accounts/1000/shared` | sharedDirectory | r/w | はい | いいえ | いいえ | + +*注*: すべてのパスは/accounts/1000-enterprise 基準に境界を動作するようにアプリケーションを展開するとき。 + +## Android の癖 + +### Android の永続的なストレージの場所 + +Android のデバイスに永続的なファイルを格納する複数の有効な場所があります。 さまざまな可能性について広範な議論のための [このページ][3] を参照してください。 + + [3]: http://developer.android.com/guide/topics/data/data-storage.html + +以前のバージョンのプラグインは、デバイスの SD カード (または同等のストレージ パーティション) マウントされていたと主張したかどうかに基づいて、起動時に一時と永続的なファイルの場所を選ぶでしょう。 SD カードがマウントされている場合、または大規模な内部ストレージ パーティションが利用可能な場合 (ようネクサス デバイス上) し、永続的なファイルは、その領域のルートに格納されます。 これはすべての Cordova アプリ見ることができる利用可能なファイルのすべてのカードに意味しました。 + +SD カードがない場合、以前のバージョンがデータを格納する `/data/data/`、お互いからアプリを分離するが、まだ原因可能性がありますユーザー間で共有するデータ。 + +内部ファイルの保存場所やアプリケーションの `config.xml` ファイルに優先順位を持つ以前のロジックを使用してファイルを保存するかどうかを選択することが可能です今。 これを行うに、`config.xml` に次の 2 行のいずれかを追加します。 + + + + + + +この行がなければファイル プラグインはデフォルトとして `Compatibility` を使用します。優先タグが存在し、これらの値の 1 つではない場合、アプリケーションは起動しません。 + +アプリケーションは、ユーザーに以前出荷されている場合、古い (前 1.0) を使用して、このプラグインのバージョンし、永続的なファイルシステムに保存されているファイルには `Compatibility` を設定する必要があります。 自分のアプリケーションをアップグレードする既存のユーザーを彼らの装置によって、以前に保存されたファイルにアクセスすることができることがあることを意味する「内部」に場所をスイッチングします。 + +アプリケーションは、新しい、または永続的なファイルシステムにファイルが格納され以前は決して場合、`内部` 設定一般的に推奨されます。 + +## iOS の癖 + +* `cordova.file.applicationStorageDirectory`読み取り専用;ルート ディレクトリ内のファイルを保存しようは失敗します。 他の 1 つを使用して `cordova.file.*` iOS のため定義されているプロパティ (のみ `applicationDirectory` と `applicationStorageDirectory` は読み取り専用)。 +* `FileReader.readAsText(blob, encoding)` + * `encoding`パラメーターはサポートされていませんし、utf-8 エンコーディングが常に有効です。 + +### iOS の永続的なストレージの場所 + +IOS デバイスに永続的なファイルを格納する 2 つの有効な場所がある: ドキュメントとライブラリのディレクトリ。 プラグインの以前のバージョンは、唯一のこれまでドキュメント ディレクトリに永続的なファイルを格納されます。 これは、ディレクトリの目的は、輸出のための完全なドキュメントを作成するのではなくなかったがしばしば意図されていたり、特に多数の小さいファイルを処理するアプリケーションの場合、iTunes に表示されているすべてのアプリケーションのファイルを作るの副作用があった。 + +ドキュメントまたはアプリケーションの `config.xml` ファイルに優先順位のライブラリ ディレクトリにファイルを保存するかどうかを選択することが可能です今。 これを行うに、`config.xml` に次の 2 行のいずれかを追加します。 + + + + + + +この行がなければファイル プラグインはデフォルトとして `Compatibility` を使用します。優先タグが存在し、これらの値の 1 つではない場合、アプリケーションは起動しません。 + +アプリケーションは、ユーザーに以前出荷されている場合、古い (前 1.0) を使用して、このプラグインのバージョンし、永続的なファイルシステムに保存されているファイルには `Compatibility` を設定する必要があります。 自分のアプリケーションをアップグレードする既存のユーザーを以前に保存されたファイルにアクセスすることができるだろうことを意味する `Library` に場所をスイッチングします。 + +アプリケーションは、新しい、または永続的なファイルシステムにファイルが格納され以前は決して場合、`Library` 設定一般的に推奨されます。 + +## Firefox OS 癖 + +ファイル システム API Firefox OS でネイティブ サポートされていないと、indexedDB の上にシムとして実装されています。 + +* 空でないディレクトリを削除するときに失敗しません +* ディレクトリのメタデータをサポートしていません +* 方法 `copyTo` と `moveTo` ディレクトリをサポートしていません + +次のデータ パスがサポートされています: * `applicationDirectory` - `xhr` を使用して、アプリケーションと共にパッケージ化されるローカル ファイルを取得します。 * `dataDirectory` - 永続的なアプリケーション固有のデータ ファイル。 * `cacheDirectory` - アプリケーションの再起動後も維持する必要がありますキャッシュ ファイル (アプリはここにファイルを削除する OS に依存しないでください)。 + +## ブラウザーの癖 + +### 共通の癖と発言 + +* 各ブラウザーはサンド ボックス化されたファイルシステムを使用します。IE と Firefox IndexedDB をベースとして使用します。すべてのブラウザーは、パスにディレクトリの区切り記号としてスラッシュを使用します。 +* ディレクトリ エントリは連続して作成されなければなりません。 たとえば、コール `fs.root.getDirectory ('dir1 dir2'、{create:true}、successCallback、解り)` dir1 が存在しなかった場合は失敗します。 +* プラグインは、永続的なストレージ アプリケーションの最初の起動時に使用するユーザーのアクセス許可を要求します。 +* プラグインは、`cdvfile://localhost` (ローカル リソース) をサポートしているだけです。すなわち外部リソースは、`cdvfile` を介してサポートされていません. +* プラグインに [制限」のファイル システム API の 8.3 命名規則][4] に従っていません。. +* Blob およびファイル ' `close` 関数はサポートされていません。 +* `FileSaver` と `BlobBuilder` このプラグインでサポートされていないスタブを持っていません。 +* プラグインは、`requestAllFileSystems` をサポートしません。この関数は、仕様で行方不明にも。 +* ディレクトリ内のエントリを使用すると削除されません `create: true` 既存ディレクトリのフラグ。 +* コンス トラクターで作成されたファイルはサポートされていません。代わりに entry.file メソッドを使用する必要があります。 +* 各ブラウザーは blob URL 参照の独自のフォームを使用します。 +* `readAsDataURL` 関数はサポートされてがクロムメッキで mediatype エントリ名の拡張子によって異なります、IE でメディアの種類は、常に空 (`text-plain` に従って、仕様と同じである)、Firefox でメディアの種類は常に `アプリケーションまたはオクテット-ストリーム`。 たとえば、コンテンツが場合 `abcdefg` し Firefox を返します `データ: アプリケーション/オクテット ストリーム、base64、YWJjZGVmZw = =`、すなわちを返します `データ:; base64、YWJjZGVmZw = =`、クロムを返します `データ: < エントリ名の拡張子によって mediatype >; base64、YWJjZGVmZw = =`. +* `toInternalURL` フォーム `file:///persistent/path/to/entry` (Firefox、IE) のパスを返します。 クロムの `cdvfile://localhost/persistent/file` フォームのパスを返します. + + [4]: http://www.w3.org/TR/2011/WD-file-system-api-20110419/#naming-restrictions + +### クロムの癖 + +* デバイスの準備ができているイベント後クローム ファイルシステムはすぐに準備ができています。回避策としては `filePluginIsReady` イベントにサブスクライブできます。例: + + javascript + window.addEventListener('filePluginIsReady', function(){ console.log('File plugin is ready');}, false); + + +`window.isFilePluginReadyRaised` 関数を使用して、イベントが既に発生したかどうかを確認できます。 -Chrome に window.requestFileSystem 一時と永続的なファイル ・ システムのクォータの制限はありません。 -クロム内の永続ストレージを増加する `window.initPersistentFileSystem` メソッドを呼び出す必要があります。 永続的な記憶域のクォータは、既定では 5 MB です。 クロムが必要です `--許可-ファイル-アクセス--ファイルから` `file:///` プロトコル経由でサポート API に引数を実行します。 -`ファイル` オブジェクト フラグを使用する場合ない変更されます `{create:true}` 既存の `エントリ` を取得するとき。 -イベント `cancelable` プロパティを設定するクロムの場合は true。 これは [仕様][5] に反して。 -クロムメッキで `網` 関数を返します `ファイルシステム:`-アプリケーションのホストによってパスのプレフィックスします。 たとえば、`filesystem:file:///persistent/somefile.txt`、`filesystem:http://localhost:8080/persistent/somefile.txt`。 -`toURL` の関数の結果にはディレクトリ エントリ場合末尾にスラッシュが含まれていません。 クロムは、スラッシュ後塵 url を持つディレクトリが正しく解決されるも。 -`resolveLocalFileSystemURL` メソッドは、受信 `url` が `ファイルシステム` のプレフィックスが必要です。 たとえば、`resolveLocalFileSystemURL` の `url` パラメーター フォーム `filesystem:file:///persistent/somefile.txt` で人造人間フォーム `file:///persistent/somefile.txt` とは対照的にする必要があります。 -廃止された `toNativeURL` 関数はサポートされていません、スタブはありません。 -`setMetadata` 関数は、仕様に記載されていないありサポートされていません。 -INVALID_MODIFICATION_ERR (コード: 9) の代わりにスローされた SYNTAX_ERR(code: 8) の非実在しないファイルシステムの依頼を。 -INVALID_MODIFICATION_ERR (コード: 9) の代わりにスローされた PATH_EXISTS_ERR(code: 12)、排他的なファイルまたはディレクトリを作成しようとするが既に存在します。 -INVALID_MODIFICATION_ERR (コード: 9) の代わりにスローされた NO_MODIFICATION_ALLOWED_ERR(code: 6) ルート ・ ファイル ・ システムで removeRecursively を呼び出すをしようとして。 -INVALID_MODIFICATION_ERR (コード: 9) の代わりにスローされた NOT_FOUND_ERR(code: 1) [moveto] ディレクトリが存在しないをしようとして。 + + [5]: http://dev.w3.org/2009/dap/file-system/file-writer.html + +### IndexedDB ベース インプレ癖 (Firefox と IE) + +* `.` `です。` はサポートされていません。 +* IE は `file:///` をサポートしていません-モード;ホスト モードのみがサポートされている (http://localhost:xxxx) です。 +* Firefox のファイルシステムのサイズは無制限ですが各 50 MB の拡張機能がユーザーのアクセス許可を要求します。 IE10 は最大 10 mb の複合 AppCache と IndexedDB を求めず、サイトごとに 250 mb の最大値まで増加を許可するかどうかをたずねられますそのレベルに当ればファイルシステムの実装で使用することができます。 `RequestFileSystem` 関数の `size` パラメーターは、Firefox と IE のファイルシステムには影響しません。 +* `readAsBinaryString` 関数の仕様に記載されていない、IE でサポートされていないと、スタブを持っていません。 +* `file.type` は、常に null です。 +* 削除された DirectoryEntry インスタンスのコールバックの結果を使用してエントリを作成しないでください。それ以外の場合は、'ハンギングのエントリ' が表示されます。 +* ちょうど書かれていた、ファイルを読むことができます前にこのファイルの新しいインスタンスを取得する必要があります。 +* `setMetadata` 関数は、仕様に記載されていない `modificationTime` フィールド変更のみをサポートします。 +* `copyTo` と `moveTo` 関数ディレクトリをサポートしていません。 +* ディレクトリのメタデータはサポートされていません。 +* 両方の Entry.remove と directoryEntry.removeRecursively は空でないディレクトリを削除するときを失敗しない - 削除されるディレクトリ コンテンツと共にを掃除している代わりに。 +* `abort` し、`truncate` 機能はサポートされていません。 +* 進行状況イベントは起動しません。たとえば、このハンドラーがない実行されます。 + + javascript + writer.onprogress = function() { /*commands*/ }; + + +## ノートをアップグレードします。 + +このプラグインのデベロッパー、公開された仕様に合うように、`認証` と `DirectoryEntry` の構造が変更されました。 + +プラグインの前 (pre 1.0.0) バージョンはデバイス絶対ファイル場所 `エントリ` オブジェクトの `fullPath` プロパティに格納されます。これらのパスはようになります通常 + + /var/mobile/Applications//Documents/path/to/file (iOS) + /storage/emulated/0/path/to/file (Android) + + +これらのパスはまた `Entry` オブジェクトの `toURL()` メソッドによって返されます。 + +デベロッパー、`fullPath` 属性は *HTML ファイルシステムのルートに対する相対パス* のファイルへのパス。 したがって、上記のパスは今両方の `fullPath` と `FileEntry` オブジェクトで表される + + /path/to/file + + +デバイス絶対パスとアプリケーション動作以前 `Entry` オブジェクトの `fullPath` プロパティを使用してこれらのパスを取得した場合は、代わりに `entry.toURL()` を使用するコードを更新する必要があります。 + +下位互換性、`resolveLocalFileSystemURL()` メソッドは、デバイス絶対パスを受け入れるし、は、`TEMPORARY` または `PERSISTENT` ファイル ・ システム内でそのファイルが存在する限り、それに対応する `Entry` オブジェクトを返します。 + +これは特に以前デバイス絶対パスを使用してファイル転送のプラグインで問題となっている (そしてまだそれらを受け入れることができます)。 それがデバイス上のファイルで動作するプラグインを得る問題を解決する必要があります `entry.toURL()` で `entry.fullPath` を置き換えるので、ファイルシステムの Url で正常に動作にアップデートされました。 + +V1.1.0 の `toURL()` の戻り値に変更されました (\[CB-6394\] (https://issues.apache.org/jira/browse/CB-6394) を参照) を絶対 'file://' で始まる URL を返します。 可能な限り。 確保するために、' cdvfile:'-`toInternalURL()` を今すぐ使用できます URL。 このメソッドは、フォームのファイルシステムの Url を返します今 + + cdvfile://localhost/persistent/path/to/file + + +これはファイルを一意に識別するために使用できます。 + +## エラー コードと意味のリスト + +エラーがスローされると、次のコードのいずれかが使用されます。 + +| コード | 定数 | +| ---:|:----------------------------- | +| 1 | `NOT_FOUND_ERR` | +| 2 | `SECURITY_ERR` | +| 3 | `ABORT_ERR` | +| 4 | `NOT_READABLE_ERR` | +| 5 | `ENCODING_ERR` | +| 6 | `NO_MODIFICATION_ALLOWED_ERR` | +| 7 | `INVALID_STATE_ERR` | +| 8 | `SYNTAX_ERR` | +| 9 | `INVALID_MODIFICATION_ERR` | +| 10 | `QUOTA_EXCEEDED_ERR` | +| 11 | `TYPE_MISMATCH_ERR` | +| 12 | `PATH_EXISTS_ERR` | + +## (省略可能) プラグインを構成します。 + +利用可能なファイルシステムのセットは構成されたプラットフォームをすることができます。IOS と Android の両方を認識します。 タグ `config.xml` をインストールするファイルシステムの名前します。既定では、すべてのファイル システムのルートが有効になります。 + + + + + +### アンドロイド + +* `files`: アプリケーションの内部ファイルのストレージ ディレクトリ +* `files-external`: アプリケーションの外部のファイルのストレージ ディレクトリ +* `sdcard`:、グローバル外部ストレージ ディレクトリをファイル (これは SD カードのルートがインストールされている場合)。 これを使用するには、`android.permission.WRITE_EXTERNAL_STORAGE` 権限が必要です。 +* `cache`: アプリケーションの内部キャッシュ ディレクトリ +* `cache-external`: 外部キャッシュのアプリケーションのディレクトリ +* `root`: デバイス全体のファイルシステム + +アンドロイドを「ファイル」ファイルシステム内の"ドキュメント/"サブディレクトリを表す"ドキュメント"という名前の特殊なファイルシステムもサポートしています。 + +### iOS + +* `library`: ライブラリのアプリケーションのディレクトリ +* `documents`: ドキュメントのアプリケーションのディレクトリ +* `cache`: キャッシュのアプリケーションのディレクトリ +* `bundle`: アプリケーションバンドル;アプリ自体 (読み取りのみ) ディスク上の場所 +* `root`: デバイス全体のファイルシステム + +既定では、ライブラリとドキュメント ディレクトリを iCloud に同期できます。 2 つの追加のファイルシステム、`library-nosync` および `documents-nosync` を表す、特別な非同期ディレクトリ内を要求することもできます、`/Library` または `Documents/` ファイルシステム。 diff --git a/plugins/cordova-plugin-file/doc/ja/plugins.md b/plugins/cordova-plugin-file/doc/ja/plugins.md new file mode 100644 index 0000000..c54aa78 --- /dev/null +++ b/plugins/cordova-plugin-file/doc/ja/plugins.md @@ -0,0 +1,101 @@ + + +# プラグイン開発者のためのメモ + +これらのノートは主に Android と iOS 開発者インタ フェース ファイルのプラグインを使用してファイル システムでプラグインを書きたい人向け。 + +## コルドバのファイル システムの Url での作業 + +バージョン 1.0.0 では、以来、このプラグインを含む Url を使用する `cdvfile` JavaScript に raw デバイス ファイル システムのパスを公開するのではなく、橋の上のすべての通信方式します。 + +JavaScript 側では、これはファイルと DirectoryEntry オブジェクトに HTML ファイル システムのルートを基準として、fullPath 属性があることを意味します。 あなたのプラグインの JavaScript API がファイルまたは DirectoryEntry オブジェクトを受け入れる場合を呼び出す必要があります `.toURL()` 橋を渡ってそれをネイティブ コードに渡す前にそのオブジェクトの。 + +### Cdvfile に変換する://fileystem のパスに Url + +ファイルシステムへの書き込みする必要があるプラグインは、実際のファイルシステムの場所に受信したファイル システム URL に変換する必要があります。ネイティブ プラットフォームによって、これを行うための複数の方法があります。 + +それを覚えていることが重要ですすべて `cdvfile://` の Url がデバイス上の実際のファイルをマッピング可能な。 いくつかの Url は、ファイルでは表されないまたはリモート リソースを参照することができますもデバイス上の資産を参照できます。 これらの可能性のためのプラグインは、戻るときにパスに Url を変換しようとして、彼らは意味のある結果を得るかどうか常にテスト必要があります。 + +#### アンドロイド + +アンドロイド, に変換する最も簡単な方法で、 `cdvfile://` を使用するファイルシステムのパスに URL は `org.apache.cordova.CordovaResourceApi` 。 `CordovaResourceApi`扱うことができるいくつかの方法は、 `cdvfile://` の Url: + + webView プラグイン クラス CordovaResourceApi resourceApi のメンバーである = webView.getResourceApi()。 + + デバイスでこのファイルを表す file:///URL を取得//ファイル Uri fileURL にマップできない場合、同じ URL は変更されません = resourceApi.remapUri(Uri.parse(cdvfileURL)); + + +また、ファイルのプラグインを直接使用することが可能です。 + + インポート org.apache.cordova.file.FileUtils; + インポート org.apache.cordova.file.FileSystem; + インポート java.net.MalformedURLException; + + プラグイン マネージャーからファイルのプラグインを入手してコマンド filePlugin = (FileUtils)webView.pluginManager.getPlugin("File"); + + それを試みるためにパスを取得 URL を指定すると、{文字列パス = filePlugin.filesystemPathForURL(cdvfileURL);} キャッチ (MalformedURLException e) {/ファイルシステムの url が認識されませんでした/} + + +パスから変換する、 `cdvfile://` URL: + + インポート org.apache.cordova.file.LocalFilesystemURL; + + デバイス ・ パスの LocalFilesystemURL オブジェクトを取得//cdvfile URL として表現できない場合は null。 + LocalFilesystemURL url = filePlugin.filesystemURLforLocalPath(path); + URL オブジェクトの文字列 cdvfileURL の文字列表現を取得する = url.toString(); + + +あなたのプラグインは、ファイルを作成しをファイル オブジェクトを返す場合、ファイルのプラグインを使用します。 + + JavaScript を返すときに適した JSON 構造を返す//このファイルは cdvfile URL として表現できない場合は null。 + JSONObject エントリ = filePlugin.getEntryForFile(file); + + +#### iOS + +IOS のコルドバは同じを使用しない `CordovaResourceApi` アンドロイドとしての概念。IOS では、Url とファイルシステムのパスの間を変換するファイル プラグインを使用する必要があります。 + + URL の文字列 CDVFilesystemURL * url から CDVFilesystem URL オブジェクトを取得 [CDVFilesystemURL fileSystemURLWithString:cdvfileURL]; + ファイル NSString * パスにマップできない場合は nil または URL オブジェクトのパスを取得 [filePlugin filesystemPathForURL:url]; + + + デバイス ・ パスの CDVFilesystem の URL オブジェクトを取得または//cdvfile URL として表現できない場合は nil です。 + CDVFilesystemURL の url = [filePlugin fileSystemURLforLocalPath:path]; + URL オブジェクト NSString * cdvfileURL の文字列表現を取得する = [url absoluteString]; + + +あなたのプラグインは、ファイルを作成しをファイル オブジェクトを返す場合、ファイルのプラグインを使用します。 + + デバイス ・ パスの CDVFilesystem の URL オブジェクトを取得または//cdvfile URL として表現できない場合は nil です。 + CDVFilesystemURL の url = [filePlugin fileSystemURLforLocalPath:path]; + JavaScript NSDictionary * エントリに戻る構造を得る = [filePlugin makeEntryForLocalURL:url] + + +#### Java スクリプトの設定 + +Java スクリプトの設定を取得するに、 `cdvfile://` ファイルまたは DirectoryEntry オブジェクトからの URL を呼び出して、 `.toURL()` それを。 + + var cdvfileURL = entry.toURL(); + + +プラグイン応答ハンドラーに返された FileEntry 構造体の実際のエントリ オブジェクトを変換する、ハンドラーのコード ファイルのプラグインをインポート、新しいオブジェクトを作成します。 + + 適切なエントリ オブジェクト var エントリを作成します。 + 場合 (entryStruct.isDirectory) {エントリ = 新しい DirectoryEntry (entryStruct.name、entryStruct.fullPath、新しい FileSystem(entryStruct.filesystemName));} 他 {エントリ = 新しいファイル (entryStruct.name、entryStruct.fullPath、新しい FileSystem(entryStruct.filesystemName));} \ No newline at end of file diff --git a/plugins/cordova-plugin-file/doc/ko/README.md b/plugins/cordova-plugin-file/doc/ko/README.md new file mode 100644 index 0000000..a3f3e94 --- /dev/null +++ b/plugins/cordova-plugin-file/doc/ko/README.md @@ -0,0 +1,335 @@ + + +# cordova-plugin-file + +[![Build Status](https://travis-ci.org/apache/cordova-plugin-file.svg)](https://travis-ci.org/apache/cordova-plugin-file) + +이 플러그인은 장치에 있는 파일에 대 한 읽기/쓰기 액세스를 허용 하는 파일 API를 구현 합니다. + +이 플러그인을 포함 한 몇 가지 사양에 따라: HTML5 파일 API는 + +(지금은 없어진) 디렉터리와 시스템 확장 최신: 플러그인 코드의 대부분은 때 이전 사양 작성 되었습니다 있지만 현재는: + +그것은 또한 FileWriter 사양 구현: + +사용을 참조 하십시오 HTML5 바위 ' 우수한 [파일 시스템 문서.](http://www.html5rocks.com/en/tutorials/file/filesystem/) + +다른 저장소 옵션에 대 한 개요, 코르도바의 [저장소 가이드](http://cordova.apache.org/docs/en/edge/cordova_storage_storage.md.html) 를 참조합니다. + +이 플러그인 글로벌 `cordova.file` 개체를 정의합니다. + +전역 범위에 있지만 그것은 불가능까지 `deviceready` 이벤트 후. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(cordova.file); + } + + +## 설치 + + cordova plugin add cordova-plugin-file + + +## 지원 되는 플랫폼 + + * 아마존 화재 운영 체제 + * 안 드 로이드 + * 블랙베리 10 + * Firefox 운영 체제 + * iOS + * Windows Phone 7과 8 * + * 윈도우 8 * + * Windows* + * 브라우저 + +\* *These platforms do not support `FileReader.readAsArrayBuffer` nor `FileWriter.write(blob)`.* + +## 파일을 저장할 위치를 + +V1.2.0, 현재 중요 한 파일 시스템 디렉터리에 Url도 제공 됩니다. 각 URL 형태 *file:///path/to/spot/* 이며 `DirectoryEntry` `window.resolveLocalFileSystemURL()`를 사용 하 여 변환할 수 있습니다.. + + * `cordova.file.applicationDirectory`-읽기 전용 디렉터리는 응용 프로그램을 설치 합니다. (*iOS*, *안 드 로이드*, *블랙베리 10*) + + * `cordova.file.applicationStorageDirectory`응용 프로그램의 샌드박스;의 루트 디렉터리 iOS에이 위치에는 읽기 전용 (특정 하위 디렉토리만 [같은 `/Documents` ]은 읽기 / 쓰기). 포함 된 모든 데이터는 응용 프로그램에 전용. ( *iOS*, *안 드 로이드*, *블랙베리 10*) + + * `cordova.file.dataDirectory`-내부 메모리를 사용 하 여 응용 프로그램의 샌드박스 내에서 영구 및 개인 데이터 스토리지 (안 드 로이드, 외부 메모리를 사용 해야 하는 경우 사용 하 여 `.externalDataDirectory` ). IOS에이 디렉터리 iCloud와 동기화 되지 되 (를 사용 하 여 `.syncedDataDirectory` ). (*iOS*, *안 드 로이드*, *블랙베리 10*) + + * `cordova.file.cacheDirectory`-디렉터리 캐시 데이터 파일 또는 모든 파일을 당신의 app를 다시 쉽게 만들 수 있습니다. 운영 체제 장치 저장소 부족 하면 이러한 파일을 삭제할 수 있습니다, 그리고 그럼에도 불구 하 고, 애플 리 케이 션 여기에 파일을 삭제 하려면 운영 체제에 의존 하지 말아야 합니다. (*iOS*, *안 드 로이드*, *블랙베리 10*) + + * `cordova.file.externalApplicationStorageDirectory`-응용 프로그램 외부 저장 공간입니다. (*안 드 로이드*) + + * `cordova.file.externalDataDirectory`-외부 저장소에 응용 프로그램 특정 데이터 파일을 넣어 어디. (*안 드 로이드*) + + * `cordova.file.externalCacheDirectory`외부 저장소에 응용 프로그램 캐시입니다. (*안 드 로이드*) + + * `cordova.file.externalRootDirectory`-외부 저장 (SD 카드) 루트입니다. (*안 드 로이드*, *블랙베리 10*) + + * `cordova.file.tempDirectory`-운영 체제에서 지울 수 있습니다 임시 디렉터리 것입니다. 이 디렉터리;를 운영 체제에 의존 하지 마십시오 귀하의 응용 프로그램 항상 해당 하는 경우 파일을 제거 해야 합니다. (*iOS*) + + * `cordova.file.syncedDataDirectory`-(ICloud)를 예를 들어 동기화 해야 하는 응용 프로그램 관련 파일을 보유 하 고 있습니다. (*iOS*) + + * `cordova.file.documentsDirectory`-파일 애플 리 케이 션, 하지만 그 개인은 다른 응용 프로그램 (예: Office 파일)에 의미입니다. (*iOS*) + + * `cordova.file.sharedDirectory`-모든 응용 프로그램 (*블랙베리 10* 에 전세계적으로 사용 가능한 파일) + +## 파일 시스템 레이아웃 + +하지만 구현 세부 사항을 기술적으로 `cordova.file.*` 속성 실제 장치에 실제 경로에 매핑하는 방법을 아는 것이 매우 유용할 수 있습니다. + +### iOS 파일 시스템 레이아웃 + +| 장치 경로 | `cordova.file.*` | `iosExtraFileSystems` | r/w? | 영구? | OS 지웁니다 | 동기화 | 개인 | +|:---------------------------------------------- |:--------------------------- |:--------------------- |:----:|:--------:|:-------------:|:---:|:--:| +| `/ var/모바일/응용 프로그램/< UUID > /` | applicationStorageDirectory | - | r | N/A | N/A | N/A | 예 | +|    `appname.app/` | applicationDirectory | 번들 | r | N/A | N/A | N/A | 예 | +|       `www/` | - | - | r | N/A | N/A | N/A | 예 | +|    `Documents/` | documentsDirectory | 문서 | r/w | 예 | 없음 | 예 | 예 | +|       `NoCloud/` | - | 문서 nosync | r/w | 예 | 없음 | 없음 | 예 | +|    `Library` | - | 라이브러리 | r/w | 예 | 없음 | 그래? | 예 | +|       `NoCloud/` | dataDirectory | 라이브러리 nosync | r/w | 예 | 없음 | 없음 | 예 | +|       `Cloud/` | syncedDataDirectory | - | r/w | 예 | 없음 | 예 | 예 | +|       `Caches/` | cacheDirectory | 캐시 | r/w | 예 * | Yes**\* | 없음 | 예 | +|    `tmp/` | tempDirectory | - | r/w | No** | Yes**\* | 없음 | 예 | + +\ * 파일 응용 프로그램 다시 시작 및 업그레이드, 유지 하지만 때마다 OS 욕망이 디렉터리를 지울 수 있습니다. 앱 삭제 될 수 있습니다 모든 콘텐츠를 다시 만들 수 있어야 합니다. + +** 파일 응용 프로그램 다시 시작에서 지속 될 수 있습니다 하지만이 동작에 의존 하지 마십시오. 파일 여러 업데이트를 보장 하지 않습니다. 때 해당 앱이이 디렉터리에서 파일을 제거 해야, 이러한 파일을 제거할 때 (또는 경우에도) 운영 체제 보증 하지 않습니다으로. + +**\ * OS 그것이 필요를 느낀다 언제 든 지이 디렉터리의 내용을 취소 수 있습니다 하지만 이것에 의존 하지 마십시오. 이 디렉터리를 응용 프로그램에 대 한 적절 한 선택을 취소 해야 합니다. + +### 안 드 로이드 파일 시스템 레이아웃 + +| 장치 경로 | `cordova.file.*` | `AndroidExtraFileSystems` | r/w? | 영구? | OS 지웁니다 | 개인 | +|:------------------------------------------------ |:----------------------------------- |:------------------------- |:----:|:---:|:--------:|:--:| +| `file:///android_asset/` | applicationDirectory | | r | N/A | N/A | 예 | +| `/data/데이터/< app id > /` | applicationStorageDirectory | - | r/w | N/A | N/A | 예 | +|    `cache` | cacheDirectory | 캐시 | r/w | 예 | 예\* | 예 | +|    `files` | dataDirectory | 파일 | r/w | 예 | 없음 | 예 | +|       `Documents` | | 문서 | r/w | 예 | 없음 | 예 | +| `< sdcard > /` | externalRootDirectory | sdcard | r/w | 예 | 없음 | 없음 | +|    `Android/data//` | externalApplicationStorageDirectory | - | r/w | 예 | 없음 | 없음 | +|       `cache` | externalCacheDirectry | 외부 캐시 | r/w | 예 | 없음** | 없음 | +|       `files` | externalDataDirectory | 파일 외부 | r/w | 예 | 없음 | 없음 | + +\ * 운영 체제 정기적으로이 디렉터리 삭제 수 있지만이 동작에 의존 하지 마십시오. 이 응용 프로그램이 디렉터리의 내용을 취소 합니다. 사용자 수동으로 캐시 제거 해야,이 디렉터리의 내용은 제거 됩니다. + +** 운영 체제 자동으로;이 디렉터리를 삭제 하지 않습니다 내용을 직접 관리에 대 한 책임이 있습니다. 사용자 수동으로 캐시 제거 합니다, 디렉터리의 내용은 제거 됩니다. + +**참고**: 외부 저장소를 탑재할 수 없는 경우 `cordova.file.external*` 속성은 `null`. + +### 블랙베리 10 파일 시스템 레이아웃 + +| 장치 경로 | `cordova.file.*` | r/w? | 영구? | OS 지웁니다 | 개인 | +|:----------------------------------------------------------- |:--------------------------- |:----:|:---:|:-------:|:--:| +| `file:///accounts/1000/appdata/ < app id > /` | applicationStorageDirectory | r | N/A | N/A | 예 | +|    `app/native` | applicationDirectory | r | N/A | N/A | 예 | +|    `data/webviews/webfs/temporary/local__0` | cacheDirectory | r/w | 없음 | 예 | 예 | +|    `data/webviews/webfs/persistent/local__0` | dataDirectory | r/w | 예 | 없음 | 예 | +| `file:///accounts/1000/removable/sdcard` | externalRemovableDirectory | r/w | 예 | 없음 | 없음 | +| `file:///accounts/1000/shared` | sharedDirectory | r/w | 예 | 없음 | 없음 | + +*참고*: 모든 경로 /accounts/1000-enterprise를 기준으로 응용 프로그램 경계를 작동 하도록 배포 될 때. + +## 안 드 로이드 단점 + +### 안 드 로이드 영구 저장 위치 + +안 드 로이드 장치에 영구 파일을 저장할 여러 유효한 위치가 있다. 다양 한 가능성의 광범위 한 토론에 대 한 [이 페이지](http://developer.android.com/guide/topics/data/data-storage.html)를 참조 하십시오. + +플러그인의 이전 버전을 시작할 때, 장치는 SD 카드 (또는 해당 스토리지 파티션) 탑재 했다 주장 하는 여부에 따라 임시 및 영구 파일의 위치를 선택 합니다. SD 카드 마운트, 또는 큰 내부 스토리지 파티션에 사용할 수 있었습니다 (같은 넥서스 장치에) 그 후에 영구 파일 공간의 루트에 저장 됩니다. 이 모든 코르 도우 바 애플 리 케이 션 카드에 모두 사용할 수 있는 파일을 볼 수 있는 의미 합니다. + +SD 카드는 사용할 수 있는 경우 이전 버전에서 데이터 저장 `/data/data/`는 서로 다른 애플 리 케이 션을 분리 하지만 여전히 원인 데이터를 사용자 간에 공유할 수 있습니다. + +그것은 지금 내부 파일 저장 위치 또는 응용 프로그램의 `config.xml` 파일에 기본 설정으로 이전 논리를 사용 하 여 파일을 저장할 것인지를 선택할 수 있습니다. 이렇게 하려면 `config.xml`에이 두 줄 중 하나를 추가: + + + + + + +이 줄이 없으면 파일 플러그인은 기본적으로 `Compatibility`을 사용 합니다. 기본 태그,이 이러한 값 중 하나가 아닌 경우에 응용 프로그램이 시작 되지 않습니다. + +이전 (사전 1.0)을 사용 하는 경우 응용 프로그램 사용자에 게 발송 되었다 이전,이 플러그인의 버전 영구 파일 시스템에 저장 된 파일은 그리고 `Compatibility` 환경 설정을 설정 해야 합니다. "내부"의 위치 전환 그들의 응용 프로그램을 업그레이드 기존 사용자의 그들의 장치에 따라 그들의 이전에 저장 된 파일에 액세스할 수 수 있다는 뜻입니다. + +경우 응용 프로그램은 새로운, 또는 이전 영구 파일 시스템에 파일을 저장, `Internal` 설정은 일반적으로 권장 됩니다. + +### /Android_asset에 대 한 느린 재귀 작업 + +자산 디렉터리를 나열 하는 것은 안 드 로이드에 정말 느리다입니다. 속도 높일 수 있습니다 하지만, 안 드 로이드 프로젝트의 루트에 `src/android/build-extras.gradle` 를 추가 하 여 최대 (cordova-android@4.0.0 필요 이상). + +## iOS 단점 + + * `cordova.file.applicationStorageDirectory`읽기 전용; 루트 디렉터리 내에서 파일을 저장 하려고에 실패 합니다. 다른 중 하나를 사용 하 여 `cordova.file.*` iOS에 대해 정의 된 속성 (만 `applicationDirectory` 와 `applicationStorageDirectory` 는 읽기 전용). + * `FileReader.readAsText(blob, encoding)` + * `encoding`매개 변수는 지원 되지 않습니다, 및 효과에 항상 u t F-8 인코딩을 합니다. + +### iOS 영구 저장소 위치 + +IOS 디바이스에 영구 파일을 저장할 두 개의 유효한 위치가 있다: 문서 디렉터리 및 라이브러리 디렉터리. 플러그인의 이전 버전은 오직 문서 디렉토리에 영구 파일을 저장. 이 부작용 보다는 아니었다 수시로 특히 많은 작은 파일을 처리 하는 응용 프로그램에 대 한 의도, iTunes에 표시 모든 응용 프로그램 파일을 만드는 디렉터리의 용도 내보내기에 대 한 완전 한 문서를 생산 했다. + +그것은 지금 문서 또는 응용 프로그램의 `config.xml` 파일에 기본 설정으로 라이브러리 디렉토리에 파일을 저장할 것인지를 선택할 수 있습니다. 이렇게 하려면 `config.xml`에이 두 줄 중 하나를 추가: + + + + + + +이 줄이 없으면 파일 플러그인은 기본적으로 `Compatibility`을 사용 합니다. 기본 태그,이 이러한 값 중 하나가 아닌 경우에 응용 프로그램이 시작 되지 않습니다. + +이전 (사전 1.0)을 사용 하는 경우 응용 프로그램 사용자에 게 발송 되었다 이전,이 플러그인의 버전 영구 파일 시스템에 저장 된 파일은 그리고 `Compatibility` 환경 설정을 설정 해야 합니다. `Library`에 위치를 스위칭 기존 사용자에 게 응용 프로그램을 업그레이 드의 그들의 이전에 저장 된 파일에 액세스할 수 것을 의미할 것입니다. + +경우 응용 프로그램은 새로운, 또는 이전 영구 파일 시스템에 파일을 저장, `Library` 설정은 일반적으로 권장 됩니다. + +## 파이어 폭스 OS 단점 + +파일 시스템 API Firefox 운영 체제에서 기본적으로 지원 하지 및 indexedDB 위에 심으로 구현 됩니다. + + * 비어 있지 않은 디렉터리를 제거할 때 실패 하지 않습니다. + * 디렉터리에 대 한 메타 데이터를 지원 하지 않습니다. + * 메서드 `copyTo` 및 `moveTo` 디렉터리를 지원 하지 않습니다 + +다음 데이터 경로 지원 됩니다: * `applicationDirectory`-`xhr`를 사용 하 여 로컬 파일을 응용 프로그램 패키지를 가져옵니다. * `dataDirectory`-영구 응용 프로그램 특정 데이터 파일에 대 한. * `cacheDirectory`-응용 프로그램 다시 시작 해야 하는 캐시 된 파일 (애플 리 케이 션은 여기에 파일을 삭제 하려면 운영 체제에 의존 하지 말아야). + +## 브라우저 만지면 + +### 일반적인 단점 및 설명 + + * 각 브라우저는 샌드박스 자체 파일 시스템을 사용합니다. IE와 파이어 폭스 기반으로 IndexedDB를 사용합니다. 모든 브라우저는 경로에서 디렉터리 구분 기호로 슬래시를 사용합니다. + * 디렉터리 항목을 연속적으로 만들 수 있다. 예를 들어 전화 `fs.root.getDirectory ('dir1/dir2 ', {create:true}, successCallback, errorCallback)` d i r 1 존재 하지 않은 경우 실패 합니다. + * 플러그인 응용 프로그램 처음 시작할 영구 저장소를 사용 하 여 사용자 권한을 요청 합니다. + * 플러그인 지원 `cdvfile://localhost` (로컬 리소스)만. 즉, 외부 리소스는 `cdvfile`를 통해 지원 되지 않습니다.. + * 플러그인 ["파일 시스템 API 8.3 명명 제한"을](http://www.w3.org/TR/2011/WD-file-system-api-20110419/#naming-restrictions) 수행 하지 않습니다.. + * Blob 및 파일 ' `close` 함수는 지원 되지 않습니다. + * `FileSaver` 및 `BlobBuilder`는이 플러그 접속식에 의해 지원 되지 않습니다 그리고 명세서를 필요가 없습니다. + * 플러그인 `requestAllFileSystems`를 지원 하지 않습니다. 이 함수는 또한 사양에 빠진. + * 사용 하는 경우 디렉터리에서 항목 제거 되지 것입니다 `create: true` 기존 디렉터리에 대 한 플래그. + * 생성자를 통해 생성 된 파일은 지원 되지 않습니다. Entry.file 메서드를 대신 사용 해야 합니다. + * 각 브라우저 blob URL 참조에 대 한 그것의 자신의 형태를 사용합니다. + * `readAsDataURL` 기능을 지원 하지만 크롬에서 mediatype 항목 이름 확장명에 따라 달라 집니다, 그리고 mediatype IE에는 항상 빈 (`텍스트 일반` 사양에 따라 동일), 파이어 폭스에서 mediatype은 항상 `응용 프로그램/8 진수 스트림`. 예를 들어, 콘텐츠는 `abcdefg` 다음 파이어 폭스 반환 `데이터: 응용 프로그램 / 8 진수 스트림; base64, YWJjZGVmZw = =`, 즉 반환 `데이터:; base64, YWJjZGVmZw = =`, 반환 크롬 `데이터: < 항목 이름의 확장에 따라 mediatype >; base64, YWJjZGVmZw = =`. + * `toInternalURL` 양식 `file:///persistent/path/to/entry` (파이어 폭스, 인터넷 익스플로러)에서 경로 반환합니다. 크롬 양식 `cdvfile://localhost/persistent/file`에 경로 반환합니다.. + +### 크롬 특수 + + * 크롬 파일 시스템 장치 준비 이벤트 후 즉시 준비 되지 않습니다. 문제를 해결 하려면 `filePluginIsReady` 이벤트를 구독할 수 있습니다. 예를 들어: + +```javascript +window.addEventListener('filePluginIsReady', function(){ console.log('File plugin is ready');}, false); +``` + +`Window.isFilePluginReadyRaised` 함수를 사용 하 여 이벤트가 이미 발생 여부를 확인할 수 있습니다. -window.requestFileSystem 임시 및 영구 파일 시스템 할당량 크롬에 제한 되지 않습니다. -크롬에서 영구 저장소를 증가 하려면 `window.initPersistentFileSystem` 메서드를 호출 해야 합니다. 영구 저장소 할당량은 기본적으로 5 메가바이트입니다. -크롬 필요 `-허용-파일-액세스-에서-파일` `file:///` 프로토콜을 통해 지원 API 인수를 실행 합니다. -플래그를 사용 하면 `파일` 개체 하지 변경할 수 `{create:true}` 때 기존 `항목`. -행사 `cancelable` 속성이로 설정 된 크롬에서. 이 [사양](http://dev.w3.org/2009/dap/file-system/file-writer.html) 대조적 이다. -크롬에서 `toURL` 함수 반환 합니다 `파일 시스템:`-응용 프로그램 호스트에 따라 경로 앞에. 예를 들어, `filesystem:file:///persistent/somefile.txt`, `filesystem:http://localhost:8080/persistent/somefile.txt`. -`toURL` 함수 결과 디렉터리 항목의 경우에 후행 슬래시를 포함 하지 않습니다. 크롬 하지만 제대로 붙여 슬래시 url이 포함 된 디렉터리 해결합니다. -`resolveLocalFileSystemURL` 메서드 인바운드 `url`을 `파일 시스템` 접두사가 필요 합니다. 예를 들어, `url` 매개 변수 `resolveLocalFileSystemURL`에 대 한 안 드 로이드에서 양식 `file:///persistent/somefile.txt` 반대로 양식 `filesystem:file:///persistent/somefile.txt`에 있어야 합니다. -사용 되지 않는 `toNativeURL` 함수는 지원 되지 않습니다 및 stub에는 없습니다. -`setMetadata` 함수는 규격에 명시 되지 않은 및 지원 되지 않습니다. -INVALID_MODIFICATION_ERR (코드: 9) 대신 throw 됩니다 SYNTAX_ERR(code: 8) 비 existant 파일 시스템의 요청에. -INVALID_MODIFICATION_ERR (코드: 9) 대신 throw 됩니다 PATH_EXISTS_ERR(code: 12) 독점적으로 파일 또는 디렉터리를 만들 려,는 이미 존재 합니다. -INVALID_MODIFICATION_ERR (코드: 9) 대신 throw 됩니다 NO_MODIFICATION_ALLOWED_ERR(code: 6) 루트 파일 시스템에 removeRecursively을 호출 하려고 합니다. -INVALID_MODIFICATION_ERR (코드: 9) 대신 throw 됩니다 NOT_FOUND_ERR(code: 1) moveTo 디렉터리 존재 하지 않는 것을 시도에. + +### IndexedDB 기반 구현이 특수 (파이어 폭스와 IE) + + * `.` `.`는 지원 되지 않습니다. + * IE `file:///`를 지원 하지 않습니다-모드; 호스트 모드 지원된 (http://localhost:xxxx)입니다. + * 파이어 폭스 파일 시스템 크기 제한 이지만 각 50MB 확장 사용자 권한을 요청 합니다. IE10 최대 10 mb 결합 AppCache 및 IndexedDB 묻는 사이트 당 250 mb의 최대 최대 증가 될 수 있도록 하려는 경우 해당 수준에 충돌 한 번 메시지를 표시 하지 않고 파일 시스템의 구현에 사용을 허용 한다. 그래서 `size` 매개 변수 `requestFileSystem` 함수에 대 한 파이어 폭스와 IE에서 파일 시스템 영향을 주지 않습니다. + * `readAsBinaryString` 함수 사양에 명시 되지 않은 IE에서 지원 되지 않으며 stub에는 없습니다. + * `file.type`은 항상 null입니다. + * 하지 항목 삭제 된 DirectoryEntry 인스턴스의 콜백 결과 사용 하 여 만들어야 합니다. 그렇지 않으면, '교수형 항목'을 얻을 것 이다. + * 그냥 작성 된 파일을 읽을 수 있는이 파일의 새 인스턴스를 얻으려면 해야 합니다. + * `setMetadata` 함수는 사양에 명시 되지 않은 지원 `modificationTime` 필드 변경에만 해당 합니다. + * `copyTo` 및 `moveTo` 함수는 디렉터리를 지원 하지 않습니다. + * 디렉터리 메타 데이터는 지원 되지 않습니다. + * 둘 다 Entry.remove와 directoryEntry.removeRecursively 비어 있지 않은 디렉터리를 제거할 때 실패 하지 않습니다-디렉터리 제거 되는 대신 내용을 함께 청소. + * `abort` 및 `truncate` 함수 지원 되지 않습니다. + * 진행 이벤트가 발생 하지 합니다. 예를 들어,이 처리기 하지 실행 됩니다. + +```javascript +writer.onprogress = function() { /*commands*/ }; +``` + +## 업그레이드 노트 + +이 플러그인의 v1.0.0에 게시 된 사양에 맞춰 더 많은 것 `FileEntry` 및 `DirectoryEntry` 구조 변경 되었습니다. + +플러그인의 이전 (pre-1.0.0) 버전 장치 절대 파일 위치 `Entry` 개체의 `fullPath` 속성에 저장 됩니다. 이러한 경로 일반적으로 같습니다. + + /var/mobile/Applications//Documents/path/to/file (iOS) + /storage/emulated/0/path/to/file (Android) + + +이러한 경로 `항목` 개체의 `toURL()` 메서드에서 반환 했다. + +V1.0.0, `fullPath` 속성은 *HTML 파일 시스템의 루트에 상대적인* 파일의 경로를. 그래서, 위의 경로 지금 둘 다의 `fullPath`와 `FileEntry` 개체에 의해 표현 될 것 이다 + + /path/to/file + + +응용 프로그램 작동 장치 절대 경로, 이전 `항목` 개체의 `fullPath` 속성을 통해 그 경로 검색 하는 경우에, 당신은 대신 `entry.toURL()`를 사용 하 여 코드를 업데이트 해야 합니다. + +대 한 뒤 호환성, `resolveLocalFileSystemURL()` 메서드는 장치-절대-경로 수락 하 고 그 파일 중 `TEMPORARY` 또는 `PERSISTENT` 파일 시스템 내에서 존재 하는 경우, 해당 `Entry` 개체를 반환 합니다. + +이 특히 이전 장치 절대 경로 사용 하는 파일 전송 플러그인에 문제가 있다 (그리고 아직도 그들을 받아들일 수.) 그것은 `entry.toURL()`와 `entry.fullPath`를 대체 확인 장치에 파일을 사용 하는 플러그인을 지 고 그래서 파일 시스템 Url와 함께 제대로 작동 하려면 업데이트 되었습니다. + +V1.1.0에 `toURL()`의 반환 값 (\[CB-6394\] (https://issues.apache.org/jira/browse/CB-6394) 참조)로 바뀌었다 'file://' 절대 URL을 반환. 가능 하다 면. 보장 하는 ' cdvfile:'-URL `toInternalURL()`를 지금 사용할 수 있습니다. 이 메서드 이제 양식의 파일 Url을 반환 합니다. + + cdvfile://localhost/persistent/path/to/file + + +어떤 파일을 고유 하 게 식별 하려면 사용할 수 있습니다. + +## 오류 코드 및 의미의 목록 + +오류가 throw 됩니다 때 다음 코드 중 하나가 사용 됩니다. + +| 코드 | 상수 | +| --:|:----------------------------- | +| 1 | `NOT_FOUND_ERR` | +| 2 | `SECURITY_ERR` | +| 3 | `ABORT_ERR` | +| 4 | `NOT_READABLE_ERR` | +| 5 | `ENCODING_ERR` | +| 6 | `NO_MODIFICATION_ALLOWED_ERR` | +| 7 | `INVALID_STATE_ERR` | +| 8 | `SYNTAX_ERR` | +| 9 | `INVALID_MODIFICATION_ERR` | +| 10 | `QUOTA_EXCEEDED_ERR` | +| 11 | `TYPE_MISMATCH_ERR` | +| 12 | `PATH_EXISTS_ERR` | + +## (선택 사항) 플러그인 구성 + +사용 가능한 파일 시스템의 집합 플랫폼 당 구성된 될 수 있습니다. IOS와 안 드 로이드를 인식 한 `config.xml` 설치 될 파일 시스템 이름에 태그. 기본적으로 모든 파일 시스템 루트 사용할 수 있습니다. + + + + + +### 안 드 로이드 + + * `files`: 응용 프로그램의 내부 파일 저장 디렉토리 + * `files-external`: 응용 프로그램의 외부 파일 저장 디렉토리 + * `sdcard`: 글로벌 외부 파일 저장 디렉토리 (이것은 SD 카드의 루트 설치 된 경우). 이것을 사용 하려면 `android.permission.WRITE_EXTERNAL_STORAGE` 권한이 있어야 합니다. + * `cache`: 응용 프로그램의 내부 캐시 디렉터리 + * `cache-external`: 응용 프로그램의 외부 캐시 디렉터리 + * `root`: 전체 장치 파일 시스템 + +안 드 로이드는 또한 "파일" 파일 시스템 내에서 "/ 문서 /" 하위 디렉토리를 나타내는 "문서" 라는 특별 한 파일을 지원 합니다. + +### iOS + + * `library`: 응용 프로그램의 라이브러리 디렉터리 + * `documents`: 응용 프로그램의 문서 디렉토리 + * `cache`: 응용 프로그램의 캐시 디렉터리 + * `bundle`: 응용 프로그램의 번들; (읽기 전용) 디스크에 응용 프로그램 자체의 위치 + * `root`: 전체 장치 파일 시스템 + +기본적으로 라이브러리 및 문서 디렉토리 iCloud에 동기화 할 수 있습니다. 또한 2 개의 추가적인 파일 시스템, `library-nosync` 및 `documents-nosync`, 내 특별 한 동기화 되지 않은 디렉터리를 대표 하는 요청할 수 있습니다는 `/Library` 또는 `/Documents` 파일 시스템. \ No newline at end of file diff --git a/plugins/cordova-plugin-file/doc/ko/index.md b/plugins/cordova-plugin-file/doc/ko/index.md new file mode 100644 index 0000000..08340d8 --- /dev/null +++ b/plugins/cordova-plugin-file/doc/ko/index.md @@ -0,0 +1,338 @@ + + +# cordova-plugin-file + +이 플러그인은 장치에 있는 파일에 대 한 읽기/쓰기 액세스를 허용 하는 파일 API를 구현 합니다. + +이 플러그인을 포함 한 몇 가지 사양에 따라: HTML5 파일 API는 + +(지금은 없어진) 디렉터리와 시스템 확장 최신: 플러그인 코드의 대부분은 때 이전 사양 작성 되었습니다 있지만 현재는: + +그것은 또한 FileWriter 사양 구현: + +사용을 참조 하십시오 HTML5 바위 ' 우수한 [파일 시스템 문서.][1] + + [1]: http://www.html5rocks.com/en/tutorials/file/filesystem/ + +다른 저장소 옵션에 대 한 개요, 코르도바의 [저장소 가이드][2] 를 참조합니다. + + [2]: http://cordova.apache.org/docs/en/edge/cordova_storage_storage.md.html + +이 플러그인 글로벌 `cordova.file` 개체를 정의합니다. + +전역 범위에 있지만 그것은 불가능까지 `deviceready` 이벤트 후. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(cordova.file); + } + + +## 설치 + + cordova plugin add cordova-plugin-file + + +## 지원 되는 플랫폼 + +* 아마존 화재 운영 체제 +* 안 드 로이드 +* 블랙베리 10 +* Firefox 운영 체제 +* iOS +* Windows Phone 7과 8 * +* 윈도우 8 * +* 브라우저 + +* *`FileReader.readAsArrayBuffer`도 `FileWriter.write(blob)`이 플랫폼을 지원 하지 않습니다.* + +## 파일을 저장할 위치를 + +V1.2.0, 현재 중요 한 파일 시스템 디렉터리에 Url도 제공 됩니다. 각 URL 형태 *file:///path/to/spot/* 이며 `DirectoryEntry` `window.resolveLocalFileSystemURL()`를 사용 하 여 변환할 수 있습니다.. + +* `cordova.file.applicationDirectory`-읽기 전용 디렉터리는 응용 프로그램을 설치 합니다. (*iOS*, *안 드 로이드*, *블랙베리 10*) + +* `cordova.file.applicationStorageDirectory`응용 프로그램의 샌드박스;의 루트 디렉터리 iOS에이 위치에는 읽기 전용 (특정 하위 디렉토리만 [같은 `/Documents` ]은 읽기 / 쓰기). 포함 된 모든 데이터는 응용 프로그램에 전용. ( *iOS*, *안 드 로이드*, *블랙베리 10*) + +* `cordova.file.dataDirectory`-내부 메모리를 사용 하 여 응용 프로그램의 샌드박스 내에서 영구 및 개인 데이터 스토리지 (안 드 로이드, 외부 메모리를 사용 해야 하는 경우 사용 하 여 `.externalDataDirectory` ). IOS에이 디렉터리 iCloud와 동기화 되지 되 (를 사용 하 여 `.syncedDataDirectory` ). (*iOS*, *안 드 로이드*, *블랙베리 10*) + +* `cordova.file.cacheDirectory`-디렉터리 캐시 데이터 파일 또는 모든 파일을 당신의 app를 다시 쉽게 만들 수 있습니다. 운영 체제 장치 저장소 부족 하면 이러한 파일을 삭제할 수 있습니다, 그리고 그럼에도 불구 하 고, 애플 리 케이 션 여기에 파일을 삭제 하려면 운영 체제에 의존 하지 말아야 합니다. (*iOS*, *안 드 로이드*, *블랙베리 10*) + +* `cordova.file.externalApplicationStorageDirectory`-응용 프로그램 외부 저장 공간입니다. (*안 드 로이드*) + +* `cordova.file.externalDataDirectory`-외부 저장소에 응용 프로그램 특정 데이터 파일을 넣어 어디. (*안 드 로이드*) + +* `cordova.file.externalCacheDirectory`외부 저장소에 응용 프로그램 캐시입니다. (*안 드 로이드*) + +* `cordova.file.externalRootDirectory`-외부 저장 (SD 카드) 루트입니다. (*안 드 로이드*, *블랙베리 10*) + +* `cordova.file.tempDirectory`-운영 체제에서 지울 수 있습니다 임시 디렉터리 것입니다. 이 디렉터리;를 운영 체제에 의존 하지 마십시오 귀하의 응용 프로그램 항상 해당 하는 경우 파일을 제거 해야 합니다. (*iOS*) + +* `cordova.file.syncedDataDirectory`-(ICloud)를 예를 들어 동기화 해야 하는 응용 프로그램 관련 파일을 보유 하 고 있습니다. (*iOS*) + +* `cordova.file.documentsDirectory`-파일 애플 리 케이 션, 하지만 그 개인은 다른 응용 프로그램 (예: Office 파일)에 의미입니다. (*iOS*) + +* `cordova.file.sharedDirectory`-모든 응용 프로그램 (*블랙베리 10* 에 전세계적으로 사용 가능한 파일) + +## 파일 시스템 레이아웃 + +하지만 구현 세부 사항을 기술적으로 `cordova.file.*` 속성 실제 장치에 실제 경로에 매핑하는 방법을 아는 것이 매우 유용할 수 있습니다. + +### iOS 파일 시스템 레이아웃 + +| 장치 경로 | `cordova.file.*` | `iosExtraFileSystems` | r/w? | 영구? | OS 지웁니다 | 동기화 | 개인 | +|:------------------------------------ |:--------------------------- |:--------------------- |:----:|:------:|:---------:|:---:|:--:| +| `/ var/모바일/응용 프로그램/< UUID > /` | applicationStorageDirectory | - | r | N/A | N/A | N/A | 예 | +|    `appname.app/` | applicationDirectory | 번들 | r | N/A | N/A | N/A | 예 | +|       `www/` | - | - | r | N/A | N/A | N/A | 예 | +|    `Documents/` | documentsDirectory | 문서 | r/w | 예 | 없음 | 예 | 예 | +|       `NoCloud/` | - | 문서 nosync | r/w | 예 | 없음 | 없음 | 예 | +|    `Library` | - | 라이브러리 | r/w | 예 | 없음 | 그래? | 예 | +|       `NoCloud/` | dataDirectory | 라이브러리 nosync | r/w | 예 | 없음 | 없음 | 예 | +|       `Cloud/` | syncedDataDirectory | - | r/w | 예 | 없음 | 예 | 예 | +|       `Caches/` | cacheDirectory | 캐시 | r/w | 예 * | 예 * * *| | 없음 | 예 | +|    `tmp/` | tempDirectory | - | r/w | 아니 * * | 예 * * *| | 없음 | 예 | + +* 파일 응용 프로그램 다시 시작 및 업그레이드, 유지 하지만 OS 욕망 언제 든 지이 디렉터리를 지울 수 있습니다. 앱 삭제 될 수 있습니다 모든 콘텐츠를 다시 만들 수 있어야 합니다. + +* * 파일 응용 프로그램 다시 시작에서 지속 될 수 있습니다 하지만이 동작에 의존 하지 마십시오. 파일 여러 업데이트를 보장 하지 않습니다. 때 해당 앱이이 디렉터리에서 파일을 제거 해야, 이러한 파일을 제거할 때 (또는 경우에도) 운영 체제 보증 하지 않습니다으로. + +* * *| OS 그것이 필요를 느낀다 언제 든 지이 디렉터리의 내용을 취소 될 수 있습니다 하지만 이것에 의존 하지 마십시오. 이 디렉터리를 응용 프로그램에 대 한 적절 한 선택을 취소 해야 합니다. + +### 안 드 로이드 파일 시스템 레이아웃 + +| 장치 경로 | `cordova.file.*` | `AndroidExtraFileSystems` | r/w? | 영구? | OS 지웁니다 | 개인 | +|:--------------------------------- |:----------------------------------- |:------------------------- |:----:|:---:|:-------:|:--:| +| `file:///android_asset/` | applicationDirectory | | r | N/A | N/A | 예 | +| `/data/데이터/< app id > /` | applicationStorageDirectory | - | r/w | N/A | N/A | 예 | +|    `cache` | cacheDirectory | 캐시 | r/w | 예 | 예 * | 예 | +|    `files` | dataDirectory | 파일 | r/w | 예 | 없음 | 예 | +|       `Documents` | | 문서 | r/w | 예 | 없음 | 예 | +| `< sdcard > /` | externalRootDirectory | sdcard | r/w | 예 | 없음 | 없음 | +|    `Android/data//` | externalApplicationStorageDirectory | - | r/w | 예 | 없음 | 없음 | +|       `cache` | externalCacheDirectry | 외부 캐시 | r/w | 예 | 아니 * * | 없음 | +|       `files` | externalDataDirectory | 파일 외부 | r/w | 예 | 없음 | 없음 | + +* OS 수 있습니다 정기적으로이 디렉터리에 있지만이 동작에 의존 하지 마십시오. 이 응용 프로그램이 디렉터리의 내용을 취소 합니다. 사용자 수동으로 캐시 제거 해야,이 디렉터리의 내용은 제거 됩니다. + +* * OS 지워지지 않습니다이 디렉터리 자동으로; 콘텐츠를 관리 하기 위한 책임이 있습니다. 사용자 수동으로 캐시 제거 합니다, 디렉터리의 내용은 제거 됩니다. + +**참고**: 외부 저장소를 탑재할 수 없는 경우 `cordova.file.external*` 속성은 `null`. + +### 블랙베리 10 파일 시스템 레이아웃 + +| 장치 경로 | `cordova.file.*` | r/w? | 영구? | OS 지웁니다 | 개인 | +|:--------------------------------------------------- |:--------------------------- |:----:|:---:|:-------:|:--:| +| `file:///accounts/1000/appdata/ < app id > /` | applicationStorageDirectory | r | N/A | N/A | 예 | +|    `app/native` | applicationDirectory | r | N/A | N/A | 예 | +|    `data/webviews/webfs/temporary/local__0` | cacheDirectory | r/w | 없음 | 예 | 예 | +|    `data/webviews/webfs/persistent/local__0` | dataDirectory | r/w | 예 | 없음 | 예 | +| `file:///accounts/1000/removable/sdcard` | externalRemovableDirectory | r/w | 예 | 없음 | 없음 | +| `file:///accounts/1000/shared` | sharedDirectory | r/w | 예 | 없음 | 없음 | + +*참고*: 모든 경로 /accounts/1000-enterprise를 기준으로 응용 프로그램 경계를 작동 하도록 배포 될 때. + +## 안 드 로이드 단점 + +### 안 드 로이드 영구 저장 위치 + +안 드 로이드 장치에 영구 파일을 저장할 여러 유효한 위치가 있다. 다양 한 가능성의 광범위 한 토론에 대 한 [이 페이지][3]를 참조 하십시오. + + [3]: http://developer.android.com/guide/topics/data/data-storage.html + +플러그인의 이전 버전을 시작할 때, 장치는 SD 카드 (또는 해당 스토리지 파티션) 탑재 했다 주장 하는 여부에 따라 임시 및 영구 파일의 위치를 선택 합니다. SD 카드 마운트, 또는 큰 내부 스토리지 파티션에 사용할 수 있었습니다 (같은 넥서스 장치에) 그 후에 영구 파일 공간의 루트에 저장 됩니다. 이 모든 코르 도우 바 애플 리 케이 션 카드에 모두 사용할 수 있는 파일을 볼 수 있는 의미 합니다. + +SD 카드는 사용할 수 있는 경우 이전 버전에서 데이터 저장 `/data/data/`는 서로 다른 애플 리 케이 션을 분리 하지만 여전히 원인 데이터를 사용자 간에 공유할 수 있습니다. + +그것은 지금 내부 파일 저장 위치 또는 응용 프로그램의 `config.xml` 파일에 기본 설정으로 이전 논리를 사용 하 여 파일을 저장할 것인지를 선택할 수 있습니다. 이렇게 하려면 `config.xml`에이 두 줄 중 하나를 추가: + + + + + + +이 줄이 없으면 파일 플러그인은 기본적으로 `Compatibility`을 사용 합니다. 기본 태그,이 이러한 값 중 하나가 아닌 경우에 응용 프로그램이 시작 되지 않습니다. + +이전 (사전 1.0)을 사용 하는 경우 응용 프로그램 사용자에 게 발송 되었다 이전,이 플러그인의 버전 영구 파일 시스템에 저장 된 파일은 그리고 `Compatibility` 환경 설정을 설정 해야 합니다. "내부"의 위치 전환 그들의 응용 프로그램을 업그레이드 기존 사용자의 그들의 장치에 따라 그들의 이전에 저장 된 파일에 액세스할 수 수 있다는 뜻입니다. + +경우 응용 프로그램은 새로운, 또는 이전 영구 파일 시스템에 파일을 저장, `Internal` 설정은 일반적으로 권장 됩니다. + +## iOS 단점 + +* `cordova.file.applicationStorageDirectory`읽기 전용; 루트 디렉터리 내에서 파일을 저장 하려고에 실패 합니다. 다른 중 하나를 사용 하 여 `cordova.file.*` iOS에 대해 정의 된 속성 (만 `applicationDirectory` 와 `applicationStorageDirectory` 는 읽기 전용). +* `FileReader.readAsText(blob, encoding)` + * `encoding`매개 변수는 지원 되지 않습니다, 및 효과에 항상 u t F-8 인코딩을 합니다. + +### iOS 영구 저장소 위치 + +IOS 디바이스에 영구 파일을 저장할 두 개의 유효한 위치가 있다: 문서 디렉터리 및 라이브러리 디렉터리. 플러그인의 이전 버전은 오직 문서 디렉토리에 영구 파일을 저장. 이 부작용 보다는 아니었다 수시로 특히 많은 작은 파일을 처리 하는 응용 프로그램에 대 한 의도, iTunes에 표시 모든 응용 프로그램 파일을 만드는 디렉터리의 용도 내보내기에 대 한 완전 한 문서를 생산 했다. + +그것은 지금 문서 또는 응용 프로그램의 `config.xml` 파일에 기본 설정으로 라이브러리 디렉토리에 파일을 저장할 것인지를 선택할 수 있습니다. 이렇게 하려면 `config.xml`에이 두 줄 중 하나를 추가: + + + + + + +이 줄이 없으면 파일 플러그인은 기본적으로 `Compatibility`을 사용 합니다. 기본 태그,이 이러한 값 중 하나가 아닌 경우에 응용 프로그램이 시작 되지 않습니다. + +이전 (사전 1.0)을 사용 하는 경우 응용 프로그램 사용자에 게 발송 되었다 이전,이 플러그인의 버전 영구 파일 시스템에 저장 된 파일은 그리고 `Compatibility` 환경 설정을 설정 해야 합니다. `Library`에 위치를 스위칭 기존 사용자에 게 응용 프로그램을 업그레이 드의 그들의 이전에 저장 된 파일에 액세스할 수 것을 의미할 것입니다. + +경우 응용 프로그램은 새로운, 또는 이전 영구 파일 시스템에 파일을 저장, `Library` 설정은 일반적으로 권장 됩니다. + +## 파이어 폭스 OS 단점 + +파일 시스템 API Firefox 운영 체제에서 기본적으로 지원 하지 및 indexedDB 위에 심으로 구현 됩니다. + +* 비어 있지 않은 디렉터리를 제거할 때 실패 하지 않습니다. +* 디렉터리에 대 한 메타 데이터를 지원 하지 않습니다. +* 메서드 `copyTo` 및 `moveTo` 디렉터리를 지원 하지 않습니다 + +다음 데이터 경로 지원 됩니다: * `applicationDirectory`-`xhr`를 사용 하 여 로컬 파일을 응용 프로그램 패키지를 가져옵니다. * `dataDirectory`-영구 응용 프로그램 특정 데이터 파일에 대 한. * `cacheDirectory`-응용 프로그램 다시 시작 해야 하는 캐시 된 파일 (애플 리 케이 션은 여기에 파일을 삭제 하려면 운영 체제에 의존 하지 말아야). + +## 브라우저 만지면 + +### 일반적인 단점 및 설명 + +* 각 브라우저는 샌드박스 자체 파일 시스템을 사용합니다. IE와 파이어 폭스 기반으로 IndexedDB를 사용합니다. 모든 브라우저는 경로에서 디렉터리 구분 기호로 슬래시를 사용합니다. +* 디렉터리 항목을 연속적으로 만들 수 있다. 예를 들어 전화 `fs.root.getDirectory ('dir1/dir2 ', {create:true}, successCallback, errorCallback)` d i r 1 존재 하지 않은 경우 실패 합니다. +* 플러그인 응용 프로그램 처음 시작할 영구 저장소를 사용 하 여 사용자 권한을 요청 합니다. +* 플러그인 지원 `cdvfile://localhost` (로컬 리소스)만. 즉, 외부 리소스는 `cdvfile`를 통해 지원 되지 않습니다.. +* 플러그인 ["파일 시스템 API 8.3 명명 제한"을][4] 수행 하지 않습니다.. +* Blob 및 파일 ' `close` 함수는 지원 되지 않습니다. +* `FileSaver` 및 `BlobBuilder`는이 플러그 접속식에 의해 지원 되지 않습니다 그리고 명세서를 필요가 없습니다. +* 플러그인 `requestAllFileSystems`를 지원 하지 않습니다. 이 함수는 또한 사양에 빠진. +* 사용 하는 경우 디렉터리에서 항목 제거 되지 것입니다 `create: true` 기존 디렉터리에 대 한 플래그. +* 생성자를 통해 생성 된 파일은 지원 되지 않습니다. Entry.file 메서드를 대신 사용 해야 합니다. +* 각 브라우저 blob URL 참조에 대 한 그것의 자신의 형태를 사용합니다. +* `readAsDataURL` 기능을 지원 하지만 크롬에서 mediatype 항목 이름 확장명에 따라 달라 집니다, 그리고 mediatype IE에는 항상 빈 (`텍스트 일반` 사양에 따라 동일), 파이어 폭스에서 mediatype은 항상 `응용 프로그램/8 진수 스트림`. 예를 들어, 콘텐츠는 `abcdefg` 다음 파이어 폭스 반환 `데이터: 응용 프로그램 / 8 진수 스트림; base64, YWJjZGVmZw = =`, 즉 반환 `데이터:; base64, YWJjZGVmZw = =`, 반환 크롬 `데이터: < 항목 이름의 확장에 따라 mediatype >; base64, YWJjZGVmZw = =`. +* `toInternalURL` 양식 `file:///persistent/path/to/entry` (파이어 폭스, 인터넷 익스플로러)에서 경로 반환합니다. 크롬 양식 `cdvfile://localhost/persistent/file`에 경로 반환합니다.. + + [4]: http://www.w3.org/TR/2011/WD-file-system-api-20110419/#naming-restrictions + +### 크롬 특수 + +* 크롬 파일 시스템 장치 준비 이벤트 후 즉시 준비 되지 않습니다. 문제를 해결 하려면 `filePluginIsReady` 이벤트를 구독할 수 있습니다. 예를 들어: + + javascript + window.addEventListener('filePluginIsReady', function(){ console.log('File plugin is ready');}, false); + + +`Window.isFilePluginReadyRaised` 함수를 사용 하 여 이벤트가 이미 발생 여부를 확인할 수 있습니다. -window.requestFileSystem 임시 및 영구 파일 시스템 할당량 크롬에 제한 되지 않습니다. -크롬에서 영구 저장소를 증가 하려면 `window.initPersistentFileSystem` 메서드를 호출 해야 합니다. 영구 저장소 할당량은 기본적으로 5 메가바이트입니다. -크롬 필요 `-허용-파일-액세스-에서-파일` `file:///` 프로토콜을 통해 지원 API 인수를 실행 합니다. -플래그를 사용 하면 `파일` 개체 하지 변경할 수 `{create:true}` 때 기존 `항목`. -행사 `cancelable` 속성이로 설정 된 크롬에서. 이 [사양][5] 대조적 이다. -크롬에서 `toURL` 함수 반환 합니다 `파일 시스템:`-응용 프로그램 호스트에 따라 경로 앞에. 예를 들어, `filesystem:file:///persistent/somefile.txt`, `filesystem:http://localhost:8080/persistent/somefile.txt`. -`toURL` 함수 결과 디렉터리 항목의 경우에 후행 슬래시를 포함 하지 않습니다. 크롬 하지만 제대로 붙여 슬래시 url이 포함 된 디렉터리 해결합니다. -`resolveLocalFileSystemURL` 메서드 인바운드 `url`을 `파일 시스템` 접두사가 필요 합니다. 예를 들어, `url` 매개 변수 `resolveLocalFileSystemURL`에 대 한 안 드 로이드에서 양식 `file:///persistent/somefile.txt` 반대로 양식 `filesystem:file:///persistent/somefile.txt`에 있어야 합니다. -사용 되지 않는 `toNativeURL` 함수는 지원 되지 않습니다 및 stub에는 없습니다. -`setMetadata` 함수는 규격에 명시 되지 않은 및 지원 되지 않습니다. -INVALID_MODIFICATION_ERR (코드: 9) 대신 throw 됩니다 SYNTAX_ERR(code: 8) 비 existant 파일 시스템의 요청에. -INVALID_MODIFICATION_ERR (코드: 9) 대신 throw 됩니다 PATH_EXISTS_ERR(code: 12) 독점적으로 파일 또는 디렉터리를 만들 려,는 이미 존재 합니다. -INVALID_MODIFICATION_ERR (코드: 9) 대신 throw 됩니다 NO_MODIFICATION_ALLOWED_ERR(code: 6) 루트 파일 시스템에 removeRecursively을 호출 하려고 합니다. -INVALID_MODIFICATION_ERR (코드: 9) 대신 throw 됩니다 NOT_FOUND_ERR(code: 1) moveTo 디렉터리 존재 하지 않는 것을 시도에. + + [5]: http://dev.w3.org/2009/dap/file-system/file-writer.html + +### IndexedDB 기반 구현이 특수 (파이어 폭스와 IE) + +* `.` `.`는 지원 되지 않습니다. +* IE `file:///`를 지원 하지 않습니다-모드; 호스트 모드 지원된 (http://localhost:xxxx)입니다. +* 파이어 폭스 파일 시스템 크기 제한 이지만 각 50MB 확장 사용자 권한을 요청 합니다. IE10 최대 10 mb 결합 AppCache 및 IndexedDB 묻는 사이트 당 250 mb의 최대 최대 증가 될 수 있도록 하려는 경우 해당 수준에 충돌 한 번 메시지를 표시 하지 않고 파일 시스템의 구현에 사용을 허용 한다. 그래서 `size` 매개 변수 `requestFileSystem` 함수에 대 한 파이어 폭스와 IE에서 파일 시스템 영향을 주지 않습니다. +* `readAsBinaryString` 함수 사양에 명시 되지 않은 IE에서 지원 되지 않으며 stub에는 없습니다. +* `file.type`은 항상 null입니다. +* 하지 항목 삭제 된 DirectoryEntry 인스턴스의 콜백 결과 사용 하 여 만들어야 합니다. 그렇지 않으면, '교수형 항목'을 얻을 것 이다. +* 그냥 작성 된 파일을 읽을 수 있는이 파일의 새 인스턴스를 얻으려면 해야 합니다. +* `setMetadata` 함수는 사양에 명시 되지 않은 지원 `modificationTime` 필드 변경에만 해당 합니다. +* `copyTo` 및 `moveTo` 함수는 디렉터리를 지원 하지 않습니다. +* 디렉터리 메타 데이터는 지원 되지 않습니다. +* 둘 다 Entry.remove와 directoryEntry.removeRecursively 비어 있지 않은 디렉터리를 제거할 때 실패 하지 않습니다-디렉터리 제거 되는 대신 내용을 함께 청소. +* `abort` 및 `truncate` 함수 지원 되지 않습니다. +* 진행 이벤트가 발생 하지 합니다. 예를 들어,이 처리기 하지 실행 됩니다. + + javascript + writer.onprogress = function() { /*commands*/ }; + + +## 업그레이드 노트 + +이 플러그인의 v1.0.0에 게시 된 사양에 맞춰 더 많은 것 `FileEntry` 및 `DirectoryEntry` 구조 변경 되었습니다. + +플러그인의 이전 (pre-1.0.0) 버전 장치 절대 파일 위치 `Entry` 개체의 `fullPath` 속성에 저장 됩니다. 이러한 경로 일반적으로 같습니다. + + /var/mobile/Applications//Documents/path/to/file (iOS) + /storage/emulated/0/path/to/file (Android) + + +이러한 경로 `항목` 개체의 `toURL()` 메서드에서 반환 했다. + +V1.0.0, `fullPath` 속성은 *HTML 파일 시스템의 루트에 상대적인* 파일의 경로를. 그래서, 위의 경로 지금 둘 다의 `fullPath`와 `FileEntry` 개체에 의해 표현 될 것 이다 + + /path/to/file + + +응용 프로그램 작동 장치 절대 경로, 이전 `항목` 개체의 `fullPath` 속성을 통해 그 경로 검색 하는 경우에, 당신은 대신 `entry.toURL()`를 사용 하 여 코드를 업데이트 해야 합니다. + +대 한 뒤 호환성, `resolveLocalFileSystemURL()` 메서드는 장치-절대-경로 수락 하 고 그 파일 중 `TEMPORARY` 또는 `PERSISTENT` 파일 시스템 내에서 존재 하는 경우, 해당 `Entry` 개체를 반환 합니다. + +이 특히 이전 장치 절대 경로 사용 하는 파일 전송 플러그인에 문제가 있다 (그리고 아직도 그들을 받아들일 수.) 그것은 `entry.toURL()`와 `entry.fullPath`를 대체 확인 장치에 파일을 사용 하는 플러그인을 지 고 그래서 파일 시스템 Url와 함께 제대로 작동 하려면 업데이트 되었습니다. + +V1.1.0에 `toURL()`의 반환 값 (\[CB-6394\] (https://issues.apache.org/jira/browse/CB-6394) 참조)로 바뀌었다 'file://' 절대 URL을 반환. 가능 하다 면. 보장 하는 ' cdvfile:'-URL `toInternalURL()`를 지금 사용할 수 있습니다. 이 메서드 이제 양식의 파일 Url을 반환 합니다. + + cdvfile://localhost/persistent/path/to/file + + +어떤 파일을 고유 하 게 식별 하려면 사용할 수 있습니다. + +## 오류 코드 및 의미의 목록 + +오류가 throw 됩니다 때 다음 코드 중 하나가 사용 됩니다. + +| 코드 | 상수 | +| --:|:----------------------------- | +| 1 | `NOT_FOUND_ERR` | +| 2 | `SECURITY_ERR` | +| 3 | `ABORT_ERR` | +| 4 | `NOT_READABLE_ERR` | +| 5 | `ENCODING_ERR` | +| 6 | `NO_MODIFICATION_ALLOWED_ERR` | +| 7 | `INVALID_STATE_ERR` | +| 8 | `SYNTAX_ERR` | +| 9 | `INVALID_MODIFICATION_ERR` | +| 10 | `QUOTA_EXCEEDED_ERR` | +| 11 | `TYPE_MISMATCH_ERR` | +| 12 | `PATH_EXISTS_ERR` | + +## (선택 사항) 플러그인 구성 + +사용 가능한 파일 시스템의 집합 플랫폼 당 구성된 될 수 있습니다. IOS와 안 드 로이드를 인식 한 `config.xml` 설치 될 파일 시스템 이름에 태그. 기본적으로 모든 파일 시스템 루트 사용할 수 있습니다. + + + + + +### 안 드 로이드 + +* `files`: 응용 프로그램의 내부 파일 저장 디렉토리 +* `files-external`: 응용 프로그램의 외부 파일 저장 디렉토리 +* `sdcard`: 글로벌 외부 파일 저장 디렉토리 (이것은 SD 카드의 루트 설치 된 경우). 이것을 사용 하려면 `android.permission.WRITE_EXTERNAL_STORAGE` 권한이 있어야 합니다. +* `cache`: 응용 프로그램의 내부 캐시 디렉터리 +* `cache-external`: 응용 프로그램의 외부 캐시 디렉터리 +* `root`: 전체 장치 파일 시스템 + +안 드 로이드는 또한 "파일" 파일 시스템 내에서 "/ 문서 /" 하위 디렉토리를 나타내는 "문서" 라는 특별 한 파일을 지원 합니다. + +### iOS + +* `library`: 응용 프로그램의 라이브러리 디렉터리 +* `documents`: 응용 프로그램의 문서 디렉토리 +* `cache`: 응용 프로그램의 캐시 디렉터리 +* `bundle`: 응용 프로그램의 번들; (읽기 전용) 디스크에 응용 프로그램 자체의 위치 +* `root`: 전체 장치 파일 시스템 + +기본적으로 라이브러리 및 문서 디렉토리 iCloud에 동기화 할 수 있습니다. 또한 2 개의 추가적인 파일 시스템, `library-nosync` 및 `documents-nosync`, 내 특별 한 동기화 되지 않은 디렉터리를 대표 하는 요청할 수 있습니다는 `/Library` 또는 `/Documents` 파일 시스템. diff --git a/plugins/cordova-plugin-file/doc/ko/plugins.md b/plugins/cordova-plugin-file/doc/ko/plugins.md new file mode 100644 index 0000000..31b274d --- /dev/null +++ b/plugins/cordova-plugin-file/doc/ko/plugins.md @@ -0,0 +1,101 @@ + + +# 플러그인 개발자를 위한 노트 + +이 노트는 주로 파일 플러그인을 사용 하 여 파일 시스템 플러그인 인터페이스를 작성 하 고 싶은 안 드 로이드와 iOS 개발자를 위한 것입니다. + +## 코르 도우 바 파일 시스템 Url 사용 + +버전 1.0.0, 이후이 플러그인과 Url 사용 하고있다는 `cdvfile` 교량, 모든 통신에 대 한 제도 보다는 자바 원시 장치 파일 시스템 경로 노출. + +자바 스크립트 측면에서 즉 그 FileEntry 및 DirectoryEntry 개체 fullPath 속성을 HTML 파일 시스템의 루트에 상대적입니다. FileEntry 또는 DirectoryEntry 개체를 수락 하는 플러그인의 자바 API를 호출 해야 `.toURL()` 다리에 걸쳐 네이티브 코드에 전달 하기 전에 해당 개체에. + +### Cdvfile 변환: / / fileystem 경로 Url + +플러그인 파일 시스템을 작성 하는 실제 파일 시스템 위치에 받은 파일 시스템 URL을 변환 할 수 있습니다. 이렇게, 네이티브 플랫폼에 따라 여러 방법이 있다. + +기억 하는 것이 중요 하다 모든 `cdvfile://` Url은 실제 파일 장치에 매핑. 일부 Url 파일에 의해 표현 되지 않는 또는 심지어 원격 리소스를 참조할 수 있는 장치에 자산을 참조할 수 있습니다. 이러한 가능성 때문에 플러그인 경로를 Url을 변환 하려고 할 때 다시 의미 있는 결과 얻을 지 여부를 항상 테스트 해야 합니다. + +#### 안 드 로이드 + +안 드 로이드, 변환 하는 간단한 방법에는 `cdvfile://` URL을 파일 시스템 경로 사용 하는 `org.apache.cordova.CordovaResourceApi` . `CordovaResourceApi`처리할 수 있는 여러 가지 방법에는 `cdvfile://` Url: + + webView 플러그인 클래스 CordovaResourceApi resourceApi의 멤버인 = webView.getResourceApi(); + + 장치에이 파일을 나타내는 file:/// URL 얻기 / / 같은 URL 변경 파일 Uri fileURL에 매핑할 수 없는 경우 또는 = resourceApi.remapUri(Uri.parse(cdvfileURL)); + + +그것은 또한 파일 플러그인을 직접 사용할 수 있습니다: + + 가져오기 org.apache.cordova.file.FileUtils; + 가져오기 org.apache.cordova.file.FileSystem; + 가져오기 java.net.MalformedURLException; + + 플러그인 관리자에서 파일 플러그인을 얻을 FileUtils filePlugin = (FileUtils)webView.pluginManager.getPlugin("File"); + + 그것 시도 대 한 경로 얻을 URL을 감안할 때, {문자열 경로 = filePlugin.filesystemPathForURL(cdvfileURL);} catch (MalformedURLException e) {/ / 파일 시스템 url 인식 되지 않았습니다} + + +경로를 변환 하는 `cdvfile://` URL: + + 가져오기 org.apache.cordova.file.LocalFilesystemURL; + + 장치 경로 대 한 LocalFilesystemURL 개체를 가져오기 / / cdvfile URL로 나타낼 수 없는 경우 null. + LocalFilesystemURL url = filePlugin.filesystemURLforLocalPath(path); + URL 개체 문자열 cdvfileURL의 문자열 표현을 = url.toString(); + + +플러그인 파일을 만들고 그것에 대 한 FileEntry 개체를 반환 하려면, 파일 플러그인을 사용. + + JSON 구조를 JavaScript에 반환을 위한 적당 한 반환 / /이 파일은 cdvfile URL로 표현 하는 경우 null. + JSONObject 항목 = filePlugin.getEntryForFile(file); + + +#### iOS + +IOS에서 코르도바 같은 사용 하지 않는 `CordovaResourceApi` 안 드 로이드 개념. Ios, Url 및 파일 시스템 경로 사이 변환 파일 플러그인을 사용 해야 합니다. + + URL 문자열 CDVFilesystemURL * url에서 CDVFilesystem URL 개체를 가져오기 = [CDVFilesystemURL fileSystemURLWithString:cdvfileURL]; + 파일 NSString * 경로에 매핑할 수 없는 경우 URL 개체 또는 없음에 대 한 경로 얻을 = [filePlugin filesystemPathForURL:url]; + + + 장치 경로 대 한 CDVFilesystem URL 개체를 가져오기 또는 / / 없음 cdvfile URL로 나타낼 수 없는 경우. + CDVFilesystemURL * url = [filePlugin fileSystemURLforLocalPath:path]; + URL 개체 NSString * cdvfileURL의 문자열 표현을 = [url absoluteString]; + + +플러그인 파일을 만들고 그것에 대 한 FileEntry 개체를 반환 하려면, 파일 플러그인을 사용. + + 장치 경로 대 한 CDVFilesystem URL 개체를 가져오기 또는 / / 없음 cdvfile URL로 나타낼 수 없는 경우. + CDVFilesystemURL * url = [filePlugin fileSystemURLforLocalPath:path]; + 자바 스크립트 NSDictionary * 항목으로 돌아가려면 구조를 얻을 = [filePlugin makeEntryForLocalURL:url] + + +#### 자바 스크립트 + +자바 스크립트에는 `cdvfile://` FileEntry 또는 DirectoryEntry 개체에서 URL 호출 `.toURL()` 그것에: + + var cdvfileURL = entry.toURL(); + + +플러그인 응답 처리기에서 실제 항목 개체로 반환 된 FileEntry 구조에서 변환 처리기 코드 해야 파일 플러그인 가져오고 새 개체를 만들: + + 적절 한 항목 개체 var 항목; + 경우 (entryStruct.isDirectory) {항목 = 새 DirectoryEntry (entryStruct.name, entryStruct.fullPath, 새로운 FileSystem(entryStruct.filesystemName));} 다른 {항목 = 새로운 FileEntry (entryStruct.name, entryStruct.fullPath, 새로운 FileSystem(entryStruct.filesystemName));} \ No newline at end of file diff --git a/plugins/cordova-plugin-file/doc/pl/README.md b/plugins/cordova-plugin-file/doc/pl/README.md new file mode 100644 index 0000000..166c3ce --- /dev/null +++ b/plugins/cordova-plugin-file/doc/pl/README.md @@ -0,0 +1,335 @@ + + +# cordova-plugin-file + +[![Build Status](https://travis-ci.org/apache/cordova-plugin-file.svg)](https://travis-ci.org/apache/cordova-plugin-file) + +Ten plugin implementuje API pliku, dzięki czemu dostęp do odczytu i zapisu do plików znajdujących się na urządzeniu. + +Ten plugin jest oparty na kilka specyfikacje, w tym: HTML5 File API + +Katalogi (nieistniejącego już) i System Najnowsze rozszerzenia: , chociaż większość z ten plugin kod został napisany podczas wcześniejszych specyfikacji były aktualne: + +To również implementuje specyfikację FileWriter: + +Wykorzystania, prosimy odnieść się do skały HTML5 doskonałe [plików art.](http://www.html5rocks.com/en/tutorials/file/filesystem/) + +Omówienie innych opcji przechowywania odnoszą się do Cordova z [magazynu przewodnik](http://cordova.apache.org/docs/en/edge/cordova_storage_storage.md.html). + +Ten plugin określa globalne `cordova.file` obiektu. + +Chociaż w globalnym zasięgu, to nie dostępne dopiero po `deviceready` imprezie. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(cordova.file); + } + + +## Instalacja + + cordova plugin add cordova-plugin-file + + +## Obsługiwane platformy + + * Amazon Fire OS + * Android + * BlackBerry 10 + * Firefox OS + * iOS + * Windows Phone 7 i 8 * + * Windows 8 * + * Windows* + * Przeglądarka + +\* *These platforms do not support `FileReader.readAsArrayBuffer` nor `FileWriter.write(blob)`.* + +## Gdzie przechowywać pliki + +Od v1.2.0 znajdują się adresy URL do katalogów ważne systemu plików. Każdy adres URL jest w formie *file:///path/to/spot/* i mogą być konwertowane na `DirectoryEntry` za pomocą `window.resolveLocalFileSystemURL()`. + + * `cordova.file.applicationDirectory`-Tylko do odczytu katalogu gdzie jest zainstalowana aplikacja. (*iOS*, *Android*, *BlackBerry 10*) + + * `cordova.file.applicationStorageDirectory`-Katalogu obszaru izolowanego aplikacji; na iOS to miejsce jest tylko do odczytu (ale podkatalogów określonego [jak `/Documents` ] są odczytu i zapisu). Wszystkie dane zawarte w jest prywatną do aplikacji. ( *iOS*, *Android*, *BlackBerry 10*) + + * `cordova.file.dataDirectory`-Trwałe i prywatne dane magazynowanie w izolowanym aplikacji przy użyciu pamięci wewnętrznej (na Android, jeśli trzeba użyć zewnętrznej pamięci, należy użyć `.externalDataDirectory` ). Na iOS, Katalog ten nie jest zsynchronizowane z iCloud (za pomocą `.syncedDataDirectory` ). (*iOS*, *Android*, *BlackBerry 10*) + + * `cordova.file.cacheDirectory`-Katalog dla plików buforowanych danych lub pliki, które aplikacji ponownie można łatwo tworzyć. System operacyjny może usunąć te pliki, gdy urządzenie działa niski na przechowywanie, niemniej jednak aplikacje nie powinny polegać na OS, aby usunąć pliki tutaj. (*iOS*, *Android*, *BlackBerry 10*) + + * `cordova.file.externalApplicationStorageDirectory`-Stosowania przestrzeni na zewnętrznej pamięci masowej. (*Android*) + + * `cordova.file.externalDataDirectory`-Gdzie umieścić pliki danych specyficznych dla aplikacji na zewnętrznej pamięci masowej. (*Android*) + + * `cordova.file.externalCacheDirectory`-Pamięci podręcznej aplikacji na zewnętrznej pamięci masowej. (*Android*) + + * `cordova.file.externalRootDirectory`-Korzeń zewnętrznej pamięci masowej (karty SD). (*Android*, *BlackBerry 10*) + + * `cordova.file.tempDirectory`-Temp katalogu systemu operacyjnego można wyczyścić w będzie. Nie należy polegać na OS wobec usunąć ten katalog; aplikacji należy zawsze usunąć pliki jako obowiązujące. (*iOS*) + + * `cordova.file.syncedDataDirectory`-Posiada pliki specyficzne dla aplikacji, które powinny być zsynchronizowane (np. do iCloud). (*iOS*) + + * `cordova.file.documentsDirectory`-Pliki prywatne do aplikacji, ale że mają znaczenie dla innych aplikacji (np. plików pakietu Office). (*iOS*) + + * `cordova.file.sharedDirectory`-Pliki dostępne na całym świecie do wszystkich aplikacji (*BlackBerry 10*) + +## Plik System układy + +Chociaż technicznie implementacyjnym, może być bardzo przydatne wiedzieć, jak `cordova.file.*` właściwości mapy fizycznej ścieżki na prawdziwe urządzenie. + +### iOS układ systemu plików + +| Ścieżka urządzenia | `Cordova.File.*` | `iosExtraFileSystems` | r/w? | trwałe? | Czyści OS | Synchronizacja | prywatne | +|:---------------------------------------------- |:--------------------------- |:--------------------- |:----:|:--------:|:-------------:|:--------------:|:--------:| +| `/ var/mobile/Applications/< UUID > /` | applicationStorageDirectory | - | r | N/D! | N/D! | N/D! | Tak | +|    `appname.app/` | applicationDirectory | pakiet | r | N/D! | N/D! | N/D! | Tak | +|       `www/` | - | - | r | N/D! | N/D! | N/D! | Tak | +|    `Documents/` | documentsDirectory | dokumenty | r/w | Tak | Nr | Tak | Tak | +|       `NoCloud/` | - | dokumenty nosync | r/w | Tak | Nr | Nr | Tak | +|    `Library` | - | Biblioteka | r/w | Tak | Nr | Tak? | Tak | +|       `NoCloud/` | dataDirectory | Biblioteka nosync | r/w | Tak | Nr | Nr | Tak | +|       `Cloud/` | syncedDataDirectory | - | r/w | Tak | Nr | Tak | Tak | +|       `Caches/` | cacheDirectory | pamięci podręcznej | r/w | Tak * | Yes**\* | Nr | Tak | +|    `tmp/` | tempDirectory | - | r/w | No** | Yes**\* | Nr | Tak | + +\ * Pliki utrzymywały aplikacja zostanie ponownie uruchomiony i uaktualnienia, ale w tym katalogu mogą być rozliczone przy każdym OS pragnień. Aplikacji należy umożliwić odtworzenie treści, które mogą być usunięte. + +** Plików może utrzymywać się po ponownym uruchomieniu aplikacji, ale nie opierają się na tym zachowaniu. Pliki nie są gwarantowane w aktualizacji. Aplikacji należy usunąć pliki z tego katalogu, gdy ma to zastosowanie, ponieważ system operacyjny nie gwarantuje Kiedy (lub nawet jeśli) te pliki zostaną usunięte. + +**\ * System operacyjny może wyczyścić zawartość tego katalogu, gdy czuje, że jest to konieczne, ale nie powoływać się na to. Należy wyczyścić ten katalog jako odpowiednie dla aplikacji. + +### Układ systemu Android plików + +| Ścieżka urządzenia | `Cordova.File.*` | `AndroidExtraFileSystems` | r/w? | trwałe? | Czyści OS | prywatne | +|:------------------------------------------------ |:----------------------------------- |:------------------------------- |:----:|:-------:|:---------:|:--------:| +| `file:///android_asset/` | applicationDirectory | | r | N/D! | N/D! | Tak | +| `/Data/danych/< Aplikacja id > /` | applicationStorageDirectory | - | r/w | N/D! | N/D! | Tak | +|    `cache` | cacheDirectory | pamięci podręcznej | r/w | Tak | Yes\ * | Tak | +|    `files` | dataDirectory | pliki | r/w | Tak | Nr | Tak | +|       `Documents` | | dokumenty | r/w | Tak | Nr | Tak | +| `< sdcard > /` | externalRootDirectory | sdcard | r/w | Tak | Nr | Nr | +|    `Android/data//` | externalApplicationStorageDirectory | - | r/w | Tak | Nr | Nr | +|       `cache` | externalCacheDirectry | zewnętrznych pamięci podręcznej | r/w | Tak | No** | Nr | +|       `files` | externalDataDirectory | zewnętrznych plików | r/w | Tak | Nr | Nr | + +\ * OS może okresowo usunąć ten katalog, ale nie opierają się na tym zachowaniu. Wyczyść zawartość tego katalogu jako odpowiednie dla danej aplikacji. Należy użytkownik przeczyścić pamięć podręczną ręcznie, zawartość w tym katalogu są usuwane. + +** OS nie usunąć ten katalog automatycznie; Jesteś odpowiedzialny za zarządzanie zawartość siebie. Należy użytkownik przeczyścić pamięć podręczną ręcznie, zawartość katalogu są usuwane. + +**Uwaga**: Jeśli nie mogą być montowane pamięci masowej, właściwości `cordova.file.external*` są `wartości null`. + +### Układ systemu plików blackBerry 10 + +| Ścieżka urządzenia | `Cordova.File.*` | r/w? | trwałe? | Czyści OS | prywatne | +|:----------------------------------------------------------- |:--------------------------- |:----:|:-------:|:---------:|:--------:| +| `file:///accounts/1000/AppData/ < id aplikacji > /` | applicationStorageDirectory | r | N/D! | N/D! | Tak | +|    `app/native` | applicationDirectory | r | N/D! | N/D! | Tak | +|    `data/webviews/webfs/temporary/local__0` | cacheDirectory | r/w | Nr | Tak | Tak | +|    `data/webviews/webfs/persistent/local__0` | dataDirectory | r/w | Tak | Nr | Tak | +| `file:///accounts/1000/Removable/sdcard` | externalRemovableDirectory | r/w | Tak | Nr | Nr | +| `file:///accounts/1000/Shared` | sharedDirectory | r/w | Tak | Nr | Nr | + +*Uwaga*: gdy aplikacja jest rozmieszczana do pracy obwodu, wszystkie ścieżki są względne do /accounts/1000-enterprise. + +## Dziwactwa Androida + +### Lokalizacja przechowywania trwałych Android + +Istnieje wiele prawidłowe lokalizacje do przechowywania trwałych plików na telefonie z systemem Android. Zobacz [tę stronę](http://developer.android.com/guide/topics/data/data-storage.html) do szerokiej dyskusji o różnych możliwościach. + +Poprzednie wersje pluginu wybrać lokalizację plików tymczasowych i trwałe podczas uruchamiania, czy urządzenie twierdził, że karta SD (lub równoważne magazynowanie podzia³) był montowany w oparciu. Czy karta SD została zamontowana, czy duży wewnętrzny magazynowanie podzia³ był dostępny (takie jak na Nexus urządzenia,) a następnie trwałe pliki będą przechowywane w katalogu głównego tego miejsca. Oznaczało to, że wszystkie aplikacje Cordova może Zobacz wszystkie pliki dostępne na karcie. + +Jeśli karta SD nie był dostępny, a następnie poprzednie wersje będzie przechowywać dane w `/data/data/`, która izoluje aplikacje od siebie, ale nadal może spowodować danych, które mają być współużytkowane przez użytkowników. + +Teraz jest możliwe, aby zdecydować, czy do przechowywania plików w lokalizacji magazynu plików, lub przy użyciu poprzednich logiki, z preferencją w aplikacji w pliku `config.xml`. Aby to zrobić, Dodaj jedną z tych dwóch linii do `pliku config.xml`: + + + + + + +Bez tej linii wtyczki pliku będzie używać `Compatibility` jako domyślny. Jeśli znacznik preferencji jest obecny i to nie jedną z tych wartości, aplikacja nie zostanie uruchomiona. + +Jeśli aplikacja wcześniej zostało wysłane do użytkowników, przy użyciu starszych (pre-1.0) wersję tego pluginu i ma zapisane na dysku pliki w trwałych plików, a następnie należy ustawić preferencje do `Compatibility`. Przełączania lokalizacji do "Internal" oznacza, że istniejących użytkowników, którzy ich aplikacja może być niesłabnący wobec dostęp ich wcześniej zapisane pliki, w zależności od ich urządzenie. + +Jeśli aplikacja jest nowy, lub ma nigdy wcześniej przechowywane pliki w systemie plików trwałe, ustawienie `Internal` generalnie jest zalecane. + +### Powolny cyklicznych operacji dla /android_asset + +Lista katalogów aktywów jest bardzo powolny na Android. Można przyspieszyć to się jednak przez dodanie `src/android/build-extras.gradle` do katalogu głównego projektu android (również wymaga cordova-android@4.0.0 lub większej). + +## Dziwactwa iOS + + * `cordova.file.applicationStorageDirectory`jest tylko do odczytu; próby przechowywania plików w katalogu głównym zakończy się niepowodzeniem. Użyj jednego z innych `cordova.file.*` właściwości zdefiniowane dla iOS (tylko `applicationDirectory` i `applicationStorageDirectory` są tylko do odczytu). + * `FileReader.readAsText(blob, encoding)` + * `encoding`Parametr nie jest obsługiwana, i kodowanie UTF-8 jest zawsze w efekcie. + +### iOS lokalizacja przechowywania trwałych + +Istnieją dwa ważne miejsca trwałe pliki na urządzenia iOS: katalogu dokumentów i katalogu biblioteki. Poprzednie wersje pluginu tylko kiedykolwiek przechowywane trwałe pliki w katalogu dokumentów. To miał ten efekt uboczny od rozpoznawalności wszystkie pliki aplikacji w iTunes, który był często niezamierzone, zwłaszcza dla aplikacji, które obsługują wiele małych plików, zamiast produkuje kompletne dokumenty do wywozu, który jest przeznaczenie katalogu. + +Teraz jest możliwe, aby zdecydować, czy do przechowywania plików w dokumentach lub katalogu biblioteki, z preferencją w pliku `config.xml` aplikacji. Aby to zrobić, Dodaj jedną z tych dwóch linii do `pliku config.xml`: + + + + + + +Bez tej linii wtyczki pliku będzie używać `Compatibility` jako domyślny. Jeśli znacznik preferencji jest obecny i to nie jedną z tych wartości, aplikacja nie zostanie uruchomiona. + +Jeśli aplikacja wcześniej zostało wysłane do użytkowników, przy użyciu starszych (pre-1.0) wersję tego pluginu i ma zapisane na dysku pliki w trwałych plików, a następnie należy ustawić preferencje do `Compatibility`. Przełączania lokalizacji do `Library` oznaczałoby, że istniejących użytkowników, którzy ich aplikacja będzie niesłabnący wobec dostęp ich wcześniej zapisane pliki. + +Jeśli aplikacja jest nowy, lub nigdy wcześniej przechowywane pliki w trwałych plików, ustawień `Library` ogólnie jest zalecane. + +## Firefox OS dziwactwa + +API systemu plików nie jest obsługiwany macierzyście przez Firefox OS i jest zaimplementowany jako podkładki na indexedDB. + + * Nie usuwając niepuste katalogi + * Nie obsługuje metadane dla katalogów + * Metody `copyTo` i `moveTo` nie obsługuje katalogi + +Obsługiwane są następujące ścieżki danych: * `applicationDirectory` - używa `xhr`, aby uzyskać lokalne pliki, które są pakowane z aplikacji. * `dataDirectory` - na trwałe dane specyficzne dla aplikacji pliki. * `cacheDirectory` - buforowanych plików, które powinny przetrwać ponowne uruchomienie aplikacji (aplikacje nie powinny polegać na OS, aby usunąć pliki tutaj). + +## Quirks przeglądarki + +### Wspólne dziwactw i uwagi + + * Każda przeglądarka używa własnej piaskownicy plików. IE i Firefox Użyj IndexedDB jako podstawa. Wszystkie przeglądarki za pomocą ukośnika jako separatora katalogu ścieżka. + * Wpisy w katalogu mają być tworzone sukcesywnie. Na przykład wywołanie `fs.root.getDirectory (' dir1/dir2 ', {create:true}, successCallback, errorCallback)` zakończy się niepowodzeniem, jeśli nie istnieje dir1. + * Plugin żądania użytkownika uprawnień do używania trwałe przechowywanie przy pierwszym uruchomieniu aplikacji. + * Wtyczka obsługuje `cdvfile://localhost` (lokalne zasoby) tylko. Czyli zewnętrznych zasobów nie są obsługiwane przez `cdvfile`. + * Plugin nie następować po ["Plik API systemu nazw 8.3 ograniczenia"](http://www.w3.org/TR/2011/WD-file-system-api-20110419/#naming-restrictions). + * Obiektu BLOB i pliku "`close` funkcja nie jest obsługiwana. + * `FileSaver` i `BlobBuilder` nie są obsługiwane przez ten plugin i nie ma artykułów. + * Plugin nie obsługuje `requestAllFileSystems`. Ta funkcja jest również brak w specyfikacji. + * Wpisy w katalogu nie zostaną usunięte, jeśli używasz `create: true` flaga dla istniejącego katalogu. + * Pliki utworzone za pomocą konstruktora nie są obsługiwane. Zamiast tego należy użyć metody entry.file. + * Każda przeglądarka używa własnej postaci URL odwołania blob. + * `readAsDataURL` funkcja jest obsługiwana, ale mediatype w Chrome zależy od wejścia z rozszerzeniem, mediatype w IE zawsze jest pusty (który jest taki sam jak `zwykły tekst` według specyfikacji), mediatype w Firefox jest zawsze `aplikacji/oktet strumień`. Na przykład, jeśli treść jest `abcdefg` Firefox wraca z `danych: stosowanie / octet-stream, base64, YWJjZGVmZw ==`, czyli zwraca `danych:; base64, YWJjZGVmZw ==`, Chrome zwraca `danych: < mediatype w zależności od rozszerzenia nazwy; > base64, YWJjZGVmZw ==`. + * `toInternalURL` zwraca ścieżkę w postaci `file:///persistent/path/to/entry` (Firefox, IE). Chrom zwraca ścieżkę w postaci `cdvfile://localhost/persistent/file`. + +### Dziwactwa chrom + + * Chrom plików nie jest od razu gotowy po gotowe urządzenia. Jako rozwiązanie alternatywne można subskrybować zdarzenia `filePluginIsReady`. Przykład: + +```javascript +window.addEventListener('filePluginIsReady', function(){ console.log('File plugin is ready');}, false); +``` + +Funkcja `window.isFilePluginReadyRaised` służy do sprawdzenia, czy zdarzenie już została podniesiona. -kwoty plików tymczasowych i trwałe window.requestFileSystem nie są ograniczone w Chrome. -W celu zwiększenia trwałego magazynu w Chrome, należy wywołać metodę `window.initPersistentFileSystem`. Domyślnie trwałe dyskowa jest 5 MB. -Chrome wymaga `--pozwalają--dostęp z plików` uruchomić argument na poparcie API za pośrednictwem protokołu `file:///`. -`Plik` obiekt będzie nie zmieniło jeśli flaga `{create:true}` gdy już istniejący `wpis`. -wydarzenia `zwrotu` właściwość jest zestaw true w Chrome. Jest to sprzeczne ze [specyfikacji](http://dev.w3.org/2009/dap/file-system/file-writer.html). -Funkcja `toURL` w Chrome zwraca `plików:`-poprzedzona ścieżką w zależności od aplikacji hosta. Na przykład, `filesystem:file:///persistent/somefile.txt`, `filesystem:http://localhost:8080/persistent/somefile.txt`. -wynik funkcji `toURL` nie zawierają ukośnika w wpis w katalogu. Chrom usuwa katalogi z ciąć doczepiane adresów URL poprawnie choć. -Metoda `resolveLocalFileSystemURL` wymaga przychodzących `url` mają prefiks `plików`. Na przykład parametr `adresu url` do `resolveLocalFileSystemURL` powinny być w formie `filesystem:file:///persistent/somefile.txt`, w przeciwieństwie do formularza `file:///persistent/somefile.txt` w Android. -Przestarzałe `toNativeURL` funkcja nie jest obsługiwana i nie tylko. -Funkcja `setMetadata` jest nie podane w specyfikacji i nie jest obsługiwane. -INVALID_MODIFICATION_ERR (kod: 9) jest generowany zamiast SYNTAX_ERR(code: 8) na żądanie nieistniejącą plików. -INVALID_MODIFICATION_ERR (kod: 9) jest generowany zamiast PATH_EXISTS_ERR(code: 12) próbuje stworzyć wyłącznie pliku lub katalogu, który już istnieje. -INVALID_MODIFICATION_ERR (kod: 9) jest generowany zamiast NO_MODIFICATION_ALLOWED_ERR(code: 6) na próby wywołania removeRecursively w głównym systemie plików. -INVALID_MODIFICATION_ERR (kod: 9) jest generowany zamiast NOT_FOUND_ERR(code: 1) na trudny do katalogu moveTo, który nie istnieje. + +### Na bazie IndexedDB impl dziwactw (Firefox i IE) + + * `.` i `.` nie są obsługiwane. + * IE obsługuje `file:///`-tryb; tylko obsługiwane tryb jest obsługiwany (http://localhost:xxxx). + * Rozmiar plików Firefox nie jest ograniczona, ale każde rozszerzenie 50MB zwróci użytkownikowi uprawnienia. IE10 pozwala maksymalnie 10mb połączone "appcache" i IndexedDB używane w implementacji systemu plików bez monitowania, gdy trafisz na tym poziomie, które uzyskasz, jeśli chcesz mogła ona zostać zwiększony do max 250mb na stronie. Więc `rozmiar` parametru funkcja `requestFileSystem` nie wpływa na system plików Firefox i IE. + * `readAsBinaryString` funkcja nie jest określona w specyfikacji i nie obsługiwane w IE i nie tylko. + * `File.Type` ma zawsze wartość null. + * Nie należy utworzyć wpis za pomocą DirectoryEntry wystąpienie wynik wywołania zwrotnego, który został usunięty. W przeciwnym razie dostaniesz wpisem"wiszące". + * Zanim będzie można przeczytać plik, który został napisany tylko trzeba uzyskać nowe wystąpienie tego pliku. + * Funkcja `setMetadata`, która nie jest określona w specyfikacji obsługuje tylko zmian pola `modificationTime`. + * `copyTo` i `moveTo` funkcji nie obsługuje katalogi. + * Metadanych w katalogów nie jest obsługiwana. + * Zarówno Entry.remove i directoryEntry.removeRecursively nie usuwając niepuste katalogi - katalogi są usuwane są czyszczone z treści zamiast. + * `abort` i `truncate` funkcje nie są obsługiwane. + * zdarzenia postępu nie są zwalniani. Na przykład to obsługa będzie nie wykonywane: + +```javascript +writer.onprogress = function() { /*commands*/ }; +``` + +## Uaktualniania notatek + +W v1.0.0 tego pluginu struktury `FileEntry` i `DirectoryEntry` zmieniły się więcej zgodnie z opublikowaną specyfikacją. + +Poprzednie wersje (pre-1.0.0) plugin przechowywane urządzenia bezwzględna plik lokalizacja we właściwości `fullPath` `wpis` obiektów. Te ścieżki zazwyczaj będzie wyglądać + + /var/mobile/Applications//Documents/path/to/file (iOS) + /storage/emulated/0/path/to/file (Android) + + +Te ścieżki były także zwracany przez metodę `toURL()` `Entry` obiektów. + +Z v1.0.0 atrybut `fullPath` jest ścieżką do pliku, *względem katalogu głównego systemu plików HTML*. Tak powyżej ścieżki będzie teraz zarówno być reprezentowane przez obiekt `FileEntry` z `fullPath` o + + /path/to/file + + +Jeśli aplikacja działa z ścieżki bezwzględnej urządzeń, i możesz wcześniej źródło tych ścieżek przez właściwość `fullPath` `wpis` obiektów, należy zaktualizować kod, aby zamiast tego użyj `entry.toURL()`. + +Dla wstecznej kompatybilności, Metoda `resolveLocalFileSystemURL()` będzie zaakceptować urządzenia ścieżka bezwzględna i zwróci obiekt `Entry` odpowiadający, tak długo, jak ten plik istnieje w albo `TEMPORARY` lub `PERSISTENT` systemy plików. + +To szczególnie został problem z pluginem transferu plików, które poprzednio używane ścieżki bezwzględnej urządzeń (i wciąż można je przyjąć). Została zaktualizowana do pracy poprawnie z adresów URL plików, więc wymiana `entry.fullPath` z `entry.toURL()` powinno rozwiązać wszelkie problemy dostawanie ten plugin do pracy z plików w pamięci urządzenia. + +W v1.1.0 wartość zwracana przez `toURL()` został zmieniony (patrz \[CB-6394\] (https://issues.apache.org/jira/browse/CB-6394)) zwraca adres URL absolutnej "file://". wszędzie tam, gdzie jest to możliwe. Aby zapewnić ' cdvfile:'-URL można użyć `toInternalURL()` teraz. Ta metoda zwróci teraz adresy URL plików formularza + + cdvfile://localhost/persistent/path/to/file + + +który służy do jednoznacznej identyfikacji pliku. + +## Wykaz kodów błędów i ich znaczenie + +Gdy błąd jest generowany, jeden z następujących kodów będzie służyć. + +| Kod | Stała | +| ---:|:----------------------------- | +| 1 | `NOT_FOUND_ERR` | +| 2 | `SECURITY_ERR` | +| 3 | `ABORT_ERR` | +| 4 | `NOT_READABLE_ERR` | +| 5 | `ENCODING_ERR` | +| 6 | `NO_MODIFICATION_ALLOWED_ERR` | +| 7 | `INVALID_STATE_ERR` | +| 8 | `SYNTAX_ERR` | +| 9 | `INVALID_MODIFICATION_ERR` | +| 10 | `QUOTA_EXCEEDED_ERR` | +| 11 | `TYPE_MISMATCH_ERR` | +| 12 | `PATH_EXISTS_ERR` | + +## Konfigurowanie wtyczka (opcjonalny) + +Zestaw dostępnych plików może być skonfigurowany na platformie. Zarówno iOS i Android Tag w `pliku config.xml`, których nazwy plików do instalacji. Domyślnie włączone są wszystkie korzenie systemu plików. + + + + + +### Android + + * `files`: katalogu przechowywania plików aplikacji + * `files-external`: katalog aplikacji zewnętrznych plików + * `sdcard`: katalog globalny plik zewnętrzny (to jest głównym karty SD, jeśli jedna jest zainstalowana). Musi mieć uprawnienia `android.permission.WRITE_EXTERNAL_STORAGE` wobec używać ten. + * `cache`: katalogu wewnętrznej pamięci podręcznej aplikacji + * `cache-external`: katalogu aplikacji zewnętrznych pamięci podręcznej + * `root`: całe urządzenie systemu plików + +Android obsługuje również specjalnych plików o nazwie "dokumenty", który reprezentuje podkatalog "/ dokumenty /" w ramach systemu plików "pliki". + +### iOS + + * `library`: katalog biblioteki aplikacji + * `documents`: dokumenty katalogu aplikacji + * `cache`: katalogu pamięci podręcznej aplikacji + * `bundle`: pakiet aplikacji; Lokalizacja aplikacji na dysku (tylko do odczytu) + * `root`: całe urządzenie systemu plików + +Domyślnie katalogi biblioteki i dokumenty mogą być synchronizowane iCloud. Można również zażądać dwóch dodatkowych plików, `library-nosync` i `documents-nosync`, które stanowią specjalny katalog nie zsynchronizowane w `/Library` lub systemu plików `/Documents`. \ No newline at end of file diff --git a/plugins/cordova-plugin-file/doc/pl/index.md b/plugins/cordova-plugin-file/doc/pl/index.md new file mode 100644 index 0000000..1ccb330 --- /dev/null +++ b/plugins/cordova-plugin-file/doc/pl/index.md @@ -0,0 +1,338 @@ + + +# cordova-plugin-file + +Ten plugin implementuje API pliku, dzięki czemu dostęp do odczytu i zapisu do plików znajdujących się na urządzeniu. + +Ten plugin jest oparty na kilka specyfikacje, w tym: HTML5 File API + +Katalogi (nieistniejącego już) i System Najnowsze rozszerzenia: , chociaż większość z ten plugin kod został napisany podczas wcześniejszych specyfikacji były aktualne: + +To również implementuje specyfikację FileWriter: + +Wykorzystania, prosimy odnieść się do skały HTML5 doskonałe [plików art.][1] + + [1]: http://www.html5rocks.com/en/tutorials/file/filesystem/ + +Omówienie innych opcji przechowywania odnoszą się do Cordova z [magazynu przewodnik][2]. + + [2]: http://cordova.apache.org/docs/en/edge/cordova_storage_storage.md.html + +Ten plugin określa globalne `cordova.file` obiektu. + +Chociaż w globalnym zasięgu, to nie dostępne dopiero po `deviceready` imprezie. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(cordova.file); + } + + +## Instalacja + + cordova plugin add cordova-plugin-file + + +## Obsługiwane platformy + +* Amazon Fire OS +* Android +* BlackBerry 10 +* Firefox OS +* iOS +* Windows Phone 7 i 8 * +* Windows 8 * +* Przeglądarka + +* *Nie obsługują tych platform, `FileReader.readAsArrayBuffer` ani `FileWriter.write(blob)`.* + +## Gdzie przechowywać pliki + +Od v1.2.0 znajdują się adresy URL do katalogów ważne systemu plików. Każdy adres URL jest w formie *file:///path/to/spot/* i mogą być konwertowane na `DirectoryEntry` za pomocą `window.resolveLocalFileSystemURL()`. + +* `cordova.file.applicationDirectory`-Tylko do odczytu katalogu gdzie jest zainstalowana aplikacja. (*iOS*, *Android*, *BlackBerry 10*) + +* `cordova.file.applicationStorageDirectory`-Katalogu obszaru izolowanego aplikacji; na iOS to miejsce jest tylko do odczytu (ale podkatalogów określonego [jak `/Documents` ] są odczytu i zapisu). Wszystkie dane zawarte w jest prywatną do aplikacji. ( *iOS*, *Android*, *BlackBerry 10*) + +* `cordova.file.dataDirectory`-Trwałe i prywatne dane magazynowanie w izolowanym aplikacji przy użyciu pamięci wewnętrznej (na Android, jeśli trzeba użyć zewnętrznej pamięci, należy użyć `.externalDataDirectory` ). Na iOS, Katalog ten nie jest zsynchronizowane z iCloud (za pomocą `.syncedDataDirectory` ). (*iOS*, *Android*, *BlackBerry 10*) + +* `cordova.file.cacheDirectory`-Katalog dla plików buforowanych danych lub pliki, które aplikacji ponownie można łatwo tworzyć. System operacyjny może usunąć te pliki, gdy urządzenie działa niski na przechowywanie, niemniej jednak aplikacje nie powinny polegać na OS, aby usunąć pliki tutaj. (*iOS*, *Android*, *BlackBerry 10*) + +* `cordova.file.externalApplicationStorageDirectory`-Stosowania przestrzeni na zewnętrznej pamięci masowej. (*Android*) + +* `cordova.file.externalDataDirectory`-Gdzie umieścić pliki danych specyficznych dla aplikacji na zewnętrznej pamięci masowej. (*Android*) + +* `cordova.file.externalCacheDirectory`-Pamięci podręcznej aplikacji na zewnętrznej pamięci masowej. (*Android*) + +* `cordova.file.externalRootDirectory`-Korzeń zewnętrznej pamięci masowej (karty SD). (*Android*, *BlackBerry 10*) + +* `cordova.file.tempDirectory`-Temp katalogu systemu operacyjnego można wyczyścić w będzie. Nie należy polegać na OS wobec usunąć ten katalog; aplikacji należy zawsze usunąć pliki jako obowiązujące. (*iOS*) + +* `cordova.file.syncedDataDirectory`-Posiada pliki specyficzne dla aplikacji, które powinny być zsynchronizowane (np. do iCloud). (*iOS*) + +* `cordova.file.documentsDirectory`-Pliki prywatne do aplikacji, ale że mają znaczenie dla innych aplikacji (np. plików pakietu Office). (*iOS*) + +* `cordova.file.sharedDirectory`-Pliki dostępne na całym świecie do wszystkich aplikacji (*BlackBerry 10*) + +## Plik System układy + +Chociaż technicznie implementacyjnym, może być bardzo przydatne wiedzieć, jak `cordova.file.*` właściwości mapy fizycznej ścieżki na prawdziwe urządzenie. + +### iOS układ systemu plików + +| Ścieżka urządzenia | `Cordova.File.*` | `iosExtraFileSystems` | r/w? | trwałe? | Czyści OS | Synchronizacja | prywatne | +|:-------------------------------------------- |:--------------------------- |:--------------------- |:----:|:-------:|:-----------:|:--------------:|:--------:| +| `/ var/mobile/Applications/< UUID > /` | applicationStorageDirectory | - | r | N/D! | N/D! | N/D! | Tak | +|    `appname.app/` | applicationDirectory | pakiet | r | N/D! | N/D! | N/D! | Tak | +|       `www/` | - | - | r | N/D! | N/D! | N/D! | Tak | +|    `Documents/` | documentsDirectory | dokumenty | r/w | Tak | Nr | Tak | Tak | +|       `NoCloud/` | - | dokumenty nosync | r/w | Tak | Nr | Nr | Tak | +|    `Library` | - | Biblioteka | r/w | Tak | Nr | Tak? | Tak | +|       `NoCloud/` | dataDirectory | Biblioteka nosync | r/w | Tak | Nr | Nr | Tak | +|       `Cloud/` | syncedDataDirectory | - | r/w | Tak | Nr | Tak | Tak | +|       `Caches/` | cacheDirectory | pamięci podręcznej | r/w | Tak * | Tak * * *| | Nr | Tak | +|    `tmp/` | tempDirectory | - | r/w | Nie * * | Tak * * *| | Nr | Tak | + +* Pliki utrzymywały aplikacja zostanie ponownie uruchomiony i uaktualnienia, ale w tym katalogu mogą być rozliczone, gdy OS pragnienia. Aplikacji powinny być w stanie odtworzyć zawartość, która może być usunięta. + +* * Plików może utrzymywać się po ponownym uruchomieniu aplikacji, ale nie opierają się na tym zachowaniu. Pliki nie są gwarantowane w aktualizacji. Aplikacji należy usunąć pliki z tego katalogu, gdy ma to zastosowanie, ponieważ system operacyjny nie gwarantuje Kiedy (lub nawet jeśli) te pliki zostaną usunięte. + +* * *| System operacyjny może wyczyścić zawartość w tym katalogu, gdy czuje, że jest to konieczne, ale nie powoływać się na to. Należy wyczyścić ten katalog jako odpowiednie dla aplikacji. + +### Układ systemu Android plików + +| Ścieżka urządzenia | `Cordova.File.*` | `AndroidExtraFileSystems` | r/w? | trwałe? | Czyści OS | prywatne | +|:--------------------------------------- |:----------------------------------- |:------------------------------- |:----:|:-------:|:---------:|:--------:| +| `file:///android_asset/` | applicationDirectory | | r | N/D! | N/D! | Tak | +| `/Data/danych/< Aplikacja id > /` | applicationStorageDirectory | - | r/w | N/D! | N/D! | Tak | +|    `cache` | cacheDirectory | pamięci podręcznej | r/w | Tak | Tak * | Tak | +|    `files` | dataDirectory | pliki | r/w | Tak | Nr | Tak | +|       `Documents` | | dokumenty | r/w | Tak | Nr | Tak | +| `< sdcard > /` | externalRootDirectory | sdcard | r/w | Tak | Nr | Nr | +|    `Android/data//` | externalApplicationStorageDirectory | - | r/w | Tak | Nr | Nr | +|       `cache` | externalCacheDirectry | zewnętrznych pamięci podręcznej | r/w | Tak | Nie * * | Nr | +|       `files` | externalDataDirectory | zewnętrznych plików | r/w | Tak | Nr | Nr | + +* System operacyjny może okresowo usunąć ten katalog, ale nie opierają się na tym zachowaniu. Wyczyść zawartość tego katalogu jako odpowiednie dla danej aplikacji. Należy użytkownik przeczyścić pamięć podręczną ręcznie, zawartość w tym katalogu są usuwane. + +* * System operacyjny nie usunąć ten katalog automatycznie; Jesteś odpowiedzialny za zarządzanie zawartość siebie. Należy użytkownik przeczyścić pamięć podręczną ręcznie, zawartość katalogu są usuwane. + +**Uwaga**: Jeśli nie mogą być montowane pamięci masowej, właściwości `cordova.file.external*` są `wartości null`. + +### Układ systemu plików blackBerry 10 + +| Ścieżka urządzenia | `Cordova.File.*` | r/w? | trwałe? | Czyści OS | prywatne | +|:--------------------------------------------------------- |:--------------------------- |:----:|:-------:|:---------:|:--------:| +| `file:///accounts/1000/AppData/ < id aplikacji > /` | applicationStorageDirectory | r | N/D! | N/D! | Tak | +|    `app/native` | applicationDirectory | r | N/D! | N/D! | Tak | +|    `data/webviews/webfs/temporary/local__0` | cacheDirectory | r/w | Nr | Tak | Tak | +|    `data/webviews/webfs/persistent/local__0` | dataDirectory | r/w | Tak | Nr | Tak | +| `file:///accounts/1000/Removable/sdcard` | externalRemovableDirectory | r/w | Tak | Nr | Nr | +| `file:///accounts/1000/Shared` | sharedDirectory | r/w | Tak | Nr | Nr | + +*Uwaga*: gdy aplikacja jest rozmieszczana do pracy obwodu, wszystkie ścieżki są względne do /accounts/1000-enterprise. + +## Dziwactwa Androida + +### Lokalizacja przechowywania trwałych Android + +Istnieje wiele prawidłowe lokalizacje do przechowywania trwałych plików na telefonie z systemem Android. Zobacz [tę stronę][3] do szerokiej dyskusji o różnych możliwościach. + + [3]: http://developer.android.com/guide/topics/data/data-storage.html + +Poprzednie wersje pluginu wybrać lokalizację plików tymczasowych i trwałe podczas uruchamiania, czy urządzenie twierdził, że karta SD (lub równoważne magazynowanie podzia³) był montowany w oparciu. Czy karta SD została zamontowana, czy duży wewnętrzny magazynowanie podzia³ był dostępny (takie jak na Nexus urządzenia,) a następnie trwałe pliki będą przechowywane w katalogu głównego tego miejsca. Oznaczało to, że wszystkie aplikacje Cordova może Zobacz wszystkie pliki dostępne na karcie. + +Jeśli karta SD nie był dostępny, a następnie poprzednie wersje będzie przechowywać dane w `/data/data/`, która izoluje aplikacje od siebie, ale nadal może spowodować danych, które mają być współużytkowane przez użytkowników. + +Teraz jest możliwe, aby zdecydować, czy do przechowywania plików w lokalizacji magazynu plików, lub przy użyciu poprzednich logiki, z preferencją w aplikacji w pliku `config.xml`. Aby to zrobić, Dodaj jedną z tych dwóch linii do `pliku config.xml`: + + + + + + +Bez tej linii wtyczki pliku będzie używać `Compatibility` jako domyślny. Jeśli znacznik preferencji jest obecny i to nie jedną z tych wartości, aplikacja nie zostanie uruchomiona. + +Jeśli aplikacja wcześniej zostało wysłane do użytkowników, przy użyciu starszych (pre-1.0) wersję tego pluginu i ma zapisane na dysku pliki w trwałych plików, a następnie należy ustawić preferencje do `Compatibility`. Przełączania lokalizacji do "Internal" oznacza, że istniejących użytkowników, którzy ich aplikacja może być niesłabnący wobec dostęp ich wcześniej zapisane pliki, w zależności od ich urządzenie. + +Jeśli aplikacja jest nowy, lub ma nigdy wcześniej przechowywane pliki w systemie plików trwałe, ustawienie `Internal` generalnie jest zalecane. + +## Dziwactwa iOS + +* `cordova.file.applicationStorageDirectory`jest tylko do odczytu; próby przechowywania plików w katalogu głównym zakończy się niepowodzeniem. Użyj jednego z innych `cordova.file.*` właściwości zdefiniowane dla iOS (tylko `applicationDirectory` i `applicationStorageDirectory` są tylko do odczytu). +* `FileReader.readAsText(blob, encoding)` + * `encoding`Parametr nie jest obsługiwana, i kodowanie UTF-8 jest zawsze w efekcie. + +### iOS lokalizacja przechowywania trwałych + +Istnieją dwa ważne miejsca trwałe pliki na urządzenia iOS: katalogu dokumentów i katalogu biblioteki. Poprzednie wersje pluginu tylko kiedykolwiek przechowywane trwałe pliki w katalogu dokumentów. To miał ten efekt uboczny od rozpoznawalności wszystkie pliki aplikacji w iTunes, który był często niezamierzone, zwłaszcza dla aplikacji, które obsługują wiele małych plików, zamiast produkuje kompletne dokumenty do wywozu, który jest przeznaczenie katalogu. + +Teraz jest możliwe, aby zdecydować, czy do przechowywania plików w dokumentach lub katalogu biblioteki, z preferencją w pliku `config.xml` aplikacji. Aby to zrobić, Dodaj jedną z tych dwóch linii do `pliku config.xml`: + + + + + + +Bez tej linii wtyczki pliku będzie używać `Compatibility` jako domyślny. Jeśli znacznik preferencji jest obecny i to nie jedną z tych wartości, aplikacja nie zostanie uruchomiona. + +Jeśli aplikacja wcześniej zostało wysłane do użytkowników, przy użyciu starszych (pre-1.0) wersję tego pluginu i ma zapisane na dysku pliki w trwałych plików, a następnie należy ustawić preferencje do `Compatibility`. Przełączania lokalizacji do `Library` oznaczałoby, że istniejących użytkowników, którzy ich aplikacja będzie niesłabnący wobec dostęp ich wcześniej zapisane pliki. + +Jeśli aplikacja jest nowy, lub nigdy wcześniej przechowywane pliki w trwałych plików, ustawień `Library` ogólnie jest zalecane. + +## Firefox OS dziwactwa + +API systemu plików nie jest obsługiwany macierzyście przez Firefox OS i jest zaimplementowany jako podkładki na indexedDB. + +* Nie usuwając niepuste katalogi +* Nie obsługuje metadane dla katalogów +* Metody `copyTo` i `moveTo` nie obsługuje katalogi + +Obsługiwane są następujące ścieżki danych: * `applicationDirectory` - używa `xhr`, aby uzyskać lokalne pliki, które są pakowane z aplikacji. * `dataDirectory` - na trwałe dane specyficzne dla aplikacji pliki. * `cacheDirectory` - buforowanych plików, które powinny przetrwać ponowne uruchomienie aplikacji (aplikacje nie powinny polegać na OS, aby usunąć pliki tutaj). + +## Quirks przeglądarki + +### Wspólne dziwactw i uwagi + +* Każda przeglądarka używa własnej piaskownicy plików. IE i Firefox Użyj IndexedDB jako podstawa. Wszystkie przeglądarki za pomocą ukośnika jako separatora katalogu ścieżka. +* Wpisy w katalogu mają być tworzone sukcesywnie. Na przykład wywołanie `fs.root.getDirectory (' dir1/dir2 ', {create:true}, successCallback, errorCallback)` zakończy się niepowodzeniem, jeśli nie istnieje dir1. +* Plugin żądania użytkownika uprawnień do używania trwałe przechowywanie przy pierwszym uruchomieniu aplikacji. +* Wtyczka obsługuje `cdvfile://localhost` (lokalne zasoby) tylko. Czyli zewnętrznych zasobów nie są obsługiwane przez `cdvfile`. +* Plugin nie następować po ["Plik API systemu nazw 8.3 ograniczenia"][4]. +* Obiektu BLOB i pliku "`close` funkcja nie jest obsługiwana. +* `FileSaver` i `BlobBuilder` nie są obsługiwane przez ten plugin i nie ma artykułów. +* Plugin nie obsługuje `requestAllFileSystems`. Ta funkcja jest również brak w specyfikacji. +* Wpisy w katalogu nie zostaną usunięte, jeśli używasz `create: true` flaga dla istniejącego katalogu. +* Pliki utworzone za pomocą konstruktora nie są obsługiwane. Zamiast tego należy użyć metody entry.file. +* Każda przeglądarka używa własnej postaci URL odwołania blob. +* `readAsDataURL` funkcja jest obsługiwana, ale mediatype w Chrome zależy od wejścia z rozszerzeniem, mediatype w IE zawsze jest pusty (który jest taki sam jak `zwykły tekst` według specyfikacji), mediatype w Firefox jest zawsze `aplikacji/oktet strumień`. Na przykład, jeśli treść jest `abcdefg` Firefox wraca z `danych: stosowanie / octet-stream, base64, YWJjZGVmZw ==`, czyli zwraca `danych:; base64, YWJjZGVmZw ==`, Chrome zwraca `danych: < mediatype w zależności od rozszerzenia nazwy; > base64, YWJjZGVmZw ==`. +* `toInternalURL` zwraca ścieżkę w postaci `file:///persistent/path/to/entry` (Firefox, IE). Chrom zwraca ścieżkę w postaci `cdvfile://localhost/persistent/file`. + + [4]: http://www.w3.org/TR/2011/WD-file-system-api-20110419/#naming-restrictions + +### Dziwactwa chrom + +* Chrom plików nie jest od razu gotowy po gotowe urządzenia. Jako rozwiązanie alternatywne można subskrybować zdarzenia `filePluginIsReady`. Przykład: + + javascript + window.addEventListener('filePluginIsReady', function(){ console.log('File plugin is ready');}, false); + + +Funkcja `window.isFilePluginReadyRaised` służy do sprawdzenia, czy zdarzenie już została podniesiona. -kwoty plików tymczasowych i trwałe window.requestFileSystem nie są ograniczone w Chrome. -W celu zwiększenia trwałego magazynu w Chrome, należy wywołać metodę `window.initPersistentFileSystem`. Domyślnie trwałe dyskowa jest 5 MB. -Chrome wymaga `--pozwalają--dostęp z plików` uruchomić argument na poparcie API za pośrednictwem protokołu `file:///`. -`Plik` obiekt będzie nie zmieniło jeśli flaga `{create:true}` gdy już istniejący `wpis`. -wydarzenia `zwrotu` właściwość jest zestaw true w Chrome. Jest to sprzeczne ze [specyfikacji][5]. -Funkcja `toURL` w Chrome zwraca `plików:`-poprzedzona ścieżką w zależności od aplikacji hosta. Na przykład, `filesystem:file:///persistent/somefile.txt`, `filesystem:http://localhost:8080/persistent/somefile.txt`. -wynik funkcji `toURL` nie zawierają ukośnika w wpis w katalogu. Chrom usuwa katalogi z ciąć doczepiane adresów URL poprawnie choć. -Metoda `resolveLocalFileSystemURL` wymaga przychodzących `url` mają prefiks `plików`. Na przykład parametr `adresu url` do `resolveLocalFileSystemURL` powinny być w formie `filesystem:file:///persistent/somefile.txt`, w przeciwieństwie do formularza `file:///persistent/somefile.txt` w Android. -Przestarzałe `toNativeURL` funkcja nie jest obsługiwana i nie tylko. -Funkcja `setMetadata` jest nie podane w specyfikacji i nie jest obsługiwane. -INVALID_MODIFICATION_ERR (kod: 9) jest generowany zamiast SYNTAX_ERR(code: 8) na żądanie nieistniejącą plików. -INVALID_MODIFICATION_ERR (kod: 9) jest generowany zamiast PATH_EXISTS_ERR(code: 12) próbuje stworzyć wyłącznie pliku lub katalogu, który już istnieje. -INVALID_MODIFICATION_ERR (kod: 9) jest generowany zamiast NO_MODIFICATION_ALLOWED_ERR(code: 6) na próby wywołania removeRecursively w głównym systemie plików. -INVALID_MODIFICATION_ERR (kod: 9) jest generowany zamiast NOT_FOUND_ERR(code: 1) na trudny do katalogu moveTo, który nie istnieje. + + [5]: http://dev.w3.org/2009/dap/file-system/file-writer.html + +### Na bazie IndexedDB impl dziwactw (Firefox i IE) + +* `.` i `.` nie są obsługiwane. +* IE obsługuje `file:///`-tryb; tylko obsługiwane tryb jest obsługiwany (http://localhost:xxxx). +* Rozmiar plików Firefox nie jest ograniczona, ale każde rozszerzenie 50MB zwróci użytkownikowi uprawnienia. IE10 pozwala maksymalnie 10mb połączone "appcache" i IndexedDB używane w implementacji systemu plików bez monitowania, gdy trafisz na tym poziomie, które uzyskasz, jeśli chcesz mogła ona zostać zwiększony do max 250mb na stronie. Więc `rozmiar` parametru funkcja `requestFileSystem` nie wpływa na system plików Firefox i IE. +* `readAsBinaryString` funkcja nie jest określona w specyfikacji i nie obsługiwane w IE i nie tylko. +* `File.Type` ma zawsze wartość null. +* Nie należy utworzyć wpis za pomocą DirectoryEntry wystąpienie wynik wywołania zwrotnego, który został usunięty. W przeciwnym razie dostaniesz wpisem"wiszące". +* Zanim będzie można przeczytać plik, który został napisany tylko trzeba uzyskać nowe wystąpienie tego pliku. +* Funkcja `setMetadata`, która nie jest określona w specyfikacji obsługuje tylko zmian pola `modificationTime`. +* `copyTo` i `moveTo` funkcji nie obsługuje katalogi. +* Metadanych w katalogów nie jest obsługiwana. +* Zarówno Entry.remove i directoryEntry.removeRecursively nie usuwając niepuste katalogi - katalogi są usuwane są czyszczone z treści zamiast. +* `abort` i `truncate` funkcje nie są obsługiwane. +* zdarzenia postępu nie są zwalniani. Na przykład to obsługa będzie nie wykonywane: + + javascript + writer.onprogress = function() { /*commands*/ }; + + +## Uaktualniania notatek + +W v1.0.0 tego pluginu struktury `FileEntry` i `DirectoryEntry` zmieniły się więcej zgodnie z opublikowaną specyfikacją. + +Poprzednie wersje (pre-1.0.0) plugin przechowywane urządzenia bezwzględna plik lokalizacja we właściwości `fullPath` `wpis` obiektów. Te ścieżki zazwyczaj będzie wyglądać + + /var/mobile/Applications//Documents/path/to/file (iOS) + /storage/emulated/0/path/to/file (Android) + + +Te ścieżki były także zwracany przez metodę `toURL()` `Entry` obiektów. + +Z v1.0.0 atrybut `fullPath` jest ścieżką do pliku, *względem katalogu głównego systemu plików HTML*. Tak powyżej ścieżki będzie teraz zarówno być reprezentowane przez obiekt `FileEntry` z `fullPath` o + + /path/to/file + + +Jeśli aplikacja działa z ścieżki bezwzględnej urządzeń, i możesz wcześniej źródło tych ścieżek przez właściwość `fullPath` `wpis` obiektów, należy zaktualizować kod, aby zamiast tego użyj `entry.toURL()`. + +Dla wstecznej kompatybilności, Metoda `resolveLocalFileSystemURL()` będzie zaakceptować urządzenia ścieżka bezwzględna i zwróci obiekt `Entry` odpowiadający, tak długo, jak ten plik istnieje w albo `TEMPORARY` lub `PERSISTENT` systemy plików. + +To szczególnie został problem z pluginem transferu plików, które poprzednio używane ścieżki bezwzględnej urządzeń (i wciąż można je przyjąć). Została zaktualizowana do pracy poprawnie z adresów URL plików, więc wymiana `entry.fullPath` z `entry.toURL()` powinno rozwiązać wszelkie problemy dostawanie ten plugin do pracy z plików w pamięci urządzenia. + +W v1.1.0 wartość zwracana przez `toURL()` został zmieniony (patrz \[CB-6394\] (https://issues.apache.org/jira/browse/CB-6394)) zwraca adres URL absolutnej "file://". wszędzie tam, gdzie jest to możliwe. Aby zapewnić ' cdvfile:'-URL można użyć `toInternalURL()` teraz. Ta metoda zwróci teraz adresy URL plików formularza + + cdvfile://localhost/persistent/path/to/file + + +który służy do jednoznacznej identyfikacji pliku. + +## Wykaz kodów błędów i ich znaczenie + +Gdy błąd jest generowany, jeden z następujących kodów będzie służyć. + +| Kod | Stała | +| ---:|:----------------------------- | +| 1 | `NOT_FOUND_ERR` | +| 2 | `SECURITY_ERR` | +| 3 | `ABORT_ERR` | +| 4 | `NOT_READABLE_ERR` | +| 5 | `ENCODING_ERR` | +| 6 | `NO_MODIFICATION_ALLOWED_ERR` | +| 7 | `INVALID_STATE_ERR` | +| 8 | `SYNTAX_ERR` | +| 9 | `INVALID_MODIFICATION_ERR` | +| 10 | `QUOTA_EXCEEDED_ERR` | +| 11 | `TYPE_MISMATCH_ERR` | +| 12 | `PATH_EXISTS_ERR` | + +## Konfigurowanie wtyczka (opcjonalny) + +Zestaw dostępnych plików może być skonfigurowany na platformie. Zarówno iOS i Android Tag w `pliku config.xml`, których nazwy plików do instalacji. Domyślnie włączone są wszystkie korzenie systemu plików. + + + + + +### Android + +* `files`: katalogu przechowywania plików aplikacji +* `files-external`: katalog aplikacji zewnętrznych plików +* `sdcard`: katalog globalny plik zewnętrzny (to jest głównym karty SD, jeśli jedna jest zainstalowana). Musi mieć uprawnienia `android.permission.WRITE_EXTERNAL_STORAGE` wobec używać ten. +* `cache`: katalogu wewnętrznej pamięci podręcznej aplikacji +* `cache-external`: katalogu aplikacji zewnętrznych pamięci podręcznej +* `root`: całe urządzenie systemu plików + +Android obsługuje również specjalnych plików o nazwie "dokumenty", który reprezentuje podkatalog "/ dokumenty /" w ramach systemu plików "pliki". + +### iOS + +* `library`: katalog biblioteki aplikacji +* `documents`: dokumenty katalogu aplikacji +* `cache`: katalogu pamięci podręcznej aplikacji +* `bundle`: pakiet aplikacji; Lokalizacja aplikacji na dysku (tylko do odczytu) +* `root`: całe urządzenie systemu plików + +Domyślnie katalogi biblioteki i dokumenty mogą być synchronizowane iCloud. Można również zażądać dwóch dodatkowych plików, `library-nosync` i `documents-nosync`, które stanowią specjalny katalog nie zsynchronizowane w `/Library` lub systemu plików `/Documents`. diff --git a/plugins/cordova-plugin-file/doc/pl/plugins.md b/plugins/cordova-plugin-file/doc/pl/plugins.md new file mode 100644 index 0000000..6e8fe86 --- /dev/null +++ b/plugins/cordova-plugin-file/doc/pl/plugins.md @@ -0,0 +1,101 @@ + + +# Uwagi dla programistów wtyczki + +Te notatki są przeznaczone przede wszystkim dla Androida i iOS deweloperów, którzy chcieli pisac pluginy które interfejs z systemu plików za pomocą wtyczki pliku. + +## Praca z Cordova pliku system adresów URL + +Od wersji 1.0.0, ten plugin ma używane adresy URL z `cdvfile` system dla wszystkich komunikacji przez most, a nie narażać urządzenia raw ścieżki systemu plików JavaScript. + +Na stronie JavaScript oznacza to, że FileEntry i DirectoryEntry obiekty mają fullPath atrybut, który jest głównym systemie plików HTML. Jeśli twój plugin JavaScript API akceptuje obiektu FileEntry lub DirectoryEntry, należy zadzwonić `.toURL()` dla tego obiektu przed przekazaniem Altpradl do kodu macierzystego. + +### Konwersja cdvfile: / / URL do ścieżki fileystem + +Wtyczek, które trzeba pisać do systemu plików może chcesz przekonwertować odebranych plików systemu adres URL lokalizacji rzeczywistych plików. Istnieje wiele sposobów robi to, w zależności od macierzystego platformy. + +Ważne jest, aby pamiętać, że nie wszystkie `cdvfile://` adresy URL są można zmapować na prawdziwe pliki w urządzeniu. Niektóre adresy URL może odnosić się do aktywów na urządzeniu, które nie są reprezentowane przez pliki, lub nawet może odnosić się do zasobów zdalnych. Ze względu na te możliwości wtyczki należy zawsze sprawdzić, czy się znaczącego wyniku powrót podczas próby konwersji adresów URL do ścieżki. + +#### Androida + +Na Android, najprostsza metoda konwersji `cdvfile://` URL do ścieżki systemu plików jest użycie `org.apache.cordova.CordovaResourceApi` . `CordovaResourceApi`jest kilka metod, które mogą obsługiwać `cdvfile://` adresów URL: + + Widok sieci Web jest członkiem Plugin klasy CordovaResourceApi resourceApi = webView.getResourceApi(); + + Uzyskać URL file:/// reprezentujących ten plik na urządzeniu / / lub ten sam adres URL niezmienione, jeśli nie mogą być mapowane do pliku fileURL Uri = resourceApi.remapUri(Uri.parse(cdvfileURL)); + + +Jest również możliwe, aby korzystać z wtyczki pliku bezpośrednio: + + org.apache.cordova.file.FileUtils przywóz; + org.apache.cordova.file.FileSystem przywóz; + java.net.MalformedURLException przywóz; + + Uzyskać pliku plugin manager wtyczki FileUtils filePlugin = (FileUtils)webView.pluginManager.getPlugin("File"); + + Biorąc pod uwagę adres URL, uzyskać ścieżkę dla to spróbuj {String ścieżka = filePlugin.filesystemPathForURL(cdvfileURL);} catch (MalformedURLException e) {/ / url plików nie było uznane} + + +Do przeliczenia ścieżki do `cdvfile://` URL: + + org.apache.cordova.file.LocalFilesystemURL przywóz; + + Uzyskanie obiektu LocalFilesystemURL na ścieżkę urządzenia / / lub null, jeśli nie może być reprezentowana jako adres URL cdvfile. + LocalFilesystemURL url = filePlugin.filesystemURLforLocalPath(path); + Dostać reprezentację ciąg adresu URL obiektu String cdvfileURL = url.toString(); + + +Jeśli twój plugin tworzy plik, i chcesz zwraca obiekt FileEntry dla niego, użyj pliku plugin: + + Zwraca JSON struktura nadaje się do powrotu do JavaScript, / / lub null, jeśli ten plik nie jest reprezentować jako adres URL cdvfile. + Wpis JSONObject = filePlugin.getEntryForFile(file); + + +#### iOS + +Cordova na iOS nie korzystać z tego samego `CordovaResourceApi` koncepcji jak Android. Na iOS należy użyć pliku plugin do konwersji między adresach URL i ścieżkach plików. + + Uzyskać obiekt CDVFilesystem URL URL url ciąg CDVFilesystemURL * = [CDVFilesystemURL fileSystemURLWithString:cdvfileURL]; + Uzyskać ścieżkę dla URL obiektu, stawka zerowa, jeśli nie mogą być mapowane do ścieżki pliku NSString * = [filePlugin filesystemPathForURL:url]; + + + Dostać CDVFilesystem URL obiektu na ścieżkę urządzenia lub / / zerowe, jeśli nie może być reprezentowana jako adres URL cdvfile. + CDVFilesystemURL * url = [filePlugin fileSystemURLforLocalPath:path]; + Dostać reprezentację ciąg adresu URL obiektu NSString * cdvfileURL = [url absoluteString]; + + +Jeśli twój plugin tworzy plik, i chcesz zwraca obiekt FileEntry dla niego, użyj pliku plugin: + + Dostać CDVFilesystem URL obiektu na ścieżkę urządzenia lub / / zerowe, jeśli nie może być reprezentowana jako adres URL cdvfile. + CDVFilesystemURL * url = [filePlugin fileSystemURLforLocalPath:path]; + Struktura wrócić do JavaScript NSDictionary * wpis = [filePlugin makeEntryForLocalURL:url] + + +#### JavaScript + +W JavaScript, aby uzyskać `cdvfile://` adres URL z obiektu FileEntry lub DirectoryEntry, wystarczy zadzwonić `.toURL()` na to: + + var cdvfileURL = entry.toURL(); + + +W plugin reakcji obsługi przerobić od zwróconych struktury FileEntry do rzeczywistego obiektu wejścia, kod obsługi należy zaimportować pliku plugin i utworzyć nowy obiekt: + + utworzyć odpowiedni wpis obiektu var wpis; + Jeśli (entryStruct.isDirectory) {wpis = nowy DirectoryEntry (entryStruct.name, entryStruct.fullPath, nowe FileSystem(entryStruct.filesystemName));} jeszcze {wpis = nowy FileEntry (entryStruct.name, entryStruct.fullPath, nowe FileSystem(entryStruct.filesystemName));} \ No newline at end of file diff --git a/plugins/cordova-plugin-file/doc/plugins.md b/plugins/cordova-plugin-file/doc/plugins.md new file mode 100644 index 0000000..a3329d6 --- /dev/null +++ b/plugins/cordova-plugin-file/doc/plugins.md @@ -0,0 +1,120 @@ + + +Notes for plugin developers +=========================== + +These notes are primarily intended for Android and iOS developers who want to write plugins which interface with the file system using the File plugin. + +Working with Cordova file system URLs +------------------------------------- + +Since version 1.0.0, this plugin has used URLs with a `cdvfile` scheme for all communication over the bridge, rather than exposing raw device file system paths to JavaScript. + +On the JavaScript side, this means that FileEntry and DirectoryEntry objects have a fullPath attribute which is relative to the root of the HTML file system. If your plugin's JavaScript API accepts a FileEntry or DirectoryEntry object, you should call `.toURL()` on that object before passing it across the bridge to native code. + +### Converting cdvfile:// URLs to fileystem paths + +Plugins which need to write to the filesystem may want to convert a received file system URL to an actual filesystem location. There are multiple ways of doing this, depending on the native platform. + +It is important to remember that not all `cdvfile://` URLs are mappable to real files on the device. Some URLs can refer to assets on device which are not represented by files, or can even refer to remote resources. Because of these possibilities, plugins should always test whether they get a meaningful result back when trying to convert URLs to paths. + +#### Android + +On Android, the simplest method to convert a `cdvfile://` URL to a filesystem path is to use `org.apache.cordova.CordovaResourceApi`. `CordovaResourceApi` has several methods which can handle `cdvfile://` URLs: + + // webView is a member of the Plugin class + CordovaResourceApi resourceApi = webView.getResourceApi(); + + // Obtain a file:/// URL representing this file on the device, + // or the same URL unchanged if it cannot be mapped to a file + Uri fileURL = resourceApi.remapUri(Uri.parse(cdvfileURL)); + +It is also possible to use the File plugin directly: + + import org.apache.cordova.file.FileUtils; + import org.apache.cordova.file.FileSystem; + import java.net.MalformedURLException; + + // Get the File plugin from the plugin manager + FileUtils filePlugin = (FileUtils)webView.pluginManager.getPlugin("File"); + + // Given a URL, get a path for it + try { + String path = filePlugin.filesystemPathForURL(cdvfileURL); + } catch (MalformedURLException e) { + // The filesystem url wasn't recognized + } + +To convert from a path to a `cdvfile://` URL: + + import org.apache.cordova.file.LocalFilesystemURL; + + // Get a LocalFilesystemURL object for a device path, + // or null if it cannot be represented as a cdvfile URL. + LocalFilesystemURL url = filePlugin.filesystemURLforLocalPath(path); + // Get the string representation of the URL object + String cdvfileURL = url.toString(); + +If your plugin creates a file, and you want to return a FileEntry object for it, use the File plugin: + + // Return a JSON structure suitable for returning to JavaScript, + // or null if this file is not representable as a cdvfile URL. + JSONObject entry = filePlugin.getEntryForFile(file); + +#### iOS + +Cordova on iOS does not use the same `CordovaResourceApi` concept as Android. On iOS, you should use the File plugin to convert between URLs and filesystem paths. + + // Get a CDVFilesystem URL object from a URL string + CDVFilesystemURL* url = [CDVFilesystemURL fileSystemURLWithString:cdvfileURL]; + // Get a path for the URL object, or nil if it cannot be mapped to a file + NSString* path = [filePlugin filesystemPathForURL:url]; + + + // Get a CDVFilesystem URL object for a device path, or + // nil if it cannot be represented as a cdvfile URL. + CDVFilesystemURL* url = [filePlugin fileSystemURLforLocalPath:path]; + // Get the string representation of the URL object + NSString* cdvfileURL = [url absoluteString]; + +If your plugin creates a file, and you want to return a FileEntry object for it, use the File plugin: + + // Get a CDVFilesystem URL object for a device path, or + // nil if it cannot be represented as a cdvfile URL. + CDVFilesystemURL* url = [filePlugin fileSystemURLforLocalPath:path]; + // Get a structure to return to JavaScript + NSDictionary* entry = [filePlugin makeEntryForLocalURL:url] + +#### JavaScript + +In JavaScript, to get a `cdvfile://` URL from a FileEntry or DirectoryEntry object, simply call `.toURL()` on it: + + var cdvfileURL = entry.toURL(); + +In plugin response handlers, to convert from a returned FileEntry structure to an actual Entry object, your handler code should import the File plugin and create a new object: + + // create appropriate Entry object + var entry; + if (entryStruct.isDirectory) { + entry = new DirectoryEntry(entryStruct.name, entryStruct.fullPath, new FileSystem(entryStruct.filesystemName)); + } else { + entry = new FileEntry(entryStruct.name, entryStruct.fullPath, new FileSystem(entryStruct.filesystemName)); + } + diff --git a/plugins/cordova-plugin-file/doc/ru/index.md b/plugins/cordova-plugin-file/doc/ru/index.md new file mode 100644 index 0000000..3c9fca9 --- /dev/null +++ b/plugins/cordova-plugin-file/doc/ru/index.md @@ -0,0 +1,275 @@ + + +# cordova-plugin-file + +Этот плагин реализует API файла, позволяя доступ на чтение и запись в файлы, находящиеся на устройстве. + +Этот плагин основан на нескольких спецификации, в том числе: HTML5 API файла + +(Ныне несуществующей) каталоги и систему расширений Последнее: , хотя большая часть кода, плагин был написан, когда ранее спец был текущим: + +Он также реализует уничтожал spec: + +Для использования, пожалуйста, обратитесь к HTML5 скалы отличные [файловой системы статьи.][1] + + [1]: http://www.html5rocks.com/en/tutorials/file/filesystem/ + +Обзор других вариантов хранения найти Cordova [хранения руководства][2]. + + [2]: http://cordova.apache.org/docs/en/edge/cordova_storage_storage.md.html + +## Установка + + cordova plugin add cordova-plugin-file + + +## Поддерживаемые платформы + +* Amazon Fire OS +* Android +* BlackBerry 10 +* Firefox OS +* iOS +* Windows Phone 7 и 8 * +* Windows 8 * + +* *Эти платформы не поддерживают `FileReader.readAsArrayBuffer` , ни `FileWriter.write(blob)` .* + +## Где хранить файлы + +По состоянию на v1.2.0 приведены URL-адреса для важных файлов в системные каталоги. Каждый URL-адрес в виде *file:///path/to/spot/*и может быть преобразован в `DirectoryEntry` с помощью`window.resolveLocalFileSystemURL()`. + +* `cordova.file.applicationDirectory`-Каталог только для чтения, где установлено приложение. (*iOS*, *Android*, *BlackBerry 10*) + +* `cordova.file.applicationStorageDirectory`-Корневой каталог приложения в песочнице; на iOS это место только для чтения (но определенных подкаталогов [как `/Documents` ], чтения записи). Все данные, содержащиеся в частных в приложение. ( *iOS*, *Android*, *BlackBerry 10*) + +* `cordova.file.dataDirectory`-Хранения стойкие и частных данных в приложения в песочнице с использованием внутренней памяти (на Android, если необходимо использовать внешнюю память, использовать `.externalDataDirectory` ). На iOS, этот каталог не синхронизируется с iCloud (использование `.syncedDataDirectory` ). (*iOS*, *Android*, *BlackBerry 10*) + +* `cordova.file.cacheDirectory`-Каталог для кэшированных данных файлов или все файлы, которые ваше приложение может повторно создать легко. ОС может удалить эти файлы, когда устройства хватает на хранение, тем не менее, приложения не должны опираться на OS, чтобы удалить файлы здесь. (*iOS*, *Android*, *BlackBerry 10*) + +* `cordova.file.externalApplicationStorageDirectory`-Пространство приложения на внешнем хранилище. (*Android*) + +* `cordova.file.externalDataDirectory`-Куда положить файлы данных конкретного приложения на внешнем хранилище. (*Android*) + +* `cordova.file.externalCacheDirectory`-Применение кэш на внешние накопители. (*Android*) + +* `cordova.file.externalRootDirectory`-Корень внешние накопители (SD карта). (*Android*, *BlackBerry 10*) + +* `cordova.file.tempDirectory`-Временный каталог, что ОС можно снять на будет. Не следует полагаться на OS, чтобы очистить этот каталог; Ваше приложение всегда следует удалять файлы в соответствующих случаях. (*iOS*) + +* `cordova.file.syncedDataDirectory`-Содержит файлы приложения, которые должны быть синхронизированы (например, к iCloud). (*iOS*) + +* `cordova.file.documentsDirectory`-Файлы для приложения, но это являются значимыми для других приложений (например, файлы Office). (*iOS*) + +* `cordova.file.sharedDirectory`-Файлы глобально доступной для всех приложений (*BlackBerry 10*) + +## Макеты файловой системы + +Хотя технически деталь реализации, она может быть очень полезно знать как `cordova.file.*` карта свойства физические пути на реальном устройстве. + +### iOS расположения файловой системы + +| Путь к устройству | `Cordova.File.*` | `iosExtraFileSystems` | r/w? | стойкие? | Очищает ОС | Синхронизация | частные | +|:---------------------------------------------- |:--------------------------- |:--------------------- |:----:|:--------:|:----------:|:-------------:|:-------:| +| `/ var/мобильного/применения/< UUID > /` | applicationStorageDirectory | - | r | Н/Д | Н/Д | Н/Д | Да | +|    `appname.app/` | applicationDirectory | расслоение | r | Н/Д | Н/Д | Н/Д | Да | +|       `www/` | - | - | r | Н/Д | Н/Д | Н/Д | Да | +|    `Documents/` | documentsDirectory | документы | r/w | Да | Нет | Да | Да | +|       `NoCloud/` | - | документы nosync | r/w | Да | Нет | Нет | Да | +|    `Library` | - | Библиотека | r/w | Да | Нет | Да? | Да | +|       `NoCloud/` | dataDirectory | Библиотека nosync | r/w | Да | Нет | Нет | Да | +|       `Cloud/` | syncedDataDirectory | - | r/w | Да | Нет | Да | Да | +|       `Caches/` | cacheDirectory | кэш | r/w | Да * | Да * * *| | Нет | Да | +|    `tmp/` | tempDirectory | - | r/w | Не * * | Да * * *| | Нет | Да | + +* Файлы сохраняются приложения перезагрузки и обновления, но этот каталог может быть очищен, когда ОС желаний. Ваше приложение должно иметь возможность воссоздать любое содержание, которое может быть удалено. + +* * Файлы могут сохраняться перезагрузками app, но не полагайтесь на это поведение. Для продолжения обновления файлов не гарантируется. Приложение должно удалить файлы из этого каталога, когда это применимо, как операционная система не гарантирует когда (или даже если) эти файлы будут удалены. + +* * *| ОС может очистить содержимое этого каталога, когда он считает это необходимым, но не полагайтесь на это. Необходимо снять этот каталог в зависимости от вашего приложения. + +### Расположения Android файловой системы + +| Путь к устройству | `Cordova.File.*` | `AndroidExtraFileSystems` | r/w? | стойкие? | Очищает ОС | частные | +|:--------------------------------- |:----------------------------------- |:------------------------- |:----:|:--------:|:----------:|:-------:| +| `File:///android_asset/` | applicationDirectory | | r | Н/Д | Н/Д | Да | +| `/ Data/data/< app-id > /` | applicationStorageDirectory | - | r/w | Н/Д | Н/Д | Да | +|    `cache` | cacheDirectory | кэш | r/w | Да | Да * | Да | +|    `files` | dataDirectory | файлы | r/w | Да | Нет | Да | +|       `Documents` | | документы | r/w | Да | Нет | Да | +| `< sdcard > /` | externalRootDirectory | SDCard | r/w | Да | Нет | Нет | +|    `Android/data//` | externalApplicationStorageDirectory | - | r/w | Да | Нет | Нет | +|       `cache` | externalCacheDirectry | кэш внешние | r/w | Да | Не * * | Нет | +|       `files` | externalDataDirectory | файлы внешние | r/w | Да | Нет | Нет | + +* ОС может периодически удалять этот каталог, но не полагайтесь на это поведение. Очистите содержимое этого каталога в зависимости от вашего приложения. Если пользователь вручную очистить кэш, содержимое этого каталога будут удалены. + +* * ОС не ясно этот каталог автоматически; Вы несете ответственность за управление содержимым самостоятельно. Если пользователь вручную очистить кэш, содержимое каталога будут удалены. + +**Примечание**: Если нельзя монтировать внешние накопители, `cordova.file.external*` Свойства`null`. + +### BlackBerry 10 расположения файловой системы + +| Путь к устройству | `Cordova.File.*` | r/w? | стойкие? | Очищает ОС | частные | +|:--------------------------------------------------- |:--------------------------- |:----:|:--------:|:----------:|:-------:| +| `File:///Accounts/1000/AppData/ < app id > /` | applicationStorageDirectory | r | Н/Д | Н/Д | Да | +|    `app/native` | applicationDirectory | r | Н/Д | Н/Д | Да | +|    `data/webviews/webfs/temporary/local__0` | cacheDirectory | r/w | Нет | Да | Да | +|    `data/webviews/webfs/persistent/local__0` | dataDirectory | r/w | Да | Нет | Да | +| `File:///Accounts/1000/Removable/SDCard` | externalRemovableDirectory | r/w | Да | Нет | Нет | +| `File:///Accounts/1000/Shared` | sharedDirectory | r/w | Да | Нет | Нет | + +*Примечание*: при развертывании приложения для работы периметра, все пути относительны /accounts/1000-enterprise. + +## Особенности Android + +### Местоположение Android постоянного хранения + +Есть несколько допустимых мест для хранения постоянных файлов на устройстве Android. Смотрите [эту страницу][3] для широкого обсуждения различных возможностей. + + [3]: http://developer.android.com/guide/topics/data/data-storage.html + +Предыдущие версии плагина будет выбирать расположение временных и постоянных файлов при запуске, основанный на ли устройство утверждал, что SD-карта (или эквивалентные хранения раздел) был смонтирован. Если была смонтирована SD-карты, или если большой внутренней памяти раздел был доступен (такие как на устройствах Nexus,), то постоянные файлы будут храниться в корне этого пространства. Это означало, что все apps Cordova могли видеть все файлы, имеющиеся на карте. + +Если SD-карты не был доступен, то предыдущих версий будет хранить данные в `/data/data/` , которая изолирует приложения друг от друга, но все еще может причина данные распределяются между пользователями. + +Это теперь можно выбрать, следует ли хранить файлы в месте хранения внутренних файлов, или с использованием предыдущей логики, с предпочтением в вашем приложении `config.xml` файл. Чтобы сделать это, добавить один из этих двух линий в `config.xml` : + + + + + + +Без этой линии, будет использовать файл плагина `Compatibility` по умолчанию. Если тег предпочтений присутствует и не является одним из этих значений, приложение не запустится. + +Если ранее была отгружена приложения для пользователей, используя старые (до 1.0) версию этого плагина и имеет сохраненные файлы в файловой системе постоянных, то вы должны установить предпочтения `Compatibility` . Переключение местоположение для «Внутреннего» будет означать, что существующие пользователи, которые обновить их применение может быть не в состоянии получить доступ к их сохраненные ранее файлы, в зависимости от их устройства. + +Если ваше приложение является новым или ранее никогда не хранит файлы в стойких файловой системы, то `Internal` как правило рекомендуется настройка. + +## Особенности iOS + +* `cordova.file.applicationStorageDirectory`доступен только для чтения; попытка хранения файлов в корневом каталоге не удастся. Использовать один из других `cordova.file.*` свойства, определенные для iOS (только `applicationDirectory` и `applicationStorageDirectory` доступны только для чтения). +* `FileReader.readAsText(blob, encoding)` + * `encoding`Параметр не поддерживается, и UTF-8 кодирование действует всегда. + +### iOS место постоянного хранения + +Существует два допустимых местоположений для хранения постоянных файлов на устройства iOS: документы каталогов и библиотека. Предыдущие версии плагина только когда-либо постоянные файлы хранятся в папке документы. Это был побочный эффект делает все файлы приложения в iTunes, который часто был непреднамеренным, особенно для приложений, которые обрабатывают большое количество мелких файлов, вместо того, чтобы производить полный комплект документов для экспорта, который является цель каталога. + +Это теперь можно выбрать, следует ли хранить файлы в документы или каталоге библиотеки, с предпочтением в вашем приложении `config.xml` файл. Чтобы сделать это, добавить один из этих двух линий в `config.xml` : + + + + + + +Без этой линии, будет использовать файл плагина `Compatibility` по умолчанию. Если тег предпочтений присутствует и не является одним из этих значений, приложение не запустится. + +Если ранее была отгружена приложения для пользователей, используя старые (до 1.0) версию этого плагина и имеет сохраненные файлы в файловой системе постоянных, то вы должны установить предпочтения `Compatibility` . Переключение расположения `Library` будет означать, что существующих пользователей обновить их применения будет не в состоянии получить доступ к их сохраненные ранее файлы. + +Если ваше приложение является новым или ранее никогда не хранит файлы в стойких файловой системы, то `Library` как правило рекомендуется настройка. + +## Особенности Firefox OS + +API файловой системы изначально не поддерживается Firefox OS и реализуется как оболочка поверх indexedDB. + +* Не вынимая непустые каталоги +* Не поддерживает метаданные для каталогов +* Методы `copyTo` и `moveTo` не поддерживает каталоги + +Поддерживаются следующие пути данных: * `applicationDirectory` -использует `xhr` чтобы получить локальные файлы, которые упакованы с приложением. * `dataDirectory` - Для постоянных данных конкретного приложения файлов. * `cacheDirectory` -Кэшированных файлов, которые должны выжить перезагрузки приложения (Apps не следует полагаться на OS, чтобы удалить файлы из здесь). + +## Обновление примечания + +В v1.0.0 этого плагина `FileEntry` и `DirectoryEntry` структур изменились, более соответствует опубликованной спецификации. + +Предыдущий (pre-1.0.0) версии плагина хранятся устройства Абсолют файл расположение в `fullPath` свойства `Entry` объектов. Эти пути обычно будет выглядеть + + /var/mobile/Applications//Documents/path/to/file (iOS) + /storage/emulated/0/path/to/file (Android) + + +Эти пути также были возвращены `toURL()` метода `Entry` объектов. + +С v1.0.0 `fullPath` атрибут является путь к файлу, *заданный относительно корня файловой системы HTML*. Таким образом, выше пути будет теперь оба быть представлено `FileEntry` объект с `fullPath` из + + /path/to/file + + +Если ваше приложение работает с устройства Абсолют путями, и ранее были получены эти пути через `fullPath` свойства `Entry` объектов, то вам следует обновить код для использования `entry.toURL()` вместо этого. + +Для обратной совместимости, `resolveLocalFileSystemURL()` метод будет принимать путь Абсолют устройства и будет возвращать `Entry` объект, соответствующий его, до тех пор, как этот файл существует в рамках либо `TEMPORARY` или `PERSISTENT` файловых систем. + +Это особенно была проблема с плагином передачи файлов, который ранее использовался устройства Абсолют пути (и все еще может принять их). Он был обновлен для корректной работы с файловой системы URL, так что замена `entry.fullPath` с `entry.toURL()` должен решить любые вопросы, получить этот плагин для работы с файлами на устройстве. + +В v1.1.0 возвращаемое значение из `toURL()` был изменен (см. \[CB-6394\] (https://issues.apache.org/jira/browse/CB-6394)) для возвращения URL-адрес абсолютным «file://». где это возможно. Для обеспечения ' cdvfile:'-вы можете использовать URL-адрес `toInternalURL()` сейчас. Этот метод будет возвращать теперь файловой системы URL формы + + cdvfile://localhost/persistent/path/to/file + + +который может использоваться для уникальной идентификации файла. + +## Список кодов ошибок и значения + +Когда возникает ошибка, один из следующих кодов будет использоваться. + +| Код | Постоянная | +| ---:|:----------------------------- | +| 1 | `NOT_FOUND_ERR` | +| 2 | `SECURITY_ERR` | +| 3 | `ABORT_ERR` | +| 4 | `NOT_READABLE_ERR` | +| 5 | `ENCODING_ERR` | +| 6 | `NO_MODIFICATION_ALLOWED_ERR` | +| 7 | `INVALID_STATE_ERR` | +| 8 | `SYNTAX_ERR` | +| 9 | `INVALID_MODIFICATION_ERR` | +| 10 | `QUOTA_EXCEEDED_ERR` | +| 11 | `TYPE_MISMATCH_ERR` | +| 12 | `PATH_EXISTS_ERR` | + +## Настройка плагина (опционально) + +Набор доступных файловых систем может быть настроен на платформе. IOS и Android признают тег в `config.xml` имена которых файловые системы для установки. По умолчанию включены все корни файловой системы. + + + + + +### Android + +* `files`: Каталог для хранения внутреннего файла приложения +* `files-external`: Каталог хранения внешнего файла приложения +* `sdcard`: Глобальный внешний файл каталог хранения (это корень SD-карты, если таковая установлена). Вы должны иметь `android.permission.WRITE_EXTERNAL_STORAGE` разрешение использовать это. +* `cache`: Каталог внутреннего кэша приложения +* `cache-external`: Каталог приложения внешней кэш-памяти +* `root`: Все устройство файловой системы + +Android поддерживает также Специальный файловую систему под названием «документы», которая представляет подкаталог «/ документы /» в пределах файловой системы «файлы». + +### iOS + +* `library`: Каталог библиотеки приложения +* `documents`: Каталог документов приложения +* `cache`: Каталог кэша приложения +* `bundle`: Пакет приложения; расположение самого приложения на диске (только для чтения) +* `root`: Все устройство файловой системы + +По умолчанию каталоги библиотеки и документы можно синхронизировать с iCloud. Вы также можете заказать два дополнительных файловых систем, `library-nosync` и `documents-nosync` , которые представляют Специальный каталог не синхронизируются в `/Library` или `/Documents` файловой системы. diff --git a/plugins/cordova-plugin-file/doc/ru/plugins.md b/plugins/cordova-plugin-file/doc/ru/plugins.md new file mode 100644 index 0000000..2445d09 --- /dev/null +++ b/plugins/cordova-plugin-file/doc/ru/plugins.md @@ -0,0 +1,124 @@ + + +# Примечания для разработчиков плагинов + +Эти примечания предназначены прежде всего для Android и iOS разработчиков, которые хотят писать плагины какой интерфейс с файловой системой, с помощью файла плагина. + +## Работа с Кордова файловой системы URL + +Начиная с версии 1.0.0, этот плагин использует URL-адресов с `cdvfile` схема для всех коммуникации через мост, а не подвергая пути файловой системы raw устройства для JavaScript. + +На стороне JavaScript это означает, что объекты DirectoryEntry и FileEntry fullPath атрибут, который является по отношению к корневой файловой системе HTML. Если ваш плагин JavaScript API принимает объект DirectoryEntry или FileEntry, необходимо вызвать `.toURL()` для этого объекта перед передачей их через мост в машинный код. + +### Преобразование cdvfile: / / URL-адреса в пути fileystem + +Плагины, которые нужно написать в файловой системе может потребоваться преобразовать URL-адреса системы полученный файл в место фактической файловой системы. Существует несколько способов сделать это, в зависимости от родной платформе. + +Важно помнить, что не все `cdvfile://` URL-адреса являются отображаемыми файлами на устройстве. Некоторые URL может относиться к активам на устройстве, которые не представлены файлы, или может даже обратиться к удаленным ресурсам. Из-за эти возможности плагины следует всегда проверять ли они получают результат обратно при попытке преобразовать URL-адреса в пути. + +#### Android + +На Android, самый простой способ для преобразования `cdvfile://` URL-адрес к пути файловой системы заключается в использовании `cordova-plugin-CordovaResourceApi` . `CordovaResourceApi`Есть несколько методов, которые можно обработать `cdvfile://` URL-адреса: + + // webView is a member of the Plugin class + CordovaResourceApi resourceApi = webView.getResourceApi(); + + // Obtain a file:/// URL representing this file on the device, + // or the same URL unchanged if it cannot be mapped to a file + Uri fileURL = resourceApi.remapUri(Uri.parse(cdvfileURL)); + + +Это также можно использовать плагин файл непосредственно: + + import cordova-plugin-file.FileUtils; + import cordova-plugin-file.FileSystem; + import java.net.MalformedURLException; + + // Get the File plugin from the plugin manager + FileUtils filePlugin = (FileUtils)webView.pluginManager.getPlugin("File"); + + // Given a URL, get a path for it + try { + String path = filePlugin.filesystemPathForURL(cdvfileURL); + } catch (MalformedURLException e) { + // The filesystem url wasn't recognized + } + + +Для преобразования пути к `cdvfile://` URL-адрес: + + import cordova-plugin-file.LocalFilesystemURL; + + // Get a LocalFilesystemURL object for a device path, + // or null if it cannot be represented as a cdvfile URL. + LocalFilesystemURL url = filePlugin.filesystemURLforLocalPath(path); + // Get the string representation of the URL object + String cdvfileURL = url.toString(); + + +Если ваш плагин создает файл, и вы хотите вернуть объект FileEntry для него, используйте файл плагина: + + // Return a JSON structure suitable for returning to JavaScript, + // or null if this file is not representable as a cdvfile URL. + JSONObject entry = filePlugin.getEntryForFile(file); + + +#### iOS + +Кордова на iOS не использовать те же `CordovaResourceApi` понятие, как Android. На iOS вы должны использовать файл плагин для преобразования URL-адреса и пути файловой системы. + + // Get a CDVFilesystem URL object from a URL string + CDVFilesystemURL* url = [CDVFilesystemURL fileSystemURLWithString:cdvfileURL]; + // Get a path for the URL object, or nil if it cannot be mapped to a file + NSString* path = [filePlugin filesystemPathForURL:url]; + + + // Get a CDVFilesystem URL object for a device path, or + // nil if it cannot be represented as a cdvfile URL. + CDVFilesystemURL* url = [filePlugin fileSystemURLforLocalPath:path]; + // Get the string representation of the URL object + NSString* cdvfileURL = [url absoluteString]; + + +Если ваш плагин создает файл, и вы хотите вернуть объект FileEntry для него, используйте файл плагина: + + // Get a CDVFilesystem URL object for a device path, or + // nil if it cannot be represented as a cdvfile URL. + CDVFilesystemURL* url = [filePlugin fileSystemURLforLocalPath:path]; + // Get a structure to return to JavaScript + NSDictionary* entry = [filePlugin makeEntryForLocalURL:url] + + +#### JavaScript + +В JavaScript, чтобы получить `cdvfile://` URL от объекта DirectoryEntry или FileEntry, просто позвоните `.toURL()` на него: + + var cdvfileURL = entry.toURL(); + + +В плагин обработчики ответ для преобразования из возвращаемой структуры FileEntry объект фактического вступления, код обработчика следует импортировать файл плагина и создайте новый объект: + + // create appropriate Entry object + var entry; + if (entryStruct.isDirectory) { + entry = new DirectoryEntry(entryStruct.name, entryStruct.fullPath, new FileSystem(entryStruct.filesystemName)); + } else { + entry = new FileEntry(entryStruct.name, entryStruct.fullPath, new FileSystem(entryStruct.filesystemName)); + } diff --git a/plugins/cordova-plugin-file/doc/zh/README.md b/plugins/cordova-plugin-file/doc/zh/README.md new file mode 100644 index 0000000..c600587 --- /dev/null +++ b/plugins/cordova-plugin-file/doc/zh/README.md @@ -0,0 +1,335 @@ + + +# cordova-plugin-file + +[![Build Status](https://travis-ci.org/apache/cordova-plugin-file.svg)](https://travis-ci.org/apache/cordova-plugin-file) + +這個外掛程式實現檔 API 允許對檔駐留在該設備上的讀/寫訪問。 + +這個外掛程式基於幾個規格,包括: HTML5 檔 API [HTTP://www.w3.org/TR/FileAPI/](http://www.w3.org/TR/FileAPI/) + +(現已解散) 目錄和系統擴展最新: [HTTP://www.w3.org/TR/2012/WD-file-system-api-20120417/](http://www.w3.org/TR/2012/WD-file-system-api-20120417/)雖然大部分的外掛程式代碼寫時較早的規格是當前: [HTTP://www.w3.org/TR/2011/WD-file-system-api-20110419/](http://www.w3.org/TR/2011/WD-file-system-api-20110419/) + +它還實現 FileWriter 規格: [HTTP://dev.w3.org/2009/dap/file-system/file-writer.html](http://dev.w3.org/2009/dap/file-system/file-writer.html) + +用法,請參閱對 HTML5 的岩石優秀[檔案系統文章。](http://www.html5rocks.com/en/tutorials/file/filesystem/) + +其他存儲選項的概述,請參閱科爾多瓦的[存儲指南](http://cordova.apache.org/docs/en/edge/cordova_storage_storage.md.html). + +這個外掛程式定義全球 `cordova.file` 物件。 + +雖然在全球範圍內,它不可用直到 `deviceready` 事件之後。 + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(cordova.file); + } + + +## 安裝 + + cordova plugin add cordova-plugin-file + + +## 支援的平臺 + + * 亞馬遜火 OS + * Android 系統 + * 黑莓 10 + * 火狐瀏覽器作業系統 + * iOS + * Windows Phone 7 和 8 * + * Windows 8 * + * Windows* + * 瀏覽器 + +\* *These platforms do not support `FileReader.readAsArrayBuffer` nor `FileWriter.write(blob)`.* + +## 存儲檔的位置 + +截至 v1.2.0,提供重要的檔案系統目錄的 Url。 每個 URL 位於表單 *file:///path/to/spot/*,和可以轉換為使用 `window.resolveLocalFileSystemURL()` 的 `DirectoryEntry`. + + * `cordova.file.applicationDirectory`-唯讀目錄在哪裡安裝的應用程式。(*iOS*、*安卓*、*黑莓 10*) + + * `cordova.file.applicationStorageDirectory`-根目錄下的應用程式的沙箱 ;在 iOS 上此位置是唯讀 (但特定的子目錄 [像 `/Documents` ] 都是讀寫)。 中包含的所有資料都是私有的應用程式。 ( *iOS*、*安卓*、*黑莓 10*) + + * `cordova.file.dataDirectory`資料持久性和私有資料存儲在內部記憶體使用的應用程式的沙箱內 (在安卓系統,如果你需要使用外部儲存體,使用 `.externalDataDirectory` )。 在 iOS,此目錄不與 iCloud 同步 (使用 `.syncedDataDirectory` )。 (*iOS*、*安卓*、*黑莓 10*) + + * `cordova.file.cacheDirectory`-緩存的資料檔案或您的應用程式重新可以輕鬆地創建的任何檔的目錄。 作業系統可能會刪除這些檔,該設備在存儲上運行低時,然而,應用程式不應依賴的作業系統,請刪除檔在這裡。 (*iOS*、*安卓*、*黑莓 10*) + + * `cordova.file.externalApplicationStorageDirectory`-應用程式外部存儲上的空間。(*安卓*) + + * `cordova.file.externalDataDirectory`-放在外部存儲特定于應用程式的資料檔案的位置。(*安卓*) + + * `cordova.file.externalCacheDirectory`-在外部存儲應用程式緩存。(*安卓*) + + * `cordova.file.externalRootDirectory`-外部存儲 (SD 卡) 的根。(*安卓*、*黑莓 10*) + + * `cordova.file.tempDirectory`-OS 可以清除時的空目錄會。 不依賴于 OS,以清除此目錄 ;您的應用程式,應總是移除作為適用的檔。 (*iOS*) + + * `cordova.file.syncedDataDirectory`-保存應同步 (例如到 iCloud) 的特定于應用程式的檔。(*iOS*) + + * `cordova.file.documentsDirectory`-檔私有的應用程式,但這是對其他應用程式 (例如 Office 檔) 有意義。(*iOS*) + + * `cordova.file.sharedDirectory`-對所有應用程式 (*黑莓 10*全域可用的檔) + +## 檔案系統佈局 + +雖然技術上實現的細節,它可以是很有必要瞭解如何 `cordova.file.*` 屬性對應到實體路徑在實際設備上。 + +### iOS 檔案系統佈局 + +| 設備路徑 | `cordova.file.*` | `iosExtraFileSystems` | r/w 嗎? | 持續性嗎? | OS 清除 | 同步 | 私人 | +|:---------------------------------------------- |:--------------------------- |:--------------------- |:------:|:-------:|:------------:|:---:|:--:| +| `/ 無功/移動/應用程式/< UUID > /` | applicationStorageDirectory | - | r | 不適用 | 不適用 | 不適用 | 是啊 | +|    `appname.app/` | applicationDirectory | 束 | r | 不適用 | 不適用 | 不適用 | 是啊 | +|       `www/` | - | - | r | 不適用 | 不適用 | 不適用 | 是啊 | +|    `Documents/` | documentsDirectory | 檔 | r/w | 是啊 | 無 | 是啊 | 是啊 | +|       `NoCloud/` | - | 檔 nosync | r/w | 是啊 | 無 | 無 | 是啊 | +|    `Library` | - | 圖書館 | r/w | 是啊 | 無 | 是嗎? | 是啊 | +|       `NoCloud/` | dataDirectory | 圖書館 nosync | r/w | 是啊 | 無 | 無 | 是啊 | +|       `Cloud/` | syncedDataDirectory | - | r/w | 是啊 | 無 | 是啊 | 是啊 | +|       `Caches/` | cacheDirectory | 快取記憶體 | r/w | 是啊 * | 是啊**\* | 無 | 是啊 | +|    `tmp/` | tempDirectory | - | r/w | 無** | 是啊**\* | 無 | 是啊 | + +\ * 檔堅持跨應用程式重新開機和升級,但每當 OS 的欲望,可以清除此目錄。您的應用程式應該能夠重新創建任何內容可能會被刪除。 + +**檔可能會持續整個應用程式重新開機,但不是依賴于這種行為。 不保證檔在更新之間持續存在。 您的應用程式時適用,是應該刪除此目錄的檔,因為作業系統並不能保證何時 (或即使) 中刪除這些檔。 + +**\ * 作業系統可能會清除此目錄的內容,每當它感覺它是必要的但做不依賴于此。 你應該清除此目錄為適合您的應用程式。 + +### Android 的檔案系統佈局 + +| 設備路徑 | `cordova.file.*` | `AndroidExtraFileSystems` | r/w 嗎? | 持續性嗎? | OS 清除 | 私人 | +|:------------------------------------------------ |:----------------------------------- |:------------------------- |:------:|:-----:|:-------:|:--:| +| `file:///android_asset/` | applicationDirectory | | r | 不適用 | 不適用 | 是啊 | +| `/ 資料資料/< 應用程式 id > /` | applicationStorageDirectory | - | r/w | 不適用 | 不適用 | 是啊 | +|    `cache` | cacheDirectory | 快取記憶體 | r/w | 是啊 | 是啊\* | 是啊 | +|    `files` | dataDirectory | 檔 | r/w | 是啊 | 無 | 是啊 | +|       `Documents` | | 檔 | r/w | 是啊 | 無 | 是啊 | +| `< sd 卡 > /` | externalRootDirectory | sd 卡 | r/w | 是啊 | 無 | 無 | +|    `Android/data//` | externalApplicationStorageDirectory | - | r/w | 是啊 | 無 | 無 | +|       `cache` | externalCacheDirectry | 外部快取記憶體 | r/w | 是啊 | 無** | 無 | +|       `files` | externalDataDirectory | 外部檔 | r/w | 是啊 | 無 | 無 | + +\ * 作業系統可能定期清除此目錄,但不是依賴于這種行為。 清除此為適合您的應用程式的目錄的內容。 使用者應手動清除緩存,將刪除此目錄的內容。 + +** OS 不會清除此目錄自動;你是負責管理自己的內容。 使用者應手動清除緩存,目錄中的內容將被刪除。 + +**注**: 如果外部存儲無法裝入,`cordova.file.external*` 屬性為 `空`. + +### 黑莓 10 檔案系統佈局 + +| 設備路徑 | `cordova.file.*` | r/w 嗎? | 持續性嗎? | OS 清除 | 私人 | +|:----------------------------------------------------------- |:--------------------------- |:------:|:-----:|:-----:|:--:| +| `file:///accounts/1000/appdata/ < 應用程式 id > /` | applicationStorageDirectory | r | 不適用 | 不適用 | 是啊 | +|    `app/native` | applicationDirectory | r | 不適用 | 不適用 | 是啊 | +|    `data/webviews/webfs/temporary/local__0` | cacheDirectory | r/w | 無 | 是啊 | 是啊 | +|    `data/webviews/webfs/persistent/local__0` | dataDirectory | r/w | 是啊 | 無 | 是啊 | +| `file:///accounts/1000/removable/sdcard` | externalRemovableDirectory | r/w | 是啊 | 無 | 無 | +| `file:///accounts/1000/shared` | sharedDirectory | r/w | 是啊 | 無 | 無 | + +*注意*: 當應用程式部署工作週邊時,所有路徑都是相對於 /accounts/1000-enterprise。 + +## Android 的怪癖 + +### Android 的持久性存儲位置 + +有很多有效的位置來存儲持久性檔在 Android 設備上。 請參閱 [此頁面](http://developer.android.com/guide/topics/data/data-storage.html) 的各種可能性進行廣泛討論。 + +以前版本的外掛程式會選擇在啟動時,基於該設備是否聲稱 SD 卡 (或等效存儲分區) 展開,臨時和永久檔的位置。 如果被掛載 SD 卡,或一個大的內部存儲分區可用 (如 nexus 系列設備上) 然後持久性檔將存儲在該空間的根目錄中。 這意味著所有的科爾多瓦應用程式可以看到所有可用的檔在卡片上。 + +如果 SD 卡不是可用的那麼以前的版本中將存儲資料下的 `/data/data/`,其中隔離應用程式從彼此,但仍可能導致使用者之間共用的資料。 + +現在可以選擇是否將檔存儲在內部檔的存儲位置,或使用以前的邏輯,與您的應用程式的 `config.xml` 檔中的偏好。 要執行此操作,請將以下兩行之一添加到 `config.xml`: + + + + + + +如果這條線,沒有檔外掛程式將使用 `Compatibility` 作為預設值。如果首選項標記存在,並不是這些值之一,應用程式將無法啟動。 + +如果您的應用程式以前已被運到使用者,使用較舊的 (預 1.0) 版本的這個外掛程式,並具有持久性的檔,系統中存儲的檔,然後您應該設置 `Compatibility` 偏好。 切換到"Internal"的位置,將意味著現有使用者升級他們的應用程式可能無法訪問他們以前存儲的檔,具體取決於他們的設備。 + +如果您的應用程式是新的或以前從未有持久性的檔案系統中存儲檔,那麼通常建議使用 `Internal` 設置。 + +### 緩慢的遞迴操作為 /android_asset 的 + +上市資產目錄是在 android 系統很慢的。 你可以讓時間加速了不過,通過將`src/android/build-extras.gradle`添加到您的 android 專案的根 (也需要 cordova-android@4.0.0 或更高版本)。 + +## iOS 的怪癖 + + * `cordova.file.applicationStorageDirectory`是唯讀的 ;試圖存儲內的根目錄中的檔將會失敗。 使用的另一個 `cordova.file.*` 為 iOS 定義的屬性 (只有 `applicationDirectory` 和 `applicationStorageDirectory` 都是唯讀)。 + * `FileReader.readAsText(blob, encoding)` + * `encoding`參數不受支援,而 utf-8 編碼總是效果。 + +### iOS 的持久性存儲位置 + +有兩個有效的位置來存儲持久性在 iOS 設備上的檔: 檔目錄和圖書館目錄。 以前版本的外掛程式永遠只能將持久性檔存儲在文檔目錄中。 這已經使所有應用程式檔可見在 iTunes,往往是無意為之,尤其是對於處理大量小檔的應用程式中,而不是生產供出口,該目錄的既定的目標是證件齊全的副作用。 + +現在可以選擇是否將檔存儲在檔或庫目錄,與您的應用程式的 `config.xml` 檔中的偏好。 要執行此操作,請將以下兩行之一添加到 `config.xml`: + + + + + + +如果這條線,沒有檔外掛程式將使用 `Compatibility` 作為預設值。如果首選項標記存在,並不是這些值之一,應用程式將無法啟動。 + +如果您的應用程式以前已被運到使用者,使用較舊的 (預 1.0) 版本的這個外掛程式,並具有持久性的檔,系統中存儲的檔,然後您應該設置 `Compatibility` 偏好。 切換到 `Library` 的位置,將意味著現有使用者升級他們的應用程式將無法訪問他們以前存儲的檔。 + +如果您的應用程式是新的或以前從未有持久性的檔案系統中存儲檔,那麼通常建議使用 `Internal` 設置。 + +## 火狐瀏覽器作業系統的怪癖 + +檔案系統 API 本身不支援火狐瀏覽器的作業系統,作為墊片在 indexedDB 上實現的。 + + * 不會失敗時刪除非空的目錄 + * 不支援中繼資料的目錄 + * 方法 `copyTo` 和 `moveTo` 不支援目錄 + +支援以下資料路徑: * `applicationDirectory`-使用 `xhr` 獲取與應用程式打包的本地檔。 `dataDirectory`-用於持久性的特定于應用程式的資料檔案。 `cacheDirectory`-生存應重新開機應用程式的快取檔案 (應用程式不應依賴作業系統來刪除檔在這裡)。 + +## 瀏覽器的怪癖 + +### 常見的怪癖和備註 + + * 每個瀏覽器使用其自己的沙箱檔案系統。IE 和火狐瀏覽器使用 IndexedDB 作為一個基地。所有瀏覽器都使用正斜杠作為路徑中的目錄分隔符號。 + * 目錄條目不得不先後創建。 例如,調用 `fs.root.getDirectory (' dir1/dir2 ',{create:true},successCallback,errorCallback)`,如果不存在 dir1 將失敗。 + * 外掛程式將請求使用者許可權,以便在應用程式初次開機使用持久性存儲。 + * 外掛程式支援 `cdvfile://localhost` (本地資源) 只。通過 `cdvfile` 不支援外部資源即. + * 該外掛程式不遵循 ["檔案系統 API 8.3 命名限制"](http://www.w3.org/TR/2011/WD-file-system-api-20110419/#naming-restrictions). + * Blob 和檔 ' `close` 功能不受支援。 + * `FileSaver` 和 `BlobBuilder` 不支援這個外掛程式,沒有存根 (stub)。 + * 該外掛程式不支援 `requestAllFileSystems`。這個功能也是缺少規範中。 + * 在目錄中的條目將不會被刪除,如果您使用 `create: true` 標誌為現有目錄。 + * 不支援通過建構函式創建的檔。你應該使用 entry.file 方法。 + * 每個瀏覽器使用它自己的形式為 blob 的 URL 引用。 + * 支援 `readAsDataURL` 功能,但在 Chrome 中的媒體類型取決於輸入副檔名,在 IE 中的媒體類型都始終空著 (這是 `純文字` 按照說明書一樣),在 Firefox 中的媒體類型始終是 `應用程式/八位位元組流`。 例如,如果內容是 `abcdefg` 然後火狐瀏覽器返回 `資料: 應用程式 / 八位位元組流 ; base64,YWJjZGVmZw = =`,即返回 `資料: ; base64,YWJjZGVmZw = =`,鉻返回 `資料: < 媒體類型根據擴展條目名稱 > ; base64,YWJjZGVmZw = =`. + * 在表單 `file:///persistent/path/to/entry` 火狐瀏覽器 IE),`toInternalURL` 返回的路徑。 鉻在表單 `cdvfile://localhost/persistent/file` 返回的路徑. + +### 鉻的怪癖 + + * 設備準備好事件之後,chrome 檔案系統並不能立即準備。作為一種變通方法,您可以訂閱到 `filePluginIsReady` 事件。示例: + +```javascript +window.addEventListener('filePluginIsReady', function(){ console.log('File plugin is ready');}, false); +``` + +你可以使用 `window.isFilePluginReadyRaised` 函數來檢查是否已經引發了事件。 -window.requestFileSystem 臨時和永久性檔案系統配額並不局限于鉻。 為增加中鉻的持久性存儲,您需要調用 `window.initPersistentFileSystem` 方法。 預設情況下,持久性存儲配額為 5 MB。 鉻需要 `— — 允許--訪問-從-檔` 通過 `file:///` 協定運行參數對 API 的支援。 -如果您使用標誌,將不更改 `檔` 物件 `{create:true}` 現有 `條目` 的時候。 -事件 `可取消` 屬性設置為 true 在 Chrome 中。 這是違反了 [規範](http://dev.w3.org/2009/dap/file-system/file-writer.html)。 -中鉻的 `toURL` 函數返回 `檔案系統:`-首碼路徑具體取決於應用程式主機。 例如,`filesystem:file:///persistent/somefile.txt`,`filesystem:HTTP://localhost:8080/persistent/somefile.txt`。 -`toURL` 函數結果不包含尾部反斜線在目錄條目的情況下。 鉻雖然正確解析目錄帶斜杠落後的 url。 -`resolveLocalFileSystemURL` 方法需要入站的 `url` 必須具有 `檔案系統` 首碼。 例如,`resolveLocalFileSystemURL` 的 `url` 參數應在表單 `filesystem:file:///persistent/somefile.txt` 而不是表單 `file:///persistent/somefile.txt` 在安卓系統。 -不推薦使用 `toNativeURL` 函數不受支援,並且沒有存根 (stub)。 -`setMetadata` 功能是沒有說出的規格,並且不支援。 -INVALID_MODIFICATION_ERR (代碼: 9) 而不是引發 SYNTAX_ERR(code: 8) 上請求一個不存在的檔案系統。 -INVALID_MODIFICATION_ERR (代碼: 9) 而不是引發 PATH_EXISTS_ERR(code: 12) 上嘗試專門創建一個檔或目錄,它已經存在。 -INVALID_MODIFICATION_ERR (代碼: 9) 而不是引發 NO_MODIFICATION_ALLOWED_ERR(code: 6) 在試圖調用 removeRecursively 的根檔案系統上。 -INVALID_MODIFICATION_ERR (代碼: 9) 而不是引發 NOT_FOUND_ERR(code: 1) 試到 moveTo 目錄不存在。 + +### 基於 IndexedDB 的 impl 怪癖 (Firefox 和 IE) + + * `.` 和 `.` 不受支援。 + * IE 不支援 `file:///`-模式 ;只有託管的模式是支援 (HTTP://localhost:xxxx)。 + * 火狐瀏覽器的檔案系統大小不是有限,但每個 50 MB 擴展會要求使用者的許可權。 IE10 允許達 10 mb 的 AppCache 和 IndexedDB 檔案系統的實現中使用而不會提示,一旦你達到這一水準你會詢問您是否允許它增加到每個網站的 250 mb 的最大合併。 所以 `requestFileSystem` 函數的 `大小` 參數並不影響檔案系統相容 Firefox 和 IE。 + * `readAsBinaryString` 函數在規範中沒有注明不支援在 IE 中和沒有存根 (stub)。 + * `file.type` 始終為 null。 + * 您不應創建條目使用已刪除的目錄實例回檔結果。否則,你會得到一個 '掛條目'。 + * 您可以讀取一個檔,其中只是寫之前你需要獲得的此檔的新實例。 + * `setMetadata` 函數,在規範中沒有注明支援 `modificationTime` 欄位的更改。 + * `copyTo` 和 `moveTo` 函數不支援目錄。 + * 不支援目錄的中繼資料。 + * 兩個 Entry.remove 和 directoryEntry.removeRecursively 不失敗時刪除非空的目錄-相反與內容一起清理目錄被刪除。 + * 不支援 `abort` 和 `truncate` 函數。 + * 進度事件不會觸發。例如,將不執行此處理程式: + +```javascript +writer.onprogress = function() { /*commands*/ }; +``` + +## 升級筆記 + +在這個外掛程式 v1.0.0,`FileEntry` 和 `DirectoryEntry` 的結構已經改變,以更加一致的已發表說明書。 + +以前 (pre-1.0.0) 版本的外掛程式中 `輸入` 物件的 `完整路徑` 屬性存放裝置固定檔案位置。這些路徑通常會看起來像 + + /var/mobile/Applications//Documents/path/to/file (iOS) + /storage/emulated/0/path/to/file (Android) + + +這些路徑還返回的 `Entry` 物件的 `toURL()` 方法。 + +與 v1.0.0,`完整路徑` 屬性是到檔中,*相對於 HTML 檔案系統的根目錄* 的路徑。 因此,上述路徑會現在都由一個 `FileEntry` 物件的 `完整路徑`, + + /path/to/file + + +如果您的應用程式與設備-絕對路徑,並且您以前檢索到這些路徑通過 `條目` 物件的 `完整路徑` 屬性,然後您應該更新您的代碼以改用 `entry.toURL()`。 + +為向後相容性,`resolveLocalFileSystemURL()` 方法將接受一個設備-絕對路徑,並將返回相應的 `條目` 物件,只要在 `臨時` 或 `永久性` 的檔案系統內的檔是否存在。 + +這尤其是一直與檔案傳輸外掛程式,以前使用設備絕對路徑的問題 (和仍然可以接受他們)。 已更新它能夠正常運行與檔案系統的 Url,所以用 `entry.toURL()` 替換 `entry.fullPath` 應解決任何問題,得到該外掛程式來處理設備上的檔。 + +在 v1.1.0 `toURL()` 的傳回值被更改 (見 [CB-6394] (HTTPs://issues.apache.org/jira/browse/CB-6394)) 為返回絕對 file:// URL。 只要有可能。 確保 'cdvfile:' — — 你現在可以用 `toInternalURL()` 的 URL。 現在,此方法將返回檔案系統表單的 Url + + cdvfile://localhost/persistent/path/to/file + + +它可以用於唯一地標識該檔。 + +## 錯誤代碼及其含義的清單中 + +當拋出一個錯誤時,將使用以下代碼之一。 + +| 代碼 | 恒 | +| --:|:----------------------------- | +| 1 | `NOT_FOUND_ERR` | +| 2 | `SECURITY_ERR` | +| 3 | `ABORT_ERR` | +| 4 | `NOT_READABLE_ERR` | +| 5 | `ENCODING_ERR` | +| 6 | `NO_MODIFICATION_ALLOWED_ERR` | +| 7 | `INVALID_STATE_ERR` | +| 8 | `SYNTAX_ERR` | +| 9 | `INVALID_MODIFICATION_ERR` | +| 10 | `QUOTA_EXCEEDED_ERR` | +| 11 | `TYPE_MISMATCH_ERR` | +| 12 | `PATH_EXISTS_ERR` | + +## 配置外掛程式 (可選) + +可用的檔案系統的一整套可以配置每個平臺。IOS 和安卓系統認識到 在 `config.xml` 名稱要安裝的檔案系統中的標記。預設情況下,啟用所有檔案系統的根。 + + + + + +### Android 系統 + + * `files`: 該應用程式的內部檔存儲目錄 + * `files-external`: 應用程式的外部檔存儲目錄 + * `sdcard`: 全球外部檔存儲目錄 (如果安裝了一個,這是 SD 卡的根目錄)。 你必須具有 `android.permission.WRITE_EXTERNAL_STORAGE` 許可權,用這個。 + * `cache`: 應用程式的內部緩存目錄 + * `cache-external`: 應用程式的外部快取記憶體目錄 + * `root`: 整個設備的檔案系統 + +安卓系統還支援特殊的檔命名為"檔",表示"/ 檔 /""檔"的檔案系統中的子目錄。 + +### iOS + + * `library`: 應用程式的庫目錄 + * `documents`: 應用程式的檔目錄 + * `cache`: 應用程式的緩存目錄 + * `bundle`: 應用程式的包 ;應用程式本身 (唯讀) 的磁片上的位置 + * `root`: 整個設備的檔案系統 + +預設情況下,圖書館和檔目錄可以同步到 iCloud。 您也可以要求兩個額外的檔案系統、 `library-nosync` 和 `documents-nosync`,代表一個特殊的非同步目錄內 `/Library` 或 `/Documents` 的檔案系統。 \ No newline at end of file diff --git a/plugins/cordova-plugin-file/doc/zh/index.md b/plugins/cordova-plugin-file/doc/zh/index.md new file mode 100644 index 0000000..6eec44d --- /dev/null +++ b/plugins/cordova-plugin-file/doc/zh/index.md @@ -0,0 +1,343 @@ + + +# cordova-plugin-file + +這個外掛程式實現檔 API 允許對檔駐留在該設備上的讀/寫訪問。 + +這個外掛程式基於幾個規格,包括: HTML5 檔 API [HTTP://www.w3.org/TR/FileAPI/][1] + + [1]: http://www.w3.org/TR/FileAPI/ + +(現已解散) 目錄和系統擴展最新: [HTTP://www.w3.org/TR/2012/WD-file-system-api-20120417/][2]雖然大部分的外掛程式代碼寫時較早的規格是當前: [HTTP://www.w3.org/TR/2011/WD-file-system-api-20110419/][3] + + [2]: http://www.w3.org/TR/2012/WD-file-system-api-20120417/ + [3]: http://www.w3.org/TR/2011/WD-file-system-api-20110419/ + +它還實現 FileWriter 規格: [HTTP://dev.w3.org/2009/dap/file-system/file-writer.html][4] + + [4]: http://dev.w3.org/2009/dap/file-system/file-writer.html + +用法,請參閱對 HTML5 的岩石優秀[檔案系統文章。][5] + + [5]: http://www.html5rocks.com/en/tutorials/file/filesystem/ + +其他存儲選項的概述,請參閱科爾多瓦的[存儲指南][6]. + + [6]: http://cordova.apache.org/docs/en/edge/cordova_storage_storage.md.html + +這個外掛程式定義全球 `cordova.file` 物件。 + +雖然在全球範圍內,它不可用直到 `deviceready` 事件之後。 + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(cordova.file); + } + + +## 安裝 + + cordova plugin add cordova-plugin-file + + +## 支援的平臺 + +* 亞馬遜火 OS +* Android 系統 +* 黑莓 10 +* 火狐瀏覽器的作業系統 +* iOS +* Windows Phone 7 和 8 * +* Windows 8 * +* 瀏覽器 + +* *這些平臺不支援 `FileReader.readAsArrayBuffer` 或 `FileWriter.write(blob)`.* + +## 存儲檔的位置 + +截至 v1.2.0,提供重要的檔案系統目錄的 Url。 每個 URL 位於表單 *file:///path/to/spot/*,和可以轉換為使用 `window.resolveLocalFileSystemURL()` 的 `DirectoryEntry`. + +* `cordova.file.applicationDirectory`-唯讀目錄在哪裡安裝的應用程式。(*iOS*、*安卓*、*黑莓 10*) + +* `cordova.file.applicationStorageDirectory`-根目錄下的應用程式的沙箱 ;在 iOS 上此位置是唯讀 (但特定的子目錄 [像 `/Documents` ] 都是讀寫)。 中包含的所有資料都是私有的應用程式。 ( *iOS*、*安卓*、*黑莓 10*) + +* `cordova.file.dataDirectory`資料持久性和私有資料存儲在內部記憶體使用的應用程式的沙箱內 (在安卓系統,如果你需要使用外部儲存體,使用 `.externalDataDirectory` )。 在 iOS,此目錄不與 iCloud 同步 (使用 `.syncedDataDirectory` )。 (*iOS*、*安卓*、*黑莓 10*) + +* `cordova.file.cacheDirectory`-緩存的資料檔案或您的應用程式重新可以輕鬆地創建的任何檔的目錄。 作業系統可能會刪除這些檔,該設備在存儲上運行低時,然而,應用程式不應依賴的作業系統,請刪除檔在這裡。 (*iOS*、*安卓*、*黑莓 10*) + +* `cordova.file.externalApplicationStorageDirectory`-應用程式外部存儲上的空間。(*安卓*) + +* `cordova.file.externalDataDirectory`-放在外部存儲特定于應用程式的資料檔案的位置。(*安卓*) + +* `cordova.file.externalCacheDirectory`-在外部存儲應用程式緩存。(*安卓*) + +* `cordova.file.externalRootDirectory`-外部存儲 (SD 卡) 的根。(*安卓*、*黑莓 10*) + +* `cordova.file.tempDirectory`-OS 可以清除時的空目錄會。 不依賴于 OS,以清除此目錄 ;您的應用程式,應總是移除作為適用的檔。 (*iOS*) + +* `cordova.file.syncedDataDirectory`-保存應同步 (例如到 iCloud) 的特定于應用程式的檔。(*iOS*) + +* `cordova.file.documentsDirectory`-檔私有的應用程式,但這是對其他應用程式 (例如 Office 檔) 有意義。(*iOS*) + +* `cordova.file.sharedDirectory`-對所有應用程式 (*黑莓 10*全域可用的檔) + +## 檔案系統佈局 + +雖然技術上實現的細節,它可以是很有必要瞭解如何 `cordova.file.*` 屬性對應到實體路徑在實際設備上。 + +### iOS 檔案系統佈局 + +| 設備路徑 | `cordova.file.*` | `iosExtraFileSystems` | r/w 嗎? | 持續性嗎? | OS 清除 | 同步 | 私人 | +|:------------------------------- |:--------------------------- |:--------------------- |:------:|:------:|:----------:|:---:|:--:| +| `/ 無功/移動/應用程式/< UUID > /` | applicationStorageDirectory | - | r | 不適用 | 不適用 | 不適用 | 是啊 | +|    `appname.app/` | applicationDirectory | 束 | r | 不適用 | 不適用 | 不適用 | 是啊 | +|       `www/` | - | - | r | 不適用 | 不適用 | 不適用 | 是啊 | +|    `Documents/` | documentsDirectory | 檔 | r/w | 是啊 | 無 | 是啊 | 是啊 | +|       `NoCloud/` | - | 檔 nosync | r/w | 是啊 | 無 | 無 | 是啊 | +|    `Library` | - | 圖書館 | r/w | 是啊 | 無 | 是嗎? | 是啊 | +|       `NoCloud/` | dataDirectory | 圖書館 nosync | r/w | 是啊 | 無 | 無 | 是啊 | +|       `Cloud/` | syncedDataDirectory | - | r/w | 是啊 | 無 | 是啊 | 是啊 | +|       `Caches/` | cacheDirectory | 快取記憶體 | r/w | 是啊 * | 是的 * * *| | 無 | 是啊 | +|    `tmp/` | tempDirectory | - | r/w | 沒有 * * | 是的 * * *| | 無 | 是啊 | + +* 檔堅持跨應用程式重新開機和升級,但是每當作業系統的欲望,可以清除此目錄。您的應用程式應該能夠重新創建任何內容可能會被刪除。 + +* * 檔可能會持續整個應用程式重新開機,但不要依賴此行為。 不保證檔在更新之間持續存在。 您的應用程式時適用,是應該刪除此目錄的檔,因為作業系統並不能保證何時 (或即使) 中刪除這些檔。 + +* * *| 作業系統可能會清除此目錄的內容,每當它感覺它是必要的但不要依賴于此。 你應該清除此目錄為適合您的應用程式。 + +### Android 的檔案系統佈局 + +| 設備路徑 | `cordova.file.*` | `AndroidExtraFileSystems` | r/w 嗎? | 持續性嗎? | OS 清除 | 私人 | +|:--------------------------------- |:----------------------------------- |:------------------------- |:------:|:-----:|:------:|:--:| +| `file:///android_asset/` | applicationDirectory | | r | 不適用 | 不適用 | 是啊 | +| `/ 資料資料/< 應用程式 id > /` | applicationStorageDirectory | - | r/w | 不適用 | 不適用 | 是啊 | +|    `cache` | cacheDirectory | 快取記憶體 | r/w | 是啊 | 是啊 * | 是啊 | +|    `files` | dataDirectory | 檔 | r/w | 是啊 | 無 | 是啊 | +|       `Documents` | | 檔 | r/w | 是啊 | 無 | 是啊 | +| `< sd 卡 > /` | externalRootDirectory | sd 卡 | r/w | 是啊 | 無 | 無 | +|    `Android/data//` | externalApplicationStorageDirectory | - | r/w | 是啊 | 無 | 無 | +|       `cache` | externalCacheDirectry | 外部快取記憶體 | r/w | 是啊 | 沒有 * * | 無 | +|       `files` | externalDataDirectory | 外部檔 | r/w | 是啊 | 無 | 無 | + +* 的作業系統可能會定期清除此目錄中,但不是依賴于這種行為。 清除此為適合您的應用程式的目錄的內容。 使用者應手動清除緩存,將刪除此目錄的內容。 + +* * 作業系統不會自動清除此目錄你是負責管理自己的內容。 使用者應手動清除緩存,目錄中的內容將被刪除。 + +**注**: 如果外部存儲無法裝入,`cordova.file.external*` 屬性為 `空`. + +### 黑莓 10 檔案系統佈局 + +| 設備路徑 | `cordova.file.*` | r/w 嗎? | 持續性嗎? | OS 清除 | 私人 | +|:---------------------------------------------------- |:--------------------------- |:------:|:-----:|:-----:|:--:| +| `file:///accounts/1000/appdata/ < 應用程式 id > /` | applicationStorageDirectory | r | 不適用 | 不適用 | 是啊 | +|    `app/native` | applicationDirectory | r | 不適用 | 不適用 | 是啊 | +|    `data/webviews/webfs/temporary/local__0` | cacheDirectory | r/w | 無 | 是啊 | 是啊 | +|    `data/webviews/webfs/persistent/local__0` | dataDirectory | r/w | 是啊 | 無 | 是啊 | +| `file:///accounts/1000/removable/sdcard` | externalRemovableDirectory | r/w | 是啊 | 無 | 無 | +| `file:///accounts/1000/shared` | sharedDirectory | r/w | 是啊 | 無 | 無 | + +*注意*: 當應用程式部署工作週邊時,所有路徑都是相對於 /accounts/1000-enterprise。 + +## Android 的怪癖 + +### Android 的持久性存儲位置 + +有很多有效的位置來存儲持久性檔在 Android 設備上。 請參閱 [此頁面][7] 的各種可能性進行廣泛討論。 + + [7]: http://developer.android.com/guide/topics/data/data-storage.html + +以前版本的外掛程式會選擇在啟動時,基於該設備是否聲稱 SD 卡 (或等效存儲分區) 展開,臨時和永久檔的位置。 如果被掛載 SD 卡,或一個大的內部存儲分區可用 (如 nexus 系列設備上) 然後持久性檔將存儲在該空間的根目錄中。 這意味著所有的科爾多瓦應用程式可以看到所有可用的檔在卡片上。 + +如果 SD 卡不是可用的那麼以前的版本中將存儲資料下的 `/data/data/`,其中隔離應用程式從彼此,但仍可能導致使用者之間共用的資料。 + +現在可以選擇是否將檔存儲在內部檔的存儲位置,或使用以前的邏輯,與您的應用程式的 `config.xml` 檔中的偏好。 要執行此操作,請將以下兩行之一添加到 `config.xml`: + + + + + + +如果這條線,沒有檔外掛程式將使用 `Compatibility` 作為預設值。如果首選項標記存在,並不是這些值之一,應用程式將無法啟動。 + +如果您的應用程式以前已被運到使用者,使用較舊的 (預 1.0) 版本的這個外掛程式,並具有持久性的檔,系統中存儲的檔,然後您應該設置 `Compatibility` 偏好。 切換到"Internal"的位置,將意味著現有使用者升級他們的應用程式可能無法訪問他們以前存儲的檔,具體取決於他們的設備。 + +如果您的應用程式是新的或以前從未有持久性的檔案系統中存儲檔,那麼通常建議使用 `Internal` 設置。 + +## iOS 的怪癖 + +* `cordova.file.applicationStorageDirectory`是唯讀的 ;試圖存儲內的根目錄中的檔將會失敗。 使用的另一個 `cordova.file.*` 為 iOS 定義的屬性 (只有 `applicationDirectory` 和 `applicationStorageDirectory` 都是唯讀)。 +* `FileReader.readAsText(blob, encoding)` + * `encoding`參數不受支援,而 utf-8 編碼總是效果。 + +### iOS 的持久性存儲位置 + +有兩個有效的位置來存儲持久性在 iOS 設備上的檔: 檔目錄和圖書館目錄。 以前版本的外掛程式永遠只能將持久性檔存儲在文檔目錄中。 這已經使所有應用程式檔可見在 iTunes,往往是無意為之,尤其是對於處理大量小檔的應用程式中,而不是生產供出口,該目錄的既定的目標是證件齊全的副作用。 + +現在可以選擇是否將檔存儲在檔或庫目錄,與您的應用程式的 `config.xml` 檔中的偏好。 要執行此操作,請將以下兩行之一添加到 `config.xml`: + + + + + + +如果這條線,沒有檔外掛程式將使用 `Compatibility` 作為預設值。如果首選項標記存在,並不是這些值之一,應用程式將無法啟動。 + +如果您的應用程式以前已被運到使用者,使用較舊的 (預 1.0) 版本的這個外掛程式,並具有持久性的檔,系統中存儲的檔,然後您應該設置 `Compatibility` 偏好。 切換到 `Library` 的位置,將意味著現有使用者升級他們的應用程式將無法訪問他們以前存儲的檔。 + +如果您的應用程式是新的或以前從未有持久性的檔案系統中存儲檔,那麼通常建議使用 `Internal` 設置。 + +## 火狐瀏覽器作業系統的怪癖 + +檔案系統 API 本身不支援火狐瀏覽器的作業系統,作為墊片在 indexedDB 上實現的。 + +* 不會失敗時刪除非空的目錄 +* 不支援中繼資料的目錄 +* 方法 `copyTo` 和 `moveTo` 不支援目錄 + +支援以下資料路徑: * `applicationDirectory`-使用 `xhr` 獲取與應用程式打包的本地檔。 `dataDirectory`-用於持久性的特定于應用程式的資料檔案。 `cacheDirectory`-生存應重新開機應用程式的快取檔案 (應用程式不應依賴作業系統來刪除檔在這裡)。 + +## 瀏覽器的怪癖 + +### 常見的怪癖和備註 + +* 每個瀏覽器使用其自己的沙箱檔案系統。IE 和火狐瀏覽器使用 IndexedDB 作為一個基地。所有瀏覽器都使用正斜杠作為路徑中的目錄分隔符號。 +* 目錄條目不得不先後創建。 例如,調用 `fs.root.getDirectory (' dir1/dir2 ',{create:true},successCallback,errorCallback)`,如果不存在 dir1 將失敗。 +* 外掛程式將請求使用者許可權,以便在應用程式初次開機使用持久性存儲。 +* 外掛程式支援 `cdvfile://localhost` (本地資源) 只。通過 `cdvfile` 不支援外部資源即. +* 該外掛程式不遵循 ["檔案系統 API 8.3 命名限制"][8]. +* Blob 和檔 ' `close` 功能不受支援。 +* `FileSaver` 和 `BlobBuilder` 不支援這個外掛程式,沒有存根 (stub)。 +* 該外掛程式不支援 `requestAllFileSystems`。這個功能也是缺少規範中。 +* 在目錄中的條目將不會被刪除,如果您使用 `create: true` 標誌為現有目錄。 +* 不支援通過建構函式創建的檔。你應該使用 entry.file 方法。 +* 每個瀏覽器使用它自己的形式為 blob 的 URL 引用。 +* 支援 `readAsDataURL` 功能,但在 Chrome 中的媒體類型取決於輸入副檔名,在 IE 中的媒體類型都始終空著 (這是 `純文字` 按照說明書一樣),在 Firefox 中的媒體類型始終是 `應用程式/八位位元組流`。 例如,如果內容是 `abcdefg` 然後火狐瀏覽器返回 `資料: 應用程式 / 八位位元組流 ; base64,YWJjZGVmZw = =`,即返回 `資料: ; base64,YWJjZGVmZw = =`,鉻返回 `資料: < 媒體類型根據擴展條目名稱 > ; base64,YWJjZGVmZw = =`. +* 在表單 `file:///persistent/path/to/entry` 火狐瀏覽器 IE),`toInternalURL` 返回的路徑。 鉻在表單 `cdvfile://localhost/persistent/file` 返回的路徑. + + [8]: http://www.w3.org/TR/2011/WD-file-system-api-20110419/#naming-restrictions + +### 鉻的怪癖 + +* 設備準備好事件之後,chrome 檔案系統並不能立即準備。作為一種變通方法,您可以訂閱到 `filePluginIsReady` 事件。示例: + + javascript + window.addEventListener('filePluginIsReady', function(){ console.log('File plugin is ready');}, false); + + +你可以使用 `window.isFilePluginReadyRaised` 函數來檢查是否已經引發了事件。 -window.requestFileSystem 臨時和永久性檔案系統配額並不局限于鉻。 為增加中鉻的持久性存儲,您需要調用 `window.initPersistentFileSystem` 方法。 預設情況下,持久性存儲配額為 5 MB。 鉻需要 `— — 允許--訪問-從-檔` 通過 `file:///` 協定運行參數對 API 的支援。 -如果您使用標誌,將不更改 `檔` 物件 `{create:true}` 現有 `條目` 的時候。 -事件 `可取消` 屬性設置為 true 在 Chrome 中。 這是違反了 [規範][4]。 -中鉻的 `toURL` 函數返回 `檔案系統:`-首碼路徑具體取決於應用程式主機。 例如,`filesystem:file:///persistent/somefile.txt`,`filesystem:HTTP://localhost:8080/persistent/somefile.txt`。 -`toURL` 函數結果不包含尾部反斜線在目錄條目的情況下。 鉻雖然正確解析目錄帶斜杠落後的 url。 -`resolveLocalFileSystemURL` 方法需要入站的 `url` 必須具有 `檔案系統` 首碼。 例如,`resolveLocalFileSystemURL` 的 `url` 參數應在表單 `filesystem:file:///persistent/somefile.txt` 而不是表單 `file:///persistent/somefile.txt` 在安卓系統。 -不推薦使用 `toNativeURL` 函數不受支援,並且沒有存根 (stub)。 -`setMetadata` 功能是沒有說出的規格,並且不支援。 -INVALID_MODIFICATION_ERR (代碼: 9) 而不是引發 SYNTAX_ERR(code: 8) 上請求一個不存在的檔案系統。 -INVALID_MODIFICATION_ERR (代碼: 9) 而不是引發 PATH_EXISTS_ERR(code: 12) 上嘗試專門創建一個檔或目錄,它已經存在。 -INVALID_MODIFICATION_ERR (代碼: 9) 而不是引發 NO_MODIFICATION_ALLOWED_ERR(code: 6) 在試圖調用 removeRecursively 的根檔案系統上。 -INVALID_MODIFICATION_ERR (代碼: 9) 而不是引發 NOT_FOUND_ERR(code: 1) 試到 moveTo 目錄不存在。 + +### 基於 IndexedDB 的 impl 怪癖 (Firefox 和 IE) + +* `.` 和 `.` 不受支援。 +* IE 不支援 `file:///`-模式 ;只有託管的模式是支援 (HTTP://localhost:xxxx)。 +* 火狐瀏覽器的檔案系統大小不是有限,但每個 50 MB 擴展會要求使用者的許可權。 IE10 允許達 10 mb 的 AppCache 和 IndexedDB 檔案系統的實現中使用而不會提示,一旦你達到這一水準你會詢問您是否允許它增加到每個網站的 250 mb 的最大合併。 所以 `requestFileSystem` 函數的 `大小` 參數並不影響檔案系統相容 Firefox 和 IE。 +* `readAsBinaryString` 函數在規範中沒有注明不支援在 IE 中和沒有存根 (stub)。 +* `file.type` 始終為 null。 +* 您不應創建條目使用已刪除的目錄實例回檔結果。否則,你會得到一個 '掛條目'。 +* 您可以讀取一個檔,其中只是寫之前你需要獲得的此檔的新實例。 +* `setMetadata` 函數,在規範中沒有注明支援 `modificationTime` 欄位的更改。 +* `copyTo` 和 `moveTo` 函數不支援目錄。 +* 不支援目錄的中繼資料。 +* 兩個 Entry.remove 和 directoryEntry.removeRecursively 不失敗時刪除非空的目錄-相反與內容一起清理目錄被刪除。 +* 不支援 `abort` 和 `truncate` 函數。 +* 進度事件不會觸發。例如,將不執行此處理程式: + + javascript + writer.onprogress = function() { /*commands*/ }; + + +## 升級筆記 + +在這個外掛程式 v1.0.0,`FileEntry` 和 `DirectoryEntry` 的結構已經改變,以更加一致的已發表說明書。 + +以前 (pre-1.0.0) 版本的外掛程式中 `輸入` 物件的 `完整路徑` 屬性存放裝置固定檔案位置。這些路徑通常會看起來像 + + /var/mobile/Applications//Documents/path/to/file (iOS) + /storage/emulated/0/path/to/file (Android) + + +這些路徑還返回的 `Entry` 物件的 `toURL()` 方法。 + +與 v1.0.0,`完整路徑` 屬性是到檔中,*相對於 HTML 檔案系統的根目錄* 的路徑。 因此,上述路徑會現在都由一個 `FileEntry` 物件的 `完整路徑`, + + /path/to/file + + +如果您的應用程式與設備-絕對路徑,並且您以前檢索到這些路徑通過 `條目` 物件的 `完整路徑` 屬性,然後您應該更新您的代碼以改用 `entry.toURL()`。 + +為向後相容性,`resolveLocalFileSystemURL()` 方法將接受一個設備-絕對路徑,並將返回相應的 `條目` 物件,只要在 `臨時` 或 `永久性` 的檔案系統內的檔是否存在。 + +這尤其是一直與檔案傳輸外掛程式,以前使用設備絕對路徑的問題 (和仍然可以接受他們)。 已更新它能夠正常運行與檔案系統的 Url,所以用 `entry.toURL()` 替換 `entry.fullPath` 應解決任何問題,得到該外掛程式來處理設備上的檔。 + +在 v1.1.0 `toURL()` 的傳回值被更改 (見 [CB-6394] (HTTPs://issues.apache.org/jira/browse/CB-6394)) 為返回絕對 file:// URL。 只要有可能。 確保 'cdvfile:' — — 你現在可以用 `toInternalURL()` 的 URL。 現在,此方法將返回檔案系統表單的 Url + + cdvfile://localhost/persistent/path/to/file + + +它可以用於唯一地標識該檔。 + +## 錯誤代碼及其含義的清單中 + +當拋出一個錯誤時,將使用以下代碼之一。 + +| 代碼 | 恒 | +| --:|:----------------------------- | +| 1 | `NOT_FOUND_ERR` | +| 2 | `SECURITY_ERR` | +| 3 | `ABORT_ERR` | +| 4 | `NOT_READABLE_ERR` | +| 5 | `ENCODING_ERR` | +| 6 | `NO_MODIFICATION_ALLOWED_ERR` | +| 7 | `INVALID_STATE_ERR` | +| 8 | `SYNTAX_ERR` | +| 9 | `INVALID_MODIFICATION_ERR` | +| 10 | `QUOTA_EXCEEDED_ERR` | +| 11 | `TYPE_MISMATCH_ERR` | +| 12 | `PATH_EXISTS_ERR` | + +## 配置外掛程式 (可選) + +可用的檔案系統的一整套可以配置每個平臺。IOS 和安卓系統認識到 在 `config.xml` 名稱要安裝的檔案系統中的標記。預設情況下,啟用所有檔案系統的根。 + + + + + +### Android 系統 + +* `files`: 該應用程式的內部檔存儲目錄 +* `files-external`: 應用程式的外部檔存儲目錄 +* `sdcard`: 全球外部檔存儲目錄 (如果安裝了一個,這是 SD 卡的根目錄)。 你必須具有 `android.permission.WRITE_EXTERNAL_STORAGE` 許可權,用這個。 +* `cache`: 應用程式的內部緩存目錄 +* `cache-external`: 應用程式的外部快取記憶體目錄 +* `root`: 整個設備的檔案系統 + +安卓系統還支援特殊的檔命名為"檔",表示"/ 檔 /""檔"的檔案系統中的子目錄。 + +### iOS + +* `library`: 應用程式的庫目錄 +* `documents`: 應用程式的檔目錄 +* `cache`: 應用程式的緩存目錄 +* `bundle`: 應用程式的包 ;應用程式本身 (唯讀) 的磁片上的位置 +* `root`: 整個設備的檔案系統 + +預設情況下,圖書館和檔目錄可以同步到 iCloud。 您也可以要求兩個額外的檔案系統、 `library-nosync` 和 `documents-nosync`,代表一個特殊的非同步目錄內 `/Library` 或 `/Documents` 的檔案系統。 diff --git a/plugins/cordova-plugin-file/doc/zh/plugins.md b/plugins/cordova-plugin-file/doc/zh/plugins.md new file mode 100644 index 0000000..c9a2d61 --- /dev/null +++ b/plugins/cordova-plugin-file/doc/zh/plugins.md @@ -0,0 +1,101 @@ + + +# 外掛程式開發人員注意事項 + +這些筆記主要用於 Android 和 iOS 開發者想要編寫外掛程式的介面與使用檔外掛程式的檔案系統。 + +## 工作與科爾多瓦檔案系統 Url + +自從版本 1.0.0,這個外掛程式一直使用 Url 與 `cdvfile` 大橋,計畫為所有通信,而不是揭露 JavaScript 的原始設備檔案系統路徑。 + +在 JavaScript 方面,這意味著 FileEntry 和 DirectoryEntry 的物件有一個完整路徑屬性是相對於 HTML 檔案系統的根目錄。 如果你的外掛程式的 JavaScript API 接受一個 FileEntry 或 DirectoryEntry 的物件,你應該打電話給 `.toURL()` 對該物件之前將它從橋上傳遞給本機代碼。 + +### 轉換 cdvfile: / / fileystem 路徑的 Url + +需要寫入到檔案系統的外掛程式可能想要將接收的檔案系統 URL 轉換為實際的檔案系統位置。有做這,根據本機平臺的多種方式。 + +很重要的是要記住,並不是所有 `cdvfile://` Url 是可映射到設備上的實際檔。 某些 Url 可以指在設備上沒有代表的檔,或甚至可以引用遠端資源的資產。 由於這些可能性,外掛程式應始終測試是否回來時試圖將 Url 轉換成路徑得到有意義的結果。 + +#### 安卓系統 + +在 android 系統,最簡單的方法來轉換 `cdvfile://` 檔案系統路徑的 URL 是使用 `org.apache.cordova.CordovaResourceApi` 。 `CordovaResourceApi`有幾種方法,可處理 `cdvfile://` 網址: + + web 視圖是成員的外掛程式類 CordovaResourceApi resourceApi = webView.getResourceApi(); + + 獲取表示此檔在設備上,file:/// URL / / 或 URL 相同變的如果它不能映射到檔 Uri fileURL = resourceApi.remapUri(Uri.parse(cdvfileURL)); + + +它也是可以直接使用檔外掛程式: + + 導入 org.apache.cordova.file.FileUtils; + 導入 org.apache.cordova.file.FileSystem; + 導入 java.net.MalformedURLException; + + 得到檔外掛程式外掛程式管理器從 FileUtils filePlugin = (FileUtils)webView.pluginManager.getPlugin("File"); + + 給定 URL,得到的路徑,因為它嘗試 {字串路徑 = filePlugin.filesystemPathForURL(cdvfileURL);} 趕上 (MalformedURLException e) {/ / 檔案系統 url 不承認} + + +要轉換到的路徑從 `cdvfile://` URL: + + 導入 org.apache.cordova.file.LocalFilesystemURL; + + 獲取設備的路徑,一個 LocalFilesystemURL 物件 / / 或如果它不能表示為 cdvfile 的 URL,則為 null。 + LocalFilesystemURL url = filePlugin.filesystemURLforLocalPath(path); + 得到的字串表示形式的 URL 物件字串 cdvfileURL = url.toString(); + + +如果你的外掛程式創建一個檔,並且您想要為它返回一個 FileEntry 物件,使用該檔的外掛程式: + + 返回一個 JSON 結構適合於回到 JavaScript,/ / 或如果此檔不是可表示為 cdvfile 的 URL,則為 null。 + JSONObject 條目 = filePlugin.getEntryForFile(file); + + +#### iOS + +科爾多瓦在 iOS 上的不使用相同 `CordovaResourceApi` 作為 android 系統的概念。在 iOS,應使用檔外掛程式 Url 和檔案系統路徑之間進行轉換。 + + 獲取一個物件,CDVFilesystem URL 從 url 字串 CDVFilesystemURL * = [CDVFilesystemURL fileSystemURLWithString:cdvfileURL]; + 獲取路徑 URL 物件,或為零,如果它不能映射到檔 NSString * 路徑 = [filePlugin filesystemPathForURL:url]; + + + CDVFilesystem URL 物件獲取設備的路徑,或 / / 為零,如果它不能表示為 cdvfile 的 URL。 + CDVFilesystemURL * url = [filePlugin fileSystemURLforLocalPath:path]; + 得到的字串表示形式的 URL 物件 NSString * cdvfileURL = [url absoluteString]; + + +如果你的外掛程式創建一個檔,並且您想要為它返回一個 FileEntry 物件,使用該檔的外掛程式: + + CDVFilesystem URL 物件獲取設備的路徑,或 / / 為零,如果它不能表示為 cdvfile 的 URL。 + CDVFilesystemURL * url = [filePlugin fileSystemURLforLocalPath:path]; + 得到一個結構來返回進入 JavaScript NSDictionary * = [filePlugin makeEntryForLocalURL:url] + + +#### JavaScript + +在 JavaScript 中,得到 `cdvfile://` URL 從 FileEntry 或 DirectoryEntry 的物件,只需調用 `.toURL()` 對它: + + var cdvfileURL = entry.toURL(); + + +在外掛程式回應處理常式,將從返回的 FileEntry 結構轉換為實際的條目物件,處理常式代碼應該導入檔外掛程式和創建新的物件: + + 創建適當的條目物件 var 條目; + 如果 (entryStruct.isDirectory) {條目 = 新目錄 (entryStruct.name,entryStruct.fullPath,新 FileSystem(entryStruct.filesystemName));} 其他 {條目 = 新的 FileEntry (entryStruct.name,entryStruct.fullPath,新 FileSystem(entryStruct.filesystemName));} \ No newline at end of file diff --git a/plugins/cordova-plugin-file/package.json b/plugins/cordova-plugin-file/package.json new file mode 100644 index 0000000..46e6384 --- /dev/null +++ b/plugins/cordova-plugin-file/package.json @@ -0,0 +1,58 @@ +{ + "name": "cordova-plugin-file", + "version": "4.3.3", + "description": "Cordova File Plugin", + "types": "./types/index.d.ts", + "cordova": { + "id": "cordova-plugin-file", + "platforms": [ + "android", + "amazon-fireos", + "ubuntu", + "ios", + "osx", + "wp7", + "wp8", + "blackberry10", + "windows8", + "windows", + "firefoxos" + ] + }, + "repository": { + "type": "git", + "url": "https://github.com/apache/cordova-plugin-file" + }, + "keywords": [ + "cordova", + "file", + "ecosystem:cordova", + "cordova-android", + "cordova-amazon-fireos", + "cordova-ubuntu", + "cordova-ios", + "cordova-osx", + "cordova-wp7", + "cordova-wp8", + "cordova-blackberry10", + "cordova-windows8", + "cordova-windows", + "cordova-firefoxos" + ], + "scripts": { + "test": "npm run jshint", + "jshint": "node node_modules/jshint/bin/jshint www && node node_modules/jshint/bin/jshint src && node node_modules/jshint/bin/jshint tests" + }, + "author": "Apache Software Foundation", + "license": "Apache-2.0", + "engines": { + "cordovaDependencies": { + "5.0.0": { + "cordova": ">100" + } + } + }, + "devDependencies": { + "jshint": "^2.6.0" + } +} diff --git a/plugins/cordova-plugin-file/plugin.xml b/plugins/cordova-plugin-file/plugin.xml new file mode 100644 index 0000000..d1662ce --- /dev/null +++ b/plugins/cordova-plugin-file/plugin.xml @@ -0,0 +1,424 @@ + + + + + File + Cordova File Plugin + Apache 2.0 + cordova,file + https://git-wip-us.apache.org/repos/asf/cordova-plugin-file.git + https://issues.apache.org/jira/browse/CB/component/12320651 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +The Android Persistent storage location now defaults to "Internal". Please check this plugin's README to see if your application needs any changes in its config.xml. + +If this is a new application no changes are required. + +If this is an update to an existing application that did not specify an "AndroidPersistentFileLocation" you may need to add: + + "<preference name="AndroidPersistentFileLocation" value="Compatibility" />" + +to config.xml in order for the application to find previously stored files. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/cordova-plugin-file/src/android/AssetFilesystem.java b/plugins/cordova-plugin-file/src/android/AssetFilesystem.java new file mode 100644 index 0000000..b035c40 --- /dev/null +++ b/plugins/cordova-plugin-file/src/android/AssetFilesystem.java @@ -0,0 +1,294 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. + */ +package org.apache.cordova.file; + +import android.content.res.AssetManager; +import android.net.Uri; + +import org.apache.cordova.CordovaResourceApi; +import org.apache.cordova.LOG; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.util.HashMap; +import java.util.Map; + +public class AssetFilesystem extends Filesystem { + + private final AssetManager assetManager; + + // A custom gradle hook creates the cdvasset.manifest file, which speeds up asset listing a tonne. + // See: http://stackoverflow.com/questions/16911558/android-assetmanager-list-incredibly-slow + private static Object listCacheLock = new Object(); + private static boolean listCacheFromFile; + private static Map listCache; + private static Map lengthCache; + + private static final String LOG_TAG = "AssetFilesystem"; + + private void lazyInitCaches() { + synchronized (listCacheLock) { + if (listCache == null) { + ObjectInputStream ois = null; + try { + ois = new ObjectInputStream(assetManager.open("cdvasset.manifest")); + listCache = (Map) ois.readObject(); + lengthCache = (Map) ois.readObject(); + listCacheFromFile = true; + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + // Asset manifest won't exist if the gradle hook isn't set up correctly. + } finally { + if (ois != null) { + try { + ois.close(); + } catch (IOException e) { + LOG.d(LOG_TAG, e.getLocalizedMessage()); + } + } + } + if (listCache == null) { + LOG.w("AssetFilesystem", "Asset manifest not found. Recursive copies and directory listing will be slow."); + listCache = new HashMap(); + } + } + } + } + + private String[] listAssets(String assetPath) throws IOException { + if (assetPath.startsWith("/")) { + assetPath = assetPath.substring(1); + } + if (assetPath.endsWith("/")) { + assetPath = assetPath.substring(0, assetPath.length() - 1); + } + lazyInitCaches(); + String[] ret = listCache.get(assetPath); + if (ret == null) { + if (listCacheFromFile) { + ret = new String[0]; + } else { + ret = assetManager.list(assetPath); + listCache.put(assetPath, ret); + } + } + return ret; + } + + private long getAssetSize(String assetPath) throws FileNotFoundException { + if (assetPath.startsWith("/")) { + assetPath = assetPath.substring(1); + } + lazyInitCaches(); + if (lengthCache != null) { + Long ret = lengthCache.get(assetPath); + if (ret == null) { + throw new FileNotFoundException("Asset not found: " + assetPath); + } + return ret; + } + CordovaResourceApi.OpenForReadResult offr = null; + try { + offr = resourceApi.openForRead(nativeUriForFullPath(assetPath)); + long length = offr.length; + if (length < 0) { + // available() doesn't always yield the file size, but for assets it does. + length = offr.inputStream.available(); + } + return length; + } catch (IOException e) { + FileNotFoundException fnfe = new FileNotFoundException("File not found: " + assetPath); + fnfe.initCause(e); + throw fnfe; + } finally { + if (offr != null) { + try { + offr.inputStream.close(); + } catch (IOException e) { + LOG.d(LOG_TAG, e.getLocalizedMessage()); + } + } + } + } + + public AssetFilesystem(AssetManager assetManager, CordovaResourceApi resourceApi) { + super(Uri.parse("file:///android_asset/"), "assets", resourceApi); + this.assetManager = assetManager; + } + + @Override + public Uri toNativeUri(LocalFilesystemURL inputURL) { + return nativeUriForFullPath(inputURL.path); + } + + @Override + public LocalFilesystemURL toLocalUri(Uri inputURL) { + if (!"file".equals(inputURL.getScheme())) { + return null; + } + File f = new File(inputURL.getPath()); + // Removes and duplicate /s (e.g. file:///a//b/c) + Uri resolvedUri = Uri.fromFile(f); + String rootUriNoTrailingSlash = rootUri.getEncodedPath(); + rootUriNoTrailingSlash = rootUriNoTrailingSlash.substring(0, rootUriNoTrailingSlash.length() - 1); + if (!resolvedUri.getEncodedPath().startsWith(rootUriNoTrailingSlash)) { + return null; + } + String subPath = resolvedUri.getEncodedPath().substring(rootUriNoTrailingSlash.length()); + // Strip leading slash + if (!subPath.isEmpty()) { + subPath = subPath.substring(1); + } + Uri.Builder b = new Uri.Builder() + .scheme(LocalFilesystemURL.FILESYSTEM_PROTOCOL) + .authority("localhost") + .path(name); + if (!subPath.isEmpty()) { + b.appendEncodedPath(subPath); + } + if (isDirectory(subPath) || inputURL.getPath().endsWith("/")) { + // Add trailing / for directories. + b.appendEncodedPath(""); + } + return LocalFilesystemURL.parse(b.build()); + } + + private boolean isDirectory(String assetPath) { + try { + return listAssets(assetPath).length != 0; + } catch (IOException e) { + return false; + } + } + + @Override + public LocalFilesystemURL[] listChildren(LocalFilesystemURL inputURL) throws FileNotFoundException { + String pathNoSlashes = inputURL.path.substring(1); + if (pathNoSlashes.endsWith("/")) { + pathNoSlashes = pathNoSlashes.substring(0, pathNoSlashes.length() - 1); + } + + String[] files; + try { + files = listAssets(pathNoSlashes); + } catch (IOException e) { + FileNotFoundException fnfe = new FileNotFoundException(); + fnfe.initCause(e); + throw fnfe; + } + + LocalFilesystemURL[] entries = new LocalFilesystemURL[files.length]; + for (int i = 0; i < files.length; ++i) { + entries[i] = localUrlforFullPath(new File(inputURL.path, files[i]).getPath()); + } + return entries; + } + + @Override + public JSONObject getFileForLocalURL(LocalFilesystemURL inputURL, + String path, JSONObject options, boolean directory) + throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException { + if (options != null && options.optBoolean("create")) { + throw new UnsupportedOperationException("Assets are read-only"); + } + + // Check whether the supplied path is absolute or relative + if (directory && !path.endsWith("/")) { + path += "/"; + } + + LocalFilesystemURL requestedURL; + if (path.startsWith("/")) { + requestedURL = localUrlforFullPath(normalizePath(path)); + } else { + requestedURL = localUrlforFullPath(normalizePath(inputURL.path + "/" + path)); + } + + // Throws a FileNotFoundException if it doesn't exist. + getFileMetadataForLocalURL(requestedURL); + + boolean isDir = isDirectory(requestedURL.path); + if (directory && !isDir) { + throw new TypeMismatchException("path doesn't exist or is file"); + } else if (!directory && isDir) { + throw new TypeMismatchException("path doesn't exist or is directory"); + } + + // Return the directory + return makeEntryForURL(requestedURL); + } + + @Override + public JSONObject getFileMetadataForLocalURL(LocalFilesystemURL inputURL) throws FileNotFoundException { + JSONObject metadata = new JSONObject(); + long size = inputURL.isDirectory ? 0 : getAssetSize(inputURL.path); + try { + metadata.put("size", size); + metadata.put("type", inputURL.isDirectory ? "text/directory" : resourceApi.getMimeType(toNativeUri(inputURL))); + metadata.put("name", new File(inputURL.path).getName()); + metadata.put("fullPath", inputURL.path); + metadata.put("lastModifiedDate", 0); + } catch (JSONException e) { + return null; + } + return metadata; + } + + @Override + public boolean canRemoveFileAtLocalURL(LocalFilesystemURL inputURL) { + return false; + } + + @Override + long writeToFileAtURL(LocalFilesystemURL inputURL, String data, int offset, boolean isBinary) throws NoModificationAllowedException, IOException { + throw new NoModificationAllowedException("Assets are read-only"); + } + + @Override + long truncateFileAtURL(LocalFilesystemURL inputURL, long size) throws IOException, NoModificationAllowedException { + throw new NoModificationAllowedException("Assets are read-only"); + } + + @Override + String filesystemPathForURL(LocalFilesystemURL url) { + return new File(rootUri.getPath(), url.path).toString(); + } + + @Override + LocalFilesystemURL URLforFilesystemPath(String path) { + return null; + } + + @Override + boolean removeFileAtLocalURL(LocalFilesystemURL inputURL) throws InvalidModificationException, NoModificationAllowedException { + throw new NoModificationAllowedException("Assets are read-only"); + } + + @Override + boolean recursiveRemoveFileAtLocalURL(LocalFilesystemURL inputURL) throws NoModificationAllowedException { + throw new NoModificationAllowedException("Assets are read-only"); + } + +} diff --git a/plugins/cordova-plugin-file/src/android/ContentFilesystem.java b/plugins/cordova-plugin-file/src/android/ContentFilesystem.java new file mode 100644 index 0000000..6b983c0 --- /dev/null +++ b/plugins/cordova-plugin-file/src/android/ContentFilesystem.java @@ -0,0 +1,223 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. + */ +package org.apache.cordova.file; + +import android.content.ContentResolver; +import android.content.Context; +import android.database.Cursor; +import android.net.Uri; +import android.provider.DocumentsContract; +import android.provider.MediaStore; +import android.provider.OpenableColumns; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import org.apache.cordova.CordovaResourceApi; +import org.json.JSONException; +import org.json.JSONObject; + +public class ContentFilesystem extends Filesystem { + + private final Context context; + + public ContentFilesystem(Context context, CordovaResourceApi resourceApi) { + super(Uri.parse("content://"), "content", resourceApi); + this.context = context; + } + + @Override + public Uri toNativeUri(LocalFilesystemURL inputURL) { + String authorityAndPath = inputURL.uri.getEncodedPath().substring(this.name.length() + 2); + if (authorityAndPath.length() < 2) { + return null; + } + String ret = "content://" + authorityAndPath; + String query = inputURL.uri.getEncodedQuery(); + if (query != null) { + ret += '?' + query; + } + String frag = inputURL.uri.getEncodedFragment(); + if (frag != null) { + ret += '#' + frag; + } + return Uri.parse(ret); + } + + @Override + public LocalFilesystemURL toLocalUri(Uri inputURL) { + if (!"content".equals(inputURL.getScheme())) { + return null; + } + String subPath = inputURL.getEncodedPath(); + if (subPath.length() > 0) { + subPath = subPath.substring(1); + } + Uri.Builder b = new Uri.Builder() + .scheme(LocalFilesystemURL.FILESYSTEM_PROTOCOL) + .authority("localhost") + .path(name) + .appendPath(inputURL.getAuthority()); + if (subPath.length() > 0) { + b.appendEncodedPath(subPath); + } + Uri localUri = b.encodedQuery(inputURL.getEncodedQuery()) + .encodedFragment(inputURL.getEncodedFragment()) + .build(); + return LocalFilesystemURL.parse(localUri); + } + + @Override + public JSONObject getFileForLocalURL(LocalFilesystemURL inputURL, + String fileName, JSONObject options, boolean directory) throws IOException, TypeMismatchException, JSONException { + throw new UnsupportedOperationException("getFile() not supported for content:. Use resolveLocalFileSystemURL instead."); + } + + @Override + public boolean removeFileAtLocalURL(LocalFilesystemURL inputURL) + throws NoModificationAllowedException { + Uri contentUri = toNativeUri(inputURL); + try { + context.getContentResolver().delete(contentUri, null, null); + } catch (UnsupportedOperationException t) { + // Was seeing this on the File mobile-spec tests on 4.0.3 x86 emulator. + // The ContentResolver applies only when the file was registered in the + // first case, which is generally only the case with images. + NoModificationAllowedException nmae = new NoModificationAllowedException("Deleting not supported for content uri: " + contentUri); + nmae.initCause(t); + throw nmae; + } + return true; + } + + @Override + public boolean recursiveRemoveFileAtLocalURL(LocalFilesystemURL inputURL) + throws NoModificationAllowedException { + throw new NoModificationAllowedException("Cannot remove content url"); + } + + @Override + public LocalFilesystemURL[] listChildren(LocalFilesystemURL inputURL) throws FileNotFoundException { + throw new UnsupportedOperationException("readEntriesAtLocalURL() not supported for content:. Use resolveLocalFileSystemURL instead."); + } + + @Override + public JSONObject getFileMetadataForLocalURL(LocalFilesystemURL inputURL) throws FileNotFoundException { + long size = -1; + long lastModified = 0; + Uri nativeUri = toNativeUri(inputURL); + String mimeType = resourceApi.getMimeType(nativeUri); + Cursor cursor = openCursorForURL(nativeUri); + try { + if (cursor != null && cursor.moveToFirst()) { + Long sizeForCursor = resourceSizeForCursor(cursor); + if (sizeForCursor != null) { + size = sizeForCursor.longValue(); + } + Long modified = lastModifiedDateForCursor(cursor); + if (modified != null) + lastModified = modified.longValue(); + } else { + // Some content providers don't support cursors at all! + CordovaResourceApi.OpenForReadResult offr = resourceApi.openForRead(nativeUri); + size = offr.length; + } + } catch (IOException e) { + FileNotFoundException fnfe = new FileNotFoundException(); + fnfe.initCause(e); + throw fnfe; + } finally { + if (cursor != null) + cursor.close(); + } + + JSONObject metadata = new JSONObject(); + try { + metadata.put("size", size); + metadata.put("type", mimeType); + metadata.put("name", name); + metadata.put("fullPath", inputURL.path); + metadata.put("lastModifiedDate", lastModified); + } catch (JSONException e) { + return null; + } + return metadata; + } + + @Override + public long writeToFileAtURL(LocalFilesystemURL inputURL, String data, + int offset, boolean isBinary) throws NoModificationAllowedException { + throw new NoModificationAllowedException("Couldn't write to file given its content URI"); + } + @Override + public long truncateFileAtURL(LocalFilesystemURL inputURL, long size) + throws NoModificationAllowedException { + throw new NoModificationAllowedException("Couldn't truncate file given its content URI"); + } + + protected Cursor openCursorForURL(Uri nativeUri) { + ContentResolver contentResolver = context.getContentResolver(); + try { + return contentResolver.query(nativeUri, null, null, null, null); + } catch (UnsupportedOperationException e) { + return null; + } + } + + private Long resourceSizeForCursor(Cursor cursor) { + int columnIndex = cursor.getColumnIndex(OpenableColumns.SIZE); + if (columnIndex != -1) { + String sizeStr = cursor.getString(columnIndex); + if (sizeStr != null) { + return Long.parseLong(sizeStr); + } + } + return null; + } + + protected Long lastModifiedDateForCursor(Cursor cursor) { + int columnIndex = cursor.getColumnIndex(MediaStore.MediaColumns.DATE_MODIFIED); + if (columnIndex == -1) { + columnIndex = cursor.getColumnIndex(DocumentsContract.Document.COLUMN_LAST_MODIFIED); + } + if (columnIndex != -1) { + String dateStr = cursor.getString(columnIndex); + if (dateStr != null) { + return Long.parseLong(dateStr); + } + } + return null; + } + + @Override + public String filesystemPathForURL(LocalFilesystemURL url) { + File f = resourceApi.mapUriToFile(toNativeUri(url)); + return f == null ? null : f.getAbsolutePath(); + } + + @Override + public LocalFilesystemURL URLforFilesystemPath(String path) { + // Returns null as we don't support reverse mapping back to content:// URLs + return null; + } + + @Override + public boolean canRemoveFileAtLocalURL(LocalFilesystemURL inputURL) { + return true; + } +} diff --git a/plugins/cordova-plugin-file/src/android/DirectoryManager.java b/plugins/cordova-plugin-file/src/android/DirectoryManager.java new file mode 100644 index 0000000..07af5ea --- /dev/null +++ b/plugins/cordova-plugin-file/src/android/DirectoryManager.java @@ -0,0 +1,134 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. +*/ +package org.apache.cordova.file; + +import android.os.Environment; +import android.os.StatFs; + +import java.io.File; + +/** + * This class provides file directory utilities. + * All file operations are performed on the SD card. + * + * It is used by the FileUtils class. + */ +public class DirectoryManager { + + @SuppressWarnings("unused") + private static final String LOG_TAG = "DirectoryManager"; + + /** + * Determine if a file or directory exists. + * @param name The name of the file to check. + * @return T=exists, F=not found + */ + public static boolean testFileExists(String name) { + boolean status; + + // If SD card exists + if ((testSaveLocationExists()) && (!name.equals(""))) { + File path = Environment.getExternalStorageDirectory(); + File newPath = constructFilePaths(path.toString(), name); + status = newPath.exists(); + } + // If no SD card + else { + status = false; + } + return status; + } + + /** + * Get the free space in external storage + * + * @return Size in KB or -1 if not available + */ + public static long getFreeExternalStorageSpace() { + String status = Environment.getExternalStorageState(); + long freeSpaceInBytes = 0; + + // Check if external storage exists + if (status.equals(Environment.MEDIA_MOUNTED)) { + freeSpaceInBytes = getFreeSpaceInBytes(Environment.getExternalStorageDirectory().getPath()); + } else { + // If no external storage then return -1 + return -1; + } + + return freeSpaceInBytes / 1024; + } + + /** + * Given a path return the number of free bytes in the filesystem containing the path. + * + * @param path to the file system + * @return free space in bytes + */ + public static long getFreeSpaceInBytes(String path) { + try { + StatFs stat = new StatFs(path); + long blockSize = stat.getBlockSize(); + long availableBlocks = stat.getAvailableBlocks(); + return availableBlocks * blockSize; + } catch (IllegalArgumentException e) { + // The path was invalid. Just return 0 free bytes. + return 0; + } + } + + /** + * Determine if SD card exists. + * + * @return T=exists, F=not found + */ + public static boolean testSaveLocationExists() { + String sDCardStatus = Environment.getExternalStorageState(); + boolean status; + + // If SD card is mounted + if (sDCardStatus.equals(Environment.MEDIA_MOUNTED)) { + status = true; + } + + // If no SD card + else { + status = false; + } + return status; + } + + /** + * Create a new file object from two file paths. + * + * @param file1 Base file path + * @param file2 Remaining file path + * @return File object + */ + private static File constructFilePaths (String file1, String file2) { + File newPath; + if (file2.startsWith(file1)) { + newPath = new File(file2); + } + else { + newPath = new File(file1 + "/" + file2); + } + return newPath; + } +} diff --git a/plugins/cordova-plugin-file/src/android/EncodingException.java b/plugins/cordova-plugin-file/src/android/EncodingException.java new file mode 100644 index 0000000..e9e1653 --- /dev/null +++ b/plugins/cordova-plugin-file/src/android/EncodingException.java @@ -0,0 +1,29 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. +*/ + +package org.apache.cordova.file; + +@SuppressWarnings("serial") +public class EncodingException extends Exception { + + public EncodingException(String message) { + super(message); + } + +} diff --git a/plugins/cordova-plugin-file/src/android/FileExistsException.java b/plugins/cordova-plugin-file/src/android/FileExistsException.java new file mode 100644 index 0000000..5c4d83d --- /dev/null +++ b/plugins/cordova-plugin-file/src/android/FileExistsException.java @@ -0,0 +1,29 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. +*/ + +package org.apache.cordova.file; + +@SuppressWarnings("serial") +public class FileExistsException extends Exception { + + public FileExistsException(String msg) { + super(msg); + } + +} diff --git a/plugins/cordova-plugin-file/src/android/FileUtils.java b/plugins/cordova-plugin-file/src/android/FileUtils.java new file mode 100644 index 0000000..2b88d52 --- /dev/null +++ b/plugins/cordova-plugin-file/src/android/FileUtils.java @@ -0,0 +1,1224 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. + */ +package org.apache.cordova.file; + +import android.Manifest; +import android.app.Activity; +import android.content.Context; +import android.content.pm.PackageManager; +import android.net.Uri; +import android.os.Build; +import android.os.Environment; +import android.util.Base64; + +import org.apache.cordova.CallbackContext; +import org.apache.cordova.CordovaInterface; +import org.apache.cordova.CordovaPlugin; +import org.apache.cordova.CordovaWebView; +import org.apache.cordova.LOG; +import org.apache.cordova.PermissionHelper; +import org.apache.cordova.PluginResult; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.security.Permission; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; + +/** + * This class provides file and directory services to JavaScript. + */ +public class FileUtils extends CordovaPlugin { + private static final String LOG_TAG = "FileUtils"; + + public static int NOT_FOUND_ERR = 1; + public static int SECURITY_ERR = 2; + public static int ABORT_ERR = 3; + + public static int NOT_READABLE_ERR = 4; + public static int ENCODING_ERR = 5; + public static int NO_MODIFICATION_ALLOWED_ERR = 6; + public static int INVALID_STATE_ERR = 7; + public static int SYNTAX_ERR = 8; + public static int INVALID_MODIFICATION_ERR = 9; + public static int QUOTA_EXCEEDED_ERR = 10; + public static int TYPE_MISMATCH_ERR = 11; + public static int PATH_EXISTS_ERR = 12; + + /* + * Permission callback codes + */ + + public static final int ACTION_GET_FILE = 0; + public static final int ACTION_WRITE = 1; + public static final int ACTION_GET_DIRECTORY = 2; + + public static final int WRITE = 3; + public static final int READ = 4; + + public static int UNKNOWN_ERR = 1000; + + private boolean configured = false; + + private PendingRequests pendingRequests; + + + + /* + * We need both read and write when accessing the storage, I think. + */ + + private String [] permissions = { + Manifest.permission.READ_EXTERNAL_STORAGE, + Manifest.permission.WRITE_EXTERNAL_STORAGE }; + + // This field exists only to support getEntry, below, which has been deprecated + private static FileUtils filePlugin; + + private interface FileOp { + void run(JSONArray args) throws Exception; + } + + private ArrayList filesystems; + + public void registerFilesystem(Filesystem fs) { + if (fs != null && filesystemForName(fs.name)== null) { + this.filesystems.add(fs); + } + } + + private Filesystem filesystemForName(String name) { + for (Filesystem fs:filesystems) { + if (fs != null && fs.name != null && fs.name.equals(name)) { + return fs; + } + } + return null; + } + + protected String[] getExtraFileSystemsPreference(Activity activity) { + String fileSystemsStr = preferences.getString("androidextrafilesystems", "files,files-external,documents,sdcard,cache,cache-external,assets,root"); + return fileSystemsStr.split(","); + } + + protected void registerExtraFileSystems(String[] filesystems, HashMap availableFileSystems) { + HashSet installedFileSystems = new HashSet(); + + /* Register filesystems in order */ + for (String fsName : filesystems) { + if (!installedFileSystems.contains(fsName)) { + String fsRoot = availableFileSystems.get(fsName); + if (fsRoot != null) { + File newRoot = new File(fsRoot); + if (newRoot.mkdirs() || newRoot.isDirectory()) { + registerFilesystem(new LocalFilesystem(fsName, webView.getContext(), webView.getResourceApi(), newRoot)); + installedFileSystems.add(fsName); + } else { + LOG.d(LOG_TAG, "Unable to create root dir for filesystem \"" + fsName + "\", skipping"); + } + } else { + LOG.d(LOG_TAG, "Unrecognized extra filesystem identifier: " + fsName); + } + } + } + } + + protected HashMap getAvailableFileSystems(Activity activity) { + Context context = activity.getApplicationContext(); + HashMap availableFileSystems = new HashMap(); + + availableFileSystems.put("files", context.getFilesDir().getAbsolutePath()); + availableFileSystems.put("documents", new File(context.getFilesDir(), "Documents").getAbsolutePath()); + availableFileSystems.put("cache", context.getCacheDir().getAbsolutePath()); + availableFileSystems.put("root", "/"); + if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { + try { + availableFileSystems.put("files-external", context.getExternalFilesDir(null).getAbsolutePath()); + availableFileSystems.put("sdcard", Environment.getExternalStorageDirectory().getAbsolutePath()); + availableFileSystems.put("cache-external", context.getExternalCacheDir().getAbsolutePath()); + } + catch(NullPointerException e) { + LOG.d(LOG_TAG, "External storage unavailable, check to see if USB Mass Storage Mode is on"); + } + } + + return availableFileSystems; + } + + @Override + public void initialize(CordovaInterface cordova, CordovaWebView webView) { + super.initialize(cordova, webView); + this.filesystems = new ArrayList(); + this.pendingRequests = new PendingRequests(); + + String tempRoot = null; + String persistentRoot = null; + + Activity activity = cordova.getActivity(); + String packageName = activity.getPackageName(); + + String location = preferences.getString("androidpersistentfilelocation", "internal"); + + tempRoot = activity.getCacheDir().getAbsolutePath(); + if ("internal".equalsIgnoreCase(location)) { + persistentRoot = activity.getFilesDir().getAbsolutePath() + "/files/"; + this.configured = true; + } else if ("compatibility".equalsIgnoreCase(location)) { + /* + * Fall-back to compatibility mode -- this is the logic implemented in + * earlier versions of this plugin, and should be maintained here so + * that apps which were originally deployed with older versions of the + * plugin can continue to provide access to files stored under those + * versions. + */ + if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { + persistentRoot = Environment.getExternalStorageDirectory().getAbsolutePath(); + tempRoot = Environment.getExternalStorageDirectory().getAbsolutePath() + + "/Android/data/" + packageName + "/cache/"; + } else { + persistentRoot = "/data/data/" + packageName; + } + this.configured = true; + } + + if (this.configured) { + // Create the directories if they don't exist. + File tmpRootFile = new File(tempRoot); + File persistentRootFile = new File(persistentRoot); + tmpRootFile.mkdirs(); + persistentRootFile.mkdirs(); + + // Register initial filesystems + // Note: The temporary and persistent filesystems need to be the first two + // registered, so that they will match window.TEMPORARY and window.PERSISTENT, + // per spec. + this.registerFilesystem(new LocalFilesystem("temporary", webView.getContext(), webView.getResourceApi(), tmpRootFile)); + this.registerFilesystem(new LocalFilesystem("persistent", webView.getContext(), webView.getResourceApi(), persistentRootFile)); + this.registerFilesystem(new ContentFilesystem(webView.getContext(), webView.getResourceApi())); + this.registerFilesystem(new AssetFilesystem(webView.getContext().getAssets(), webView.getResourceApi())); + + registerExtraFileSystems(getExtraFileSystemsPreference(activity), getAvailableFileSystems(activity)); + + // Initialize static plugin reference for deprecated getEntry method + if (filePlugin == null) { + FileUtils.filePlugin = this; + } + } else { + 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)"); + activity.finish(); + } + } + + public static FileUtils getFilePlugin() { + return filePlugin; + } + + private Filesystem filesystemForURL(LocalFilesystemURL localURL) { + if (localURL == null) return null; + return filesystemForName(localURL.fsName); + } + + @Override + public Uri remapUri(Uri uri) { + // Remap only cdvfile: URLs (not content:). + if (!LocalFilesystemURL.FILESYSTEM_PROTOCOL.equals(uri.getScheme())) { + return null; + } + try { + LocalFilesystemURL inputURL = LocalFilesystemURL.parse(uri); + Filesystem fs = this.filesystemForURL(inputURL); + if (fs == null) { + return null; + } + String path = fs.filesystemPathForURL(inputURL); + if (path != null) { + return Uri.parse("file://" + fs.filesystemPathForURL(inputURL)); + } + return null; + } catch (IllegalArgumentException e) { + return null; + } + } + + public boolean execute(String action, final String rawArgs, final CallbackContext callbackContext) { + if (!configured) { + 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")); + return true; + } + if (action.equals("testSaveLocationExists")) { + threadhelper(new FileOp() { + public void run(JSONArray args) { + boolean b = DirectoryManager.testSaveLocationExists(); + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, b)); + } + }, rawArgs, callbackContext); + } + else if (action.equals("getFreeDiskSpace")) { + threadhelper( new FileOp( ){ + public void run(JSONArray args) { + // The getFreeDiskSpace plugin API is not documented, but some apps call it anyway via exec(). + // For compatibility it always returns free space in the primary external storage, and + // does NOT fallback to internal store if external storage is unavailable. + long l = DirectoryManager.getFreeExternalStorageSpace(); + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, l)); + } + }, rawArgs, callbackContext); + } + else if (action.equals("testFileExists")) { + threadhelper( new FileOp( ){ + public void run(JSONArray args) throws JSONException { + String fname=args.getString(0); + boolean b = DirectoryManager.testFileExists(fname); + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, b)); + } + }, rawArgs, callbackContext); + } + else if (action.equals("testDirectoryExists")) { + threadhelper( new FileOp( ){ + public void run(JSONArray args) throws JSONException { + String fname=args.getString(0); + boolean b = DirectoryManager.testFileExists(fname); + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, b)); + } + }, rawArgs, callbackContext); + } + else if (action.equals("readAsText")) { + threadhelper( new FileOp( ){ + public void run(JSONArray args) throws JSONException, MalformedURLException { + String encoding = args.getString(1); + int start = args.getInt(2); + int end = args.getInt(3); + String fname=args.getString(0); + readFileAs(fname, start, end, callbackContext, encoding, PluginResult.MESSAGE_TYPE_STRING); + } + }, rawArgs, callbackContext); + } + else if (action.equals("readAsDataURL")) { + threadhelper( new FileOp( ){ + public void run(JSONArray args) throws JSONException, MalformedURLException { + int start = args.getInt(1); + int end = args.getInt(2); + String fname=args.getString(0); + readFileAs(fname, start, end, callbackContext, null, -1); + } + }, rawArgs, callbackContext); + } + else if (action.equals("readAsArrayBuffer")) { + threadhelper( new FileOp( ){ + public void run(JSONArray args) throws JSONException, MalformedURLException { + int start = args.getInt(1); + int end = args.getInt(2); + String fname=args.getString(0); + readFileAs(fname, start, end, callbackContext, null, PluginResult.MESSAGE_TYPE_ARRAYBUFFER); + } + }, rawArgs, callbackContext); + } + else if (action.equals("readAsBinaryString")) { + threadhelper( new FileOp( ){ + public void run(JSONArray args) throws JSONException, MalformedURLException { + int start = args.getInt(1); + int end = args.getInt(2); + String fname=args.getString(0); + readFileAs(fname, start, end, callbackContext, null, PluginResult.MESSAGE_TYPE_BINARYSTRING); + } + }, rawArgs, callbackContext); + } + else if (action.equals("write")) { + threadhelper( new FileOp( ){ + public void run(JSONArray args) throws JSONException, FileNotFoundException, IOException, NoModificationAllowedException { + String fname=args.getString(0); + String nativeURL = resolveLocalFileSystemURI(fname).getString("nativeURL"); + String data=args.getString(1); + int offset=args.getInt(2); + Boolean isBinary=args.getBoolean(3); + + if(needPermission(nativeURL, WRITE)) { + getWritePermission(rawArgs, ACTION_WRITE, callbackContext); + } + else { + long fileSize = write(fname, data, offset, isBinary); + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, fileSize)); + } + + } + }, rawArgs, callbackContext); + } + else if (action.equals("truncate")) { + threadhelper( new FileOp( ){ + public void run(JSONArray args) throws JSONException, FileNotFoundException, IOException, NoModificationAllowedException { + String fname=args.getString(0); + int offset=args.getInt(1); + long fileSize = truncateFile(fname, offset); + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, fileSize)); + } + }, rawArgs, callbackContext); + } + else if (action.equals("requestAllFileSystems")) { + threadhelper( new FileOp( ){ + public void run(JSONArray args) throws IOException, JSONException { + callbackContext.success(requestAllFileSystems()); + } + }, rawArgs, callbackContext); + } else if (action.equals("requestAllPaths")) { + cordova.getThreadPool().execute( + new Runnable() { + public void run() { + try { + callbackContext.success(requestAllPaths()); + } catch (JSONException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + ); + } else if (action.equals("requestFileSystem")) { + threadhelper( new FileOp( ){ + public void run(JSONArray args) throws JSONException { + int fstype = args.getInt(0); + long requiredSize = args.optLong(1); + requestFileSystem(fstype, requiredSize, callbackContext); + } + }, rawArgs, callbackContext); + } + else if (action.equals("resolveLocalFileSystemURI")) { + threadhelper( new FileOp( ){ + public void run(JSONArray args) throws IOException, JSONException { + String fname=args.getString(0); + JSONObject obj = resolveLocalFileSystemURI(fname); + callbackContext.success(obj); + } + }, rawArgs, callbackContext); + } + else if (action.equals("getFileMetadata")) { + threadhelper( new FileOp( ){ + public void run(JSONArray args) throws FileNotFoundException, JSONException, MalformedURLException { + String fname=args.getString(0); + JSONObject obj = getFileMetadata(fname); + callbackContext.success(obj); + } + }, rawArgs, callbackContext); + } + else if (action.equals("getParent")) { + threadhelper( new FileOp( ){ + public void run(JSONArray args) throws JSONException, IOException { + String fname=args.getString(0); + JSONObject obj = getParent(fname); + callbackContext.success(obj); + } + }, rawArgs, callbackContext); + } + else if (action.equals("getDirectory")) { + threadhelper( new FileOp( ){ + public void run(JSONArray args) throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException { + String dirname = args.getString(0); + String path = args.getString(1); + String nativeURL = resolveLocalFileSystemURI(dirname).getString("nativeURL"); + boolean containsCreate = (args.isNull(2)) ? false : args.getJSONObject(2).optBoolean("create", false); + + if(containsCreate && needPermission(nativeURL, WRITE)) { + getWritePermission(rawArgs, ACTION_GET_DIRECTORY, callbackContext); + } + else if(!containsCreate && needPermission(nativeURL, READ)) { + getReadPermission(rawArgs, ACTION_GET_DIRECTORY, callbackContext); + } + else { + JSONObject obj = getFile(dirname, path, args.optJSONObject(2), true); + callbackContext.success(obj); + } + } + }, rawArgs, callbackContext); + } + else if (action.equals("getFile")) { + threadhelper( new FileOp( ){ + public void run(JSONArray args) throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException { + String dirname = args.getString(0); + String path = args.getString(1); + String nativeURL = resolveLocalFileSystemURI(dirname).getString("nativeURL"); + boolean containsCreate = (args.isNull(2)) ? false : args.getJSONObject(2).optBoolean("create", false); + + if(containsCreate && needPermission(nativeURL, WRITE)) { + getWritePermission(rawArgs, ACTION_GET_FILE, callbackContext); + } + else if(!containsCreate && needPermission(nativeURL, READ)) { + getReadPermission(rawArgs, ACTION_GET_FILE, callbackContext); + } + else { + JSONObject obj = getFile(dirname, path, args.optJSONObject(2), false); + callbackContext.success(obj); + } + } + }, rawArgs, callbackContext); + } + else if (action.equals("remove")) { + threadhelper( new FileOp( ){ + public void run(JSONArray args) throws JSONException, NoModificationAllowedException, InvalidModificationException, MalformedURLException { + String fname=args.getString(0); + boolean success = remove(fname); + if (success) { + callbackContext.success(); + } else { + callbackContext.error(FileUtils.NO_MODIFICATION_ALLOWED_ERR); + } + } + }, rawArgs, callbackContext); + } + else if (action.equals("removeRecursively")) { + threadhelper( new FileOp( ){ + public void run(JSONArray args) throws JSONException, FileExistsException, MalformedURLException, NoModificationAllowedException { + String fname=args.getString(0); + boolean success = removeRecursively(fname); + if (success) { + callbackContext.success(); + } else { + callbackContext.error(FileUtils.NO_MODIFICATION_ALLOWED_ERR); + } + } + }, rawArgs, callbackContext); + } + else if (action.equals("moveTo")) { + threadhelper( new FileOp( ){ + public void run(JSONArray args) throws JSONException, NoModificationAllowedException, IOException, InvalidModificationException, EncodingException, FileExistsException { + String fname=args.getString(0); + String newParent=args.getString(1); + String newName=args.getString(2); + JSONObject entry = transferTo(fname, newParent, newName, true); + callbackContext.success(entry); + } + }, rawArgs, callbackContext); + } + else if (action.equals("copyTo")) { + threadhelper( new FileOp( ){ + public void run(JSONArray args) throws JSONException, NoModificationAllowedException, IOException, InvalidModificationException, EncodingException, FileExistsException { + String fname=args.getString(0); + String newParent=args.getString(1); + String newName=args.getString(2); + JSONObject entry = transferTo(fname, newParent, newName, false); + callbackContext.success(entry); + } + }, rawArgs, callbackContext); + } + else if (action.equals("readEntries")) { + threadhelper( new FileOp( ){ + public void run(JSONArray args) throws FileNotFoundException, JSONException, MalformedURLException { + String fname=args.getString(0); + JSONArray entries = readEntries(fname); + callbackContext.success(entries); + } + }, rawArgs, callbackContext); + } + else if (action.equals("_getLocalFilesystemPath")) { + // Internal method for testing: Get the on-disk location of a local filesystem url. + // [Currently used for testing file-transfer] + threadhelper( new FileOp( ){ + public void run(JSONArray args) throws FileNotFoundException, JSONException, MalformedURLException { + String localURLstr = args.getString(0); + String fname = filesystemPathForURL(localURLstr); + callbackContext.success(fname); + } + }, rawArgs, callbackContext); + } + else { + return false; + } + return true; + } + + private void getReadPermission(String rawArgs, int action, CallbackContext callbackContext) { + int requestCode = pendingRequests.createRequest(rawArgs, action, callbackContext); + PermissionHelper.requestPermission(this, requestCode, Manifest.permission.READ_EXTERNAL_STORAGE); + } + + private void getWritePermission(String rawArgs, int action, CallbackContext callbackContext) { + int requestCode = pendingRequests.createRequest(rawArgs, action, callbackContext); + PermissionHelper.requestPermission(this, requestCode, Manifest.permission.WRITE_EXTERNAL_STORAGE); + } + + private boolean hasReadPermission() { + return PermissionHelper.hasPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE); + } + + private boolean hasWritePermission() { + return PermissionHelper.hasPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE); + } + + private boolean needPermission(String nativeURL, int permissionType) throws JSONException { + JSONObject j = requestAllPaths(); + ArrayList allowedStorageDirectories = new ArrayList(); + allowedStorageDirectories.add(j.getString("applicationStorageDirectory")); + if(j.has("externalApplicationStorageDirectory")) { + allowedStorageDirectories.add(j.getString("externalApplicationStorageDirectory")); + } + + if(permissionType == READ && hasReadPermission()) { + return false; + } + else if(permissionType == WRITE && hasWritePermission()) { + return false; + } + + // Permission required if the native url lies outside the allowed storage directories + for(String directory : allowedStorageDirectories) { + if(nativeURL.startsWith(directory)) { + return false; + } + } + return true; + } + + + public LocalFilesystemURL resolveNativeUri(Uri nativeUri) { + LocalFilesystemURL localURL = null; + + // Try all installed filesystems. Return the best matching URL + // (determined by the shortest resulting URL) + for (Filesystem fs : filesystems) { + LocalFilesystemURL url = fs.toLocalUri(nativeUri); + if (url != null) { + // A shorter fullPath implies that the filesystem is a better + // match for the local path than the previous best. + if (localURL == null || (url.uri.toString().length() < localURL.toString().length())) { + localURL = url; + } + } + } + return localURL; + } + + /* + * These two native-only methods can be used by other plugins to translate between + * device file system paths and URLs. By design, there is no direct JavaScript + * interface to these methods. + */ + + public String filesystemPathForURL(String localURLstr) throws MalformedURLException { + try { + LocalFilesystemURL inputURL = LocalFilesystemURL.parse(localURLstr); + Filesystem fs = this.filesystemForURL(inputURL); + if (fs == null) { + throw new MalformedURLException("No installed handlers for this URL"); + } + return fs.filesystemPathForURL(inputURL); + } catch (IllegalArgumentException e) { + MalformedURLException mue = new MalformedURLException("Unrecognized filesystem URL"); + mue.initCause(e); + throw mue; + } + } + + public LocalFilesystemURL filesystemURLforLocalPath(String localPath) { + LocalFilesystemURL localURL = null; + int shortestFullPath = 0; + + // Try all installed filesystems. Return the best matching URL + // (determined by the shortest resulting URL) + for (Filesystem fs: filesystems) { + LocalFilesystemURL url = fs.URLforFilesystemPath(localPath); + if (url != null) { + // A shorter fullPath implies that the filesystem is a better + // match for the local path than the previous best. + if (localURL == null || (url.path.length() < shortestFullPath)) { + localURL = url; + shortestFullPath = url.path.length(); + } + } + } + return localURL; + } + + + /* helper to execute functions async and handle the result codes + * + */ + private void threadhelper(final FileOp f, final String rawArgs, final CallbackContext callbackContext){ + cordova.getThreadPool().execute(new Runnable() { + public void run() { + try { + JSONArray args = new JSONArray(rawArgs); + f.run(args); + } catch ( Exception e) { + if( e instanceof EncodingException){ + callbackContext.error(FileUtils.ENCODING_ERR); + } else if(e instanceof FileNotFoundException) { + callbackContext.error(FileUtils.NOT_FOUND_ERR); + } else if(e instanceof FileExistsException) { + callbackContext.error(FileUtils.PATH_EXISTS_ERR); + } else if(e instanceof NoModificationAllowedException ) { + callbackContext.error(FileUtils.NO_MODIFICATION_ALLOWED_ERR); + } else if(e instanceof InvalidModificationException ) { + callbackContext.error(FileUtils.INVALID_MODIFICATION_ERR); + } else if(e instanceof MalformedURLException ) { + callbackContext.error(FileUtils.ENCODING_ERR); + } else if(e instanceof IOException ) { + callbackContext.error(FileUtils.INVALID_MODIFICATION_ERR); + } else if(e instanceof EncodingException ) { + callbackContext.error(FileUtils.ENCODING_ERR); + } else if(e instanceof TypeMismatchException ) { + callbackContext.error(FileUtils.TYPE_MISMATCH_ERR); + } else if(e instanceof JSONException ) { + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); + } else if (e instanceof SecurityException) { + callbackContext.error(FileUtils.SECURITY_ERR); + } else { + e.printStackTrace(); + callbackContext.error(FileUtils.UNKNOWN_ERR); + } + } + } + }); + } + + /** + * Allows the user to look up the Entry for a file or directory referred to by a local URI. + * + * @param uriString of the file/directory to look up + * @return a JSONObject representing a Entry from the filesystem + * @throws MalformedURLException if the url is not valid + * @throws FileNotFoundException if the file does not exist + * @throws IOException if the user can't read the file + * @throws JSONException + */ + private JSONObject resolveLocalFileSystemURI(String uriString) throws IOException, JSONException { + if (uriString == null) { + throw new MalformedURLException("Unrecognized filesystem URL"); + } + Uri uri = Uri.parse(uriString); + boolean isNativeUri = false; + + LocalFilesystemURL inputURL = LocalFilesystemURL.parse(uri); + if (inputURL == null) { + /* Check for file://, content:// urls */ + inputURL = resolveNativeUri(uri); + isNativeUri = true; + } + + try { + Filesystem fs = this.filesystemForURL(inputURL); + if (fs == null) { + throw new MalformedURLException("No installed handlers for this URL"); + } + if (fs.exists(inputURL)) { + if (!isNativeUri) { + // If not already resolved as native URI, resolve to a native URI and back to + // fix the terminating slash based on whether the entry is a directory or file. + inputURL = fs.toLocalUri(fs.toNativeUri(inputURL)); + } + + return fs.getEntryForLocalURL(inputURL); + } + } catch (IllegalArgumentException e) { + MalformedURLException mue = new MalformedURLException("Unrecognized filesystem URL"); + mue.initCause(e); + throw mue; + } + throw new FileNotFoundException(); + } + + /** + * Read the list of files from this directory. + * + * @return a JSONArray containing JSONObjects that represent Entry objects. + * @throws FileNotFoundException if the directory is not found. + * @throws JSONException + * @throws MalformedURLException + */ + private JSONArray readEntries(String baseURLstr) throws FileNotFoundException, JSONException, MalformedURLException { + try { + LocalFilesystemURL inputURL = LocalFilesystemURL.parse(baseURLstr); + Filesystem fs = this.filesystemForURL(inputURL); + if (fs == null) { + throw new MalformedURLException("No installed handlers for this URL"); + } + return fs.readEntriesAtLocalURL(inputURL); + + } catch (IllegalArgumentException e) { + MalformedURLException mue = new MalformedURLException("Unrecognized filesystem URL"); + mue.initCause(e); + throw mue; + } + } + + /** + * A setup method that handles the move/copy of files/directories + * + * @param newName for the file directory to be called, if null use existing file name + * @param move if false do a copy, if true do a move + * @return a Entry object + * @throws NoModificationAllowedException + * @throws IOException + * @throws InvalidModificationException + * @throws EncodingException + * @throws JSONException + * @throws FileExistsException + */ + private JSONObject transferTo(String srcURLstr, String destURLstr, String newName, boolean move) throws JSONException, NoModificationAllowedException, IOException, InvalidModificationException, EncodingException, FileExistsException { + if (srcURLstr == null || destURLstr == null) { + // either no source or no destination provided + throw new FileNotFoundException(); + } + + LocalFilesystemURL srcURL = LocalFilesystemURL.parse(srcURLstr); + LocalFilesystemURL destURL = LocalFilesystemURL.parse(destURLstr); + + Filesystem srcFs = this.filesystemForURL(srcURL); + Filesystem destFs = this.filesystemForURL(destURL); + + // Check for invalid file name + if (newName != null && newName.contains(":")) { + throw new EncodingException("Bad file name"); + } + + return destFs.copyFileToURL(destURL, newName, srcFs, srcURL, move); + } + + /** + * Deletes a directory and all of its contents, if any. In the event of an error + * [e.g. trying to delete a directory that contains a file that cannot be removed], + * some of the contents of the directory may be deleted. + * It is an error to attempt to delete the root directory of a filesystem. + * + * @return a boolean representing success of failure + * @throws FileExistsException + * @throws NoModificationAllowedException + * @throws MalformedURLException + */ + private boolean removeRecursively(String baseURLstr) throws FileExistsException, NoModificationAllowedException, MalformedURLException { + try { + LocalFilesystemURL inputURL = LocalFilesystemURL.parse(baseURLstr); + // You can't delete the root directory. + if ("".equals(inputURL.path) || "/".equals(inputURL.path)) { + throw new NoModificationAllowedException("You can't delete the root directory"); + } + + Filesystem fs = this.filesystemForURL(inputURL); + if (fs == null) { + throw new MalformedURLException("No installed handlers for this URL"); + } + return fs.recursiveRemoveFileAtLocalURL(inputURL); + + } catch (IllegalArgumentException e) { + MalformedURLException mue = new MalformedURLException("Unrecognized filesystem URL"); + mue.initCause(e); + throw mue; + } + } + + + /** + * Deletes a file or directory. It is an error to attempt to delete a directory that is not empty. + * It is an error to attempt to delete the root directory of a filesystem. + * + * @return a boolean representing success of failure + * @throws NoModificationAllowedException + * @throws InvalidModificationException + * @throws MalformedURLException + */ + private boolean remove(String baseURLstr) throws NoModificationAllowedException, InvalidModificationException, MalformedURLException { + try { + LocalFilesystemURL inputURL = LocalFilesystemURL.parse(baseURLstr); + // You can't delete the root directory. + if ("".equals(inputURL.path) || "/".equals(inputURL.path)) { + + throw new NoModificationAllowedException("You can't delete the root directory"); + } + + Filesystem fs = this.filesystemForURL(inputURL); + if (fs == null) { + throw new MalformedURLException("No installed handlers for this URL"); + } + return fs.removeFileAtLocalURL(inputURL); + + } catch (IllegalArgumentException e) { + MalformedURLException mue = new MalformedURLException("Unrecognized filesystem URL"); + mue.initCause(e); + throw mue; + } + } + + /** + * Creates or looks up a file. + * + * @param baseURLstr base directory + * @param path file/directory to lookup or create + * @param options specify whether to create or not + * @param directory if true look up directory, if false look up file + * @return a Entry object + * @throws FileExistsException + * @throws IOException + * @throws TypeMismatchException + * @throws EncodingException + * @throws JSONException + */ + private JSONObject getFile(String baseURLstr, String path, JSONObject options, boolean directory) throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException { + try { + LocalFilesystemURL inputURL = LocalFilesystemURL.parse(baseURLstr); + Filesystem fs = this.filesystemForURL(inputURL); + if (fs == null) { + throw new MalformedURLException("No installed handlers for this URL"); + } + return fs.getFileForLocalURL(inputURL, path, options, directory); + + } catch (IllegalArgumentException e) { + MalformedURLException mue = new MalformedURLException("Unrecognized filesystem URL"); + mue.initCause(e); + throw mue; + } + + } + + /** + * Look up the parent DirectoryEntry containing this Entry. + * If this Entry is the root of its filesystem, its parent is itself. + */ + private JSONObject getParent(String baseURLstr) throws JSONException, IOException { + try { + LocalFilesystemURL inputURL = LocalFilesystemURL.parse(baseURLstr); + Filesystem fs = this.filesystemForURL(inputURL); + if (fs == null) { + throw new MalformedURLException("No installed handlers for this URL"); + } + return fs.getParentForLocalURL(inputURL); + + } catch (IllegalArgumentException e) { + MalformedURLException mue = new MalformedURLException("Unrecognized filesystem URL"); + mue.initCause(e); + throw mue; + } + } + + /** + * Returns a File that represents the current state of the file that this FileEntry represents. + * + * @return returns a JSONObject represent a W3C File object + */ + private JSONObject getFileMetadata(String baseURLstr) throws FileNotFoundException, JSONException, MalformedURLException { + try { + LocalFilesystemURL inputURL = LocalFilesystemURL.parse(baseURLstr); + Filesystem fs = this.filesystemForURL(inputURL); + if (fs == null) { + throw new MalformedURLException("No installed handlers for this URL"); + } + return fs.getFileMetadataForLocalURL(inputURL); + + } catch (IllegalArgumentException e) { + MalformedURLException mue = new MalformedURLException("Unrecognized filesystem URL"); + mue.initCause(e); + throw mue; + } + } + + /** + * Requests a filesystem in which to store application data. + * + * @param type of file system requested + * @param requiredSize required free space in the file system in bytes + * @param callbackContext context for returning the result or error + * @throws JSONException + */ + private void requestFileSystem(int type, long requiredSize, final CallbackContext callbackContext) throws JSONException { + Filesystem rootFs = null; + try { + rootFs = this.filesystems.get(type); + } catch (ArrayIndexOutOfBoundsException e) { + // Pass null through + } + if (rootFs == null) { + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, FileUtils.NOT_FOUND_ERR)); + } else { + // If a nonzero required size was specified, check that the retrieved filesystem has enough free space. + long availableSize = 0; + if (requiredSize > 0) { + availableSize = rootFs.getFreeSpaceInBytes(); + } + + if (availableSize < requiredSize) { + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, FileUtils.QUOTA_EXCEEDED_ERR)); + } else { + JSONObject fs = new JSONObject(); + fs.put("name", rootFs.name); + fs.put("root", rootFs.getRootEntry()); + callbackContext.success(fs); + } + } + } + + /** + * Requests a filesystem in which to store application data. + * + * @return a JSONObject representing the file system + */ + private JSONArray requestAllFileSystems() throws IOException, JSONException { + JSONArray ret = new JSONArray(); + for (Filesystem fs : filesystems) { + ret.put(fs.getRootEntry()); + } + return ret; + } + + private static String toDirUrl(File f) { + return Uri.fromFile(f).toString() + '/'; + } + + private JSONObject requestAllPaths() throws JSONException { + Context context = cordova.getActivity(); + JSONObject ret = new JSONObject(); + ret.put("applicationDirectory", "file:///android_asset/"); + ret.put("applicationStorageDirectory", toDirUrl(context.getFilesDir().getParentFile())); + ret.put("dataDirectory", toDirUrl(context.getFilesDir())); + ret.put("cacheDirectory", toDirUrl(context.getCacheDir())); + if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { + try { + ret.put("externalApplicationStorageDirectory", toDirUrl(context.getExternalFilesDir(null).getParentFile())); + ret.put("externalDataDirectory", toDirUrl(context.getExternalFilesDir(null))); + ret.put("externalCacheDirectory", toDirUrl(context.getExternalCacheDir())); + ret.put("externalRootDirectory", toDirUrl(Environment.getExternalStorageDirectory())); + } + catch(NullPointerException e) { + /* If external storage is unavailable, context.getExternal* returns null */ + LOG.d(LOG_TAG, "Unable to access these paths, most liklely due to USB storage"); + } + } + return ret; + } + + /** + * Returns a JSON object representing the given File. Internal APIs should be modified + * to use URLs instead of raw FS paths wherever possible, when interfacing with this plugin. + * + * @param file the File to convert + * @return a JSON representation of the given File + * @throws JSONException + */ + public JSONObject getEntryForFile(File file) throws JSONException { + JSONObject entry; + + for (Filesystem fs : filesystems) { + entry = fs.makeEntryForFile(file); + if (entry != null) { + return entry; + } + } + return null; + } + + /** + * Returns a JSON object representing the given File. Deprecated, as this is only used by + * FileTransfer, and because it is a static method that should really be an instance method, + * since it depends on the actual filesystem roots in use. Internal APIs should be modified + * to use URLs instead of raw FS paths wherever possible, when interfacing with this plugin. + * + * @param file the File to convert + * @return a JSON representation of the given File + * @throws JSONException + */ + @Deprecated + public static JSONObject getEntry(File file) throws JSONException { + if (getFilePlugin() != null) { + return getFilePlugin().getEntryForFile(file); + } + return null; + } + + /** + * Read the contents of a file. + * This is done in a background thread; the result is sent to the callback. + * + * @param start Start position in the file. + * @param end End position to stop at (exclusive). + * @param callbackContext The context through which to send the result. + * @param encoding The encoding to return contents as. Typical value is UTF-8. (see http://www.iana.org/assignments/character-sets) + * @param resultType The desired type of data to send to the callback. + * @return Contents of file. + */ + public void readFileAs(final String srcURLstr, final int start, final int end, final CallbackContext callbackContext, final String encoding, final int resultType) throws MalformedURLException { + try { + LocalFilesystemURL inputURL = LocalFilesystemURL.parse(srcURLstr); + Filesystem fs = this.filesystemForURL(inputURL); + if (fs == null) { + throw new MalformedURLException("No installed handlers for this URL"); + } + + fs.readFileAtURL(inputURL, start, end, new Filesystem.ReadFileCallback() { + public void handleData(InputStream inputStream, String contentType) { + try { + ByteArrayOutputStream os = new ByteArrayOutputStream(); + final int BUFFER_SIZE = 8192; + byte[] buffer = new byte[BUFFER_SIZE]; + + for (;;) { + int bytesRead = inputStream.read(buffer, 0, BUFFER_SIZE); + + if (bytesRead <= 0) { + break; + } + os.write(buffer, 0, bytesRead); + } + + PluginResult result; + switch (resultType) { + case PluginResult.MESSAGE_TYPE_STRING: + result = new PluginResult(PluginResult.Status.OK, os.toString(encoding)); + break; + case PluginResult.MESSAGE_TYPE_ARRAYBUFFER: + result = new PluginResult(PluginResult.Status.OK, os.toByteArray()); + break; + case PluginResult.MESSAGE_TYPE_BINARYSTRING: + result = new PluginResult(PluginResult.Status.OK, os.toByteArray(), true); + break; + default: // Base64. + byte[] base64 = Base64.encode(os.toByteArray(), Base64.NO_WRAP); + String s = "data:" + contentType + ";base64," + new String(base64, "US-ASCII"); + result = new PluginResult(PluginResult.Status.OK, s); + } + + callbackContext.sendPluginResult(result); + } catch (IOException e) { + LOG.d(LOG_TAG, e.getLocalizedMessage()); + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, NOT_READABLE_ERR)); + } + } + }); + + + } catch (IllegalArgumentException e) { + MalformedURLException mue = new MalformedURLException("Unrecognized filesystem URL"); + mue.initCause(e); + throw mue; + } catch (FileNotFoundException e) { + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, NOT_FOUND_ERR)); + } catch (IOException e) { + LOG.d(LOG_TAG, e.getLocalizedMessage()); + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, NOT_READABLE_ERR)); + } + } + + + /** + * Write contents of file. + * + * @param data The contents of the file. + * @param offset The position to begin writing the file. + * @param isBinary True if the file contents are base64-encoded binary data + */ + /**/ + public long write(String srcURLstr, String data, int offset, boolean isBinary) throws FileNotFoundException, IOException, NoModificationAllowedException { + try { + LocalFilesystemURL inputURL = LocalFilesystemURL.parse(srcURLstr); + Filesystem fs = this.filesystemForURL(inputURL); + if (fs == null) { + throw new MalformedURLException("No installed handlers for this URL"); + } + + long x = fs.writeToFileAtURL(inputURL, data, offset, isBinary); LOG.d("TEST",srcURLstr + ": "+x); return x; + } catch (IllegalArgumentException e) { + MalformedURLException mue = new MalformedURLException("Unrecognized filesystem URL"); + mue.initCause(e); + throw mue; + } + + } + + /** + * Truncate the file to size + */ + private long truncateFile(String srcURLstr, long size) throws FileNotFoundException, IOException, NoModificationAllowedException { + try { + LocalFilesystemURL inputURL = LocalFilesystemURL.parse(srcURLstr); + Filesystem fs = this.filesystemForURL(inputURL); + if (fs == null) { + throw new MalformedURLException("No installed handlers for this URL"); + } + + return fs.truncateFileAtURL(inputURL, size); + } catch (IllegalArgumentException e) { + MalformedURLException mue = new MalformedURLException("Unrecognized filesystem URL"); + mue.initCause(e); + throw mue; + } + } + + + /* + * Handle the response + */ + + public void onRequestPermissionResult(int requestCode, String[] permissions, + int[] grantResults) throws JSONException { + + final PendingRequests.Request req = pendingRequests.getAndRemove(requestCode); + if (req != null) { + for(int r:grantResults) + { + if(r == PackageManager.PERMISSION_DENIED) + { + req.getCallbackContext().sendPluginResult(new PluginResult(PluginResult.Status.ERROR, SECURITY_ERR)); + return; + } + } + switch(req.getAction()) + { + case ACTION_GET_FILE: + threadhelper( new FileOp( ){ + public void run(JSONArray args) throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException { + String dirname = args.getString(0); + + String path = args.getString(1); + JSONObject obj = getFile(dirname, path, args.optJSONObject(2), false); + req.getCallbackContext().success(obj); + } + }, req.getRawArgs(), req.getCallbackContext()); + break; + case ACTION_GET_DIRECTORY: + threadhelper( new FileOp( ){ + public void run(JSONArray args) throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException { + String dirname = args.getString(0); + + String path = args.getString(1); + JSONObject obj = getFile(dirname, path, args.optJSONObject(2), true); + req.getCallbackContext().success(obj); + } + }, req.getRawArgs(), req.getCallbackContext()); + break; + case ACTION_WRITE: + threadhelper( new FileOp( ){ + public void run(JSONArray args) throws JSONException, FileNotFoundException, IOException, NoModificationAllowedException { + String fname=args.getString(0); + String data=args.getString(1); + int offset=args.getInt(2); + Boolean isBinary=args.getBoolean(3); + long fileSize = write(fname, data, offset, isBinary); + req.getCallbackContext().sendPluginResult(new PluginResult(PluginResult.Status.OK, fileSize)); + } + }, req.getRawArgs(), req.getCallbackContext()); + break; + } + } else { + LOG.d(LOG_TAG, "Received permission callback for unknown request code"); + } + } +} diff --git a/plugins/cordova-plugin-file/src/android/Filesystem.java b/plugins/cordova-plugin-file/src/android/Filesystem.java new file mode 100644 index 0000000..c69d3bd --- /dev/null +++ b/plugins/cordova-plugin-file/src/android/Filesystem.java @@ -0,0 +1,331 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. + */ +package org.apache.cordova.file; + +import android.net.Uri; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FilterInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.Arrays; + +import org.apache.cordova.CordovaResourceApi; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +public abstract class Filesystem { + + protected final Uri rootUri; + protected final CordovaResourceApi resourceApi; + public final String name; + private JSONObject rootEntry; + + public Filesystem(Uri rootUri, String name, CordovaResourceApi resourceApi) { + this.rootUri = rootUri; + this.name = name; + this.resourceApi = resourceApi; + } + + public interface ReadFileCallback { + public void handleData(InputStream inputStream, String contentType) throws IOException; + } + + public static JSONObject makeEntryForURL(LocalFilesystemURL inputURL, Uri nativeURL) { + try { + String path = inputURL.path; + int end = path.endsWith("/") ? 1 : 0; + String[] parts = path.substring(0, path.length() - end).split("/+"); + String fileName = parts[parts.length - 1]; + + JSONObject entry = new JSONObject(); + entry.put("isFile", !inputURL.isDirectory); + entry.put("isDirectory", inputURL.isDirectory); + entry.put("name", fileName); + entry.put("fullPath", path); + // The file system can't be specified, as it would lead to an infinite loop, + // but the filesystem name can be. + entry.put("filesystemName", inputURL.fsName); + // Backwards compatibility + entry.put("filesystem", "temporary".equals(inputURL.fsName) ? 0 : 1); + + String nativeUrlStr = nativeURL.toString(); + if (inputURL.isDirectory && !nativeUrlStr.endsWith("/")) { + nativeUrlStr += "/"; + } + entry.put("nativeURL", nativeUrlStr); + return entry; + } catch (JSONException e) { + e.printStackTrace(); + throw new RuntimeException(e); + } + } + + public JSONObject makeEntryForURL(LocalFilesystemURL inputURL) { + Uri nativeUri = toNativeUri(inputURL); + return nativeUri == null ? null : makeEntryForURL(inputURL, nativeUri); + } + + public JSONObject makeEntryForNativeUri(Uri nativeUri) { + LocalFilesystemURL inputUrl = toLocalUri(nativeUri); + return inputUrl == null ? null : makeEntryForURL(inputUrl, nativeUri); + } + + public JSONObject getEntryForLocalURL(LocalFilesystemURL inputURL) throws IOException { + return makeEntryForURL(inputURL); + } + + public JSONObject makeEntryForFile(File file) { + return makeEntryForNativeUri(Uri.fromFile(file)); + } + + abstract JSONObject getFileForLocalURL(LocalFilesystemURL inputURL, String path, + JSONObject options, boolean directory) throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException; + + abstract boolean removeFileAtLocalURL(LocalFilesystemURL inputURL) throws InvalidModificationException, NoModificationAllowedException; + + abstract boolean recursiveRemoveFileAtLocalURL(LocalFilesystemURL inputURL) throws FileExistsException, NoModificationAllowedException; + + abstract LocalFilesystemURL[] listChildren(LocalFilesystemURL inputURL) throws FileNotFoundException; + + public final JSONArray readEntriesAtLocalURL(LocalFilesystemURL inputURL) throws FileNotFoundException { + LocalFilesystemURL[] children = listChildren(inputURL); + JSONArray entries = new JSONArray(); + if (children != null) { + for (LocalFilesystemURL url : children) { + entries.put(makeEntryForURL(url)); + } + } + return entries; + } + + abstract JSONObject getFileMetadataForLocalURL(LocalFilesystemURL inputURL) throws FileNotFoundException; + + public Uri getRootUri() { + return rootUri; + } + + public boolean exists(LocalFilesystemURL inputURL) { + try { + getFileMetadataForLocalURL(inputURL); + } catch (FileNotFoundException e) { + return false; + } + return true; + } + + public Uri nativeUriForFullPath(String fullPath) { + Uri ret = null; + if (fullPath != null) { + String encodedPath = Uri.fromFile(new File(fullPath)).getEncodedPath(); + if (encodedPath.startsWith("/")) { + encodedPath = encodedPath.substring(1); + } + ret = rootUri.buildUpon().appendEncodedPath(encodedPath).build(); + } + return ret; + } + + public LocalFilesystemURL localUrlforFullPath(String fullPath) { + Uri nativeUri = nativeUriForFullPath(fullPath); + if (nativeUri != null) { + return toLocalUri(nativeUri); + } + return null; + } + + /** + * Removes multiple repeated //s, and collapses processes ../s. + */ + protected static String normalizePath(String rawPath) { + // If this is an absolute path, trim the leading "/" and replace it later + boolean isAbsolutePath = rawPath.startsWith("/"); + if (isAbsolutePath) { + rawPath = rawPath.replaceFirst("/+", ""); + } + ArrayList components = new ArrayList(Arrays.asList(rawPath.split("/+"))); + for (int index = 0; index < components.size(); ++index) { + if (components.get(index).equals("..")) { + components.remove(index); + if (index > 0) { + components.remove(index-1); + --index; + } + } + } + StringBuilder normalizedPath = new StringBuilder(); + for(String component: components) { + normalizedPath.append("/"); + normalizedPath.append(component); + } + if (isAbsolutePath) { + return normalizedPath.toString(); + } else { + return normalizedPath.toString().substring(1); + } + } + + /** + * Gets the free space in bytes available on this filesystem. + * Subclasses may override this method to return nonzero free space. + */ + public long getFreeSpaceInBytes() { + return 0; + } + + public abstract Uri toNativeUri(LocalFilesystemURL inputURL); + public abstract LocalFilesystemURL toLocalUri(Uri inputURL); + + public JSONObject getRootEntry() { + if (rootEntry == null) { + rootEntry = makeEntryForNativeUri(rootUri); + } + return rootEntry; + } + + public JSONObject getParentForLocalURL(LocalFilesystemURL inputURL) throws IOException { + Uri parentUri = inputURL.uri; + String parentPath = new File(inputURL.uri.getPath()).getParent(); + if (!"/".equals(parentPath)) { + parentUri = inputURL.uri.buildUpon().path(parentPath + '/').build(); + } + return getEntryForLocalURL(LocalFilesystemURL.parse(parentUri)); + } + + protected LocalFilesystemURL makeDestinationURL(String newName, LocalFilesystemURL srcURL, LocalFilesystemURL destURL, boolean isDirectory) { + // I know this looks weird but it is to work around a JSON bug. + if ("null".equals(newName) || "".equals(newName)) { + newName = srcURL.uri.getLastPathSegment();; + } + + String newDest = destURL.uri.toString(); + if (newDest.endsWith("/")) { + newDest = newDest + newName; + } else { + newDest = newDest + "/" + newName; + } + if (isDirectory) { + newDest += '/'; + } + return LocalFilesystemURL.parse(newDest); + } + + /* Read a source URL (possibly from a different filesystem, srcFs,) and copy it to + * the destination URL on this filesystem, optionally with a new filename. + * If move is true, then this method should either perform an atomic move operation + * or remove the source file when finished. + */ + public JSONObject copyFileToURL(LocalFilesystemURL destURL, String newName, + Filesystem srcFs, LocalFilesystemURL srcURL, boolean move) throws IOException, InvalidModificationException, JSONException, NoModificationAllowedException, FileExistsException { + // First, check to see that we can do it + if (move && !srcFs.canRemoveFileAtLocalURL(srcURL)) { + throw new NoModificationAllowedException("Cannot move file at source URL"); + } + final LocalFilesystemURL destination = makeDestinationURL(newName, srcURL, destURL, srcURL.isDirectory); + + Uri srcNativeUri = srcFs.toNativeUri(srcURL); + + CordovaResourceApi.OpenForReadResult ofrr = resourceApi.openForRead(srcNativeUri); + OutputStream os = null; + try { + os = getOutputStreamForURL(destination); + } catch (IOException e) { + ofrr.inputStream.close(); + throw e; + } + // Closes streams. + resourceApi.copyResource(ofrr, os); + + if (move) { + srcFs.removeFileAtLocalURL(srcURL); + } + return getEntryForLocalURL(destination); + } + + public OutputStream getOutputStreamForURL(LocalFilesystemURL inputURL) throws IOException { + return resourceApi.openOutputStream(toNativeUri(inputURL)); + } + + public void readFileAtURL(LocalFilesystemURL inputURL, long start, long end, + ReadFileCallback readFileCallback) throws IOException { + CordovaResourceApi.OpenForReadResult ofrr = resourceApi.openForRead(toNativeUri(inputURL)); + if (end < 0) { + end = ofrr.length; + } + long numBytesToRead = end - start; + try { + if (start > 0) { + ofrr.inputStream.skip(start); + } + InputStream inputStream = ofrr.inputStream; + if (end < ofrr.length) { + inputStream = new LimitedInputStream(inputStream, numBytesToRead); + } + readFileCallback.handleData(inputStream, ofrr.mimeType); + } finally { + ofrr.inputStream.close(); + } + } + + abstract long writeToFileAtURL(LocalFilesystemURL inputURL, String data, int offset, + boolean isBinary) throws NoModificationAllowedException, IOException; + + abstract long truncateFileAtURL(LocalFilesystemURL inputURL, long size) + throws IOException, NoModificationAllowedException; + + // This method should return null if filesystem urls cannot be mapped to paths + abstract String filesystemPathForURL(LocalFilesystemURL url); + + abstract LocalFilesystemURL URLforFilesystemPath(String path); + + abstract boolean canRemoveFileAtLocalURL(LocalFilesystemURL inputURL); + + protected class LimitedInputStream extends FilterInputStream { + long numBytesToRead; + public LimitedInputStream(InputStream in, long numBytesToRead) { + super(in); + this.numBytesToRead = numBytesToRead; + } + @Override + public int read() throws IOException { + if (numBytesToRead <= 0) { + return -1; + } + numBytesToRead--; + return in.read(); + } + @Override + public int read(byte[] buffer, int byteOffset, int byteCount) throws IOException { + if (numBytesToRead <= 0) { + return -1; + } + int bytesToRead = byteCount; + if (byteCount > numBytesToRead) { + bytesToRead = (int)numBytesToRead; // Cast okay; long is less than int here. + } + int numBytesRead = in.read(buffer, byteOffset, bytesToRead); + numBytesToRead -= numBytesRead; + return numBytesRead; + } + } +} diff --git a/plugins/cordova-plugin-file/src/android/InvalidModificationException.java b/plugins/cordova-plugin-file/src/android/InvalidModificationException.java new file mode 100644 index 0000000..8f6bec5 --- /dev/null +++ b/plugins/cordova-plugin-file/src/android/InvalidModificationException.java @@ -0,0 +1,30 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. +*/ + + +package org.apache.cordova.file; + +@SuppressWarnings("serial") +public class InvalidModificationException extends Exception { + + public InvalidModificationException(String message) { + super(message); + } + +} diff --git a/plugins/cordova-plugin-file/src/android/LocalFilesystem.java b/plugins/cordova-plugin-file/src/android/LocalFilesystem.java new file mode 100644 index 0000000..051f994 --- /dev/null +++ b/plugins/cordova-plugin-file/src/android/LocalFilesystem.java @@ -0,0 +1,513 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. + */ +package org.apache.cordova.file; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.RandomAccessFile; +import java.nio.channels.FileChannel; +import org.apache.cordova.CordovaResourceApi; +import org.json.JSONException; +import org.json.JSONObject; + +import android.os.Build; +import android.os.Environment; +import android.util.Base64; +import android.net.Uri; +import android.content.Context; +import android.content.Intent; + +import java.nio.charset.Charset; + +public class LocalFilesystem extends Filesystem { + private final Context context; + + public LocalFilesystem(String name, Context context, CordovaResourceApi resourceApi, File fsRoot) { + super(Uri.fromFile(fsRoot).buildUpon().appendEncodedPath("").build(), name, resourceApi); + this.context = context; + } + + public String filesystemPathForFullPath(String fullPath) { + return new File(rootUri.getPath(), fullPath).toString(); + } + + @Override + public String filesystemPathForURL(LocalFilesystemURL url) { + return filesystemPathForFullPath(url.path); + } + + private String fullPathForFilesystemPath(String absolutePath) { + if (absolutePath != null && absolutePath.startsWith(rootUri.getPath())) { + return absolutePath.substring(rootUri.getPath().length() - 1); + } + return null; + } + + @Override + public Uri toNativeUri(LocalFilesystemURL inputURL) { + return nativeUriForFullPath(inputURL.path); + } + + @Override + public LocalFilesystemURL toLocalUri(Uri inputURL) { + if (!"file".equals(inputURL.getScheme())) { + return null; + } + File f = new File(inputURL.getPath()); + // Removes and duplicate /s (e.g. file:///a//b/c) + Uri resolvedUri = Uri.fromFile(f); + String rootUriNoTrailingSlash = rootUri.getEncodedPath(); + rootUriNoTrailingSlash = rootUriNoTrailingSlash.substring(0, rootUriNoTrailingSlash.length() - 1); + if (!resolvedUri.getEncodedPath().startsWith(rootUriNoTrailingSlash)) { + return null; + } + String subPath = resolvedUri.getEncodedPath().substring(rootUriNoTrailingSlash.length()); + // Strip leading slash + if (!subPath.isEmpty()) { + subPath = subPath.substring(1); + } + Uri.Builder b = new Uri.Builder() + .scheme(LocalFilesystemURL.FILESYSTEM_PROTOCOL) + .authority("localhost") + .path(name); + if (!subPath.isEmpty()) { + b.appendEncodedPath(subPath); + } + if (f.isDirectory()) { + // Add trailing / for directories. + b.appendEncodedPath(""); + } + return LocalFilesystemURL.parse(b.build()); + } + + @Override + public LocalFilesystemURL URLforFilesystemPath(String path) { + return localUrlforFullPath(fullPathForFilesystemPath(path)); + } + + @Override + public JSONObject getFileForLocalURL(LocalFilesystemURL inputURL, + String path, JSONObject options, boolean directory) throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException { + boolean create = false; + boolean exclusive = false; + + if (options != null) { + create = options.optBoolean("create"); + if (create) { + exclusive = options.optBoolean("exclusive"); + } + } + + // Check for a ":" character in the file to line up with BB and iOS + if (path.contains(":")) { + throw new EncodingException("This path has an invalid \":\" in it."); + } + + LocalFilesystemURL requestedURL; + + // Check whether the supplied path is absolute or relative + if (directory && !path.endsWith("/")) { + path += "/"; + } + if (path.startsWith("/")) { + requestedURL = localUrlforFullPath(normalizePath(path)); + } else { + requestedURL = localUrlforFullPath(normalizePath(inputURL.path + "/" + path)); + } + + File fp = new File(this.filesystemPathForURL(requestedURL)); + + if (create) { + if (exclusive && fp.exists()) { + throw new FileExistsException("create/exclusive fails"); + } + if (directory) { + fp.mkdir(); + } else { + fp.createNewFile(); + } + if (!fp.exists()) { + throw new FileExistsException("create fails"); + } + } + else { + if (!fp.exists()) { + throw new FileNotFoundException("path does not exist"); + } + if (directory) { + if (fp.isFile()) { + throw new TypeMismatchException("path doesn't exist or is file"); + } + } else { + if (fp.isDirectory()) { + throw new TypeMismatchException("path doesn't exist or is directory"); + } + } + } + + // Return the directory + return makeEntryForURL(requestedURL); + } + + @Override + public boolean removeFileAtLocalURL(LocalFilesystemURL inputURL) throws InvalidModificationException { + + File fp = new File(filesystemPathForURL(inputURL)); + + // You can't delete a directory that is not empty + if (fp.isDirectory() && fp.list().length > 0) { + throw new InvalidModificationException("You can't delete a directory that is not empty."); + } + + return fp.delete(); + } + + @Override + public boolean exists(LocalFilesystemURL inputURL) { + File fp = new File(filesystemPathForURL(inputURL)); + return fp.exists(); + } + + @Override + public long getFreeSpaceInBytes() { + return DirectoryManager.getFreeSpaceInBytes(rootUri.getPath()); + } + + @Override + public boolean recursiveRemoveFileAtLocalURL(LocalFilesystemURL inputURL) throws FileExistsException { + File directory = new File(filesystemPathForURL(inputURL)); + return removeDirRecursively(directory); + } + + protected boolean removeDirRecursively(File directory) throws FileExistsException { + if (directory.isDirectory()) { + for (File file : directory.listFiles()) { + removeDirRecursively(file); + } + } + + if (!directory.delete()) { + throw new FileExistsException("could not delete: " + directory.getName()); + } else { + return true; + } + } + + @Override + public LocalFilesystemURL[] listChildren(LocalFilesystemURL inputURL) throws FileNotFoundException { + File fp = new File(filesystemPathForURL(inputURL)); + + if (!fp.exists()) { + // The directory we are listing doesn't exist so we should fail. + throw new FileNotFoundException(); + } + + File[] files = fp.listFiles(); + if (files == null) { + // inputURL is a directory + return null; + } + LocalFilesystemURL[] entries = new LocalFilesystemURL[files.length]; + for (int i = 0; i < files.length; i++) { + entries[i] = URLforFilesystemPath(files[i].getPath()); + } + + return entries; + } + + @Override + public JSONObject getFileMetadataForLocalURL(LocalFilesystemURL inputURL) throws FileNotFoundException { + File file = new File(filesystemPathForURL(inputURL)); + + if (!file.exists()) { + throw new FileNotFoundException("File at " + inputURL.uri + " does not exist."); + } + + JSONObject metadata = new JSONObject(); + try { + // Ensure that directories report a size of 0 + metadata.put("size", file.isDirectory() ? 0 : file.length()); + metadata.put("type", resourceApi.getMimeType(Uri.fromFile(file))); + metadata.put("name", file.getName()); + metadata.put("fullPath", inputURL.path); + metadata.put("lastModifiedDate", file.lastModified()); + } catch (JSONException e) { + return null; + } + return metadata; + } + + private void copyFile(Filesystem srcFs, LocalFilesystemURL srcURL, File destFile, boolean move) throws IOException, InvalidModificationException, NoModificationAllowedException { + if (move) { + String realSrcPath = srcFs.filesystemPathForURL(srcURL); + if (realSrcPath != null) { + File srcFile = new File(realSrcPath); + if (srcFile.renameTo(destFile)) { + return; + } + // Trying to rename the file failed. Possibly because we moved across file system on the device. + } + } + + CordovaResourceApi.OpenForReadResult offr = resourceApi.openForRead(srcFs.toNativeUri(srcURL)); + copyResource(offr, new FileOutputStream(destFile)); + + if (move) { + srcFs.removeFileAtLocalURL(srcURL); + } + } + + private void copyDirectory(Filesystem srcFs, LocalFilesystemURL srcURL, File dstDir, boolean move) throws IOException, NoModificationAllowedException, InvalidModificationException, FileExistsException { + if (move) { + String realSrcPath = srcFs.filesystemPathForURL(srcURL); + if (realSrcPath != null) { + File srcDir = new File(realSrcPath); + // If the destination directory already exists and is empty then delete it. This is according to spec. + if (dstDir.exists()) { + if (dstDir.list().length > 0) { + throw new InvalidModificationException("directory is not empty"); + } + dstDir.delete(); + } + // Try to rename the directory + if (srcDir.renameTo(dstDir)) { + return; + } + // Trying to rename the file failed. Possibly because we moved across file system on the device. + } + } + + if (dstDir.exists()) { + if (dstDir.list().length > 0) { + throw new InvalidModificationException("directory is not empty"); + } + } else { + if (!dstDir.mkdir()) { + // If we can't create the directory then fail + throw new NoModificationAllowedException("Couldn't create the destination directory"); + } + } + + LocalFilesystemURL[] children = srcFs.listChildren(srcURL); + for (LocalFilesystemURL childLocalUrl : children) { + File target = new File(dstDir, new File(childLocalUrl.path).getName()); + if (childLocalUrl.isDirectory) { + copyDirectory(srcFs, childLocalUrl, target, false); + } else { + copyFile(srcFs, childLocalUrl, target, false); + } + } + + if (move) { + srcFs.recursiveRemoveFileAtLocalURL(srcURL); + } + } + + @Override + public JSONObject copyFileToURL(LocalFilesystemURL destURL, String newName, + Filesystem srcFs, LocalFilesystemURL srcURL, boolean move) throws IOException, InvalidModificationException, JSONException, NoModificationAllowedException, FileExistsException { + + // Check to see if the destination directory exists + String newParent = this.filesystemPathForURL(destURL); + File destinationDir = new File(newParent); + if (!destinationDir.exists()) { + // The destination does not exist so we should fail. + throw new FileNotFoundException("The source does not exist"); + } + + // Figure out where we should be copying to + final LocalFilesystemURL destinationURL = makeDestinationURL(newName, srcURL, destURL, srcURL.isDirectory); + + Uri dstNativeUri = toNativeUri(destinationURL); + Uri srcNativeUri = srcFs.toNativeUri(srcURL); + // Check to see if source and destination are the same file + if (dstNativeUri.equals(srcNativeUri)) { + throw new InvalidModificationException("Can't copy onto itself"); + } + + if (move && !srcFs.canRemoveFileAtLocalURL(srcURL)) { + throw new InvalidModificationException("Source URL is read-only (cannot move)"); + } + + File destFile = new File(dstNativeUri.getPath()); + if (destFile.exists()) { + if (!srcURL.isDirectory && destFile.isDirectory()) { + throw new InvalidModificationException("Can't copy/move a file to an existing directory"); + } else if (srcURL.isDirectory && destFile.isFile()) { + throw new InvalidModificationException("Can't copy/move a directory to an existing file"); + } + } + + if (srcURL.isDirectory) { + // E.g. Copy /sdcard/myDir to /sdcard/myDir/backup + if (dstNativeUri.toString().startsWith(srcNativeUri.toString() + '/')) { + throw new InvalidModificationException("Can't copy directory into itself"); + } + copyDirectory(srcFs, srcURL, destFile, move); + } else { + copyFile(srcFs, srcURL, destFile, move); + } + return makeEntryForURL(destinationURL); + } + + @Override + public long writeToFileAtURL(LocalFilesystemURL inputURL, String data, + int offset, boolean isBinary) throws IOException, NoModificationAllowedException { + + boolean append = false; + if (offset > 0) { + this.truncateFileAtURL(inputURL, offset); + append = true; + } + + byte[] rawData; + if (isBinary) { + rawData = Base64.decode(data, Base64.DEFAULT); + } else { + rawData = data.getBytes(Charset.defaultCharset()); + } + ByteArrayInputStream in = new ByteArrayInputStream(rawData); + try + { + byte buff[] = new byte[rawData.length]; + String absolutePath = filesystemPathForURL(inputURL); + FileOutputStream out = new FileOutputStream(absolutePath, append); + try { + in.read(buff, 0, buff.length); + out.write(buff, 0, rawData.length); + out.flush(); + } finally { + // Always close the output + out.close(); + } + if (isPublicDirectory(absolutePath)) { + broadcastNewFile(Uri.fromFile(new File(absolutePath))); + } + } + catch (NullPointerException e) + { + // This is a bug in the Android implementation of the Java Stack + NoModificationAllowedException realException = new NoModificationAllowedException(inputURL.toString()); + realException.initCause(e); + throw realException; + } + + return rawData.length; + } + + private boolean isPublicDirectory(String absolutePath) { + // TODO: should expose a way to scan app's private files (maybe via a flag). + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + // Lollipop has a bug where SD cards are null. + for (File f : context.getExternalMediaDirs()) { + if(f != null && absolutePath.startsWith(f.getAbsolutePath())) { + return true; + } + } + } + + String extPath = Environment.getExternalStorageDirectory().getAbsolutePath(); + return absolutePath.startsWith(extPath); + } + + /** + * Send broadcast of new file so files appear over MTP + */ + private void broadcastNewFile(Uri nativeUri) { + Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, nativeUri); + context.sendBroadcast(intent); + } + + @Override + public long truncateFileAtURL(LocalFilesystemURL inputURL, long size) throws IOException { + File file = new File(filesystemPathForURL(inputURL)); + + if (!file.exists()) { + throw new FileNotFoundException("File at " + inputURL.uri + " does not exist."); + } + + RandomAccessFile raf = new RandomAccessFile(filesystemPathForURL(inputURL), "rw"); + try { + if (raf.length() >= size) { + FileChannel channel = raf.getChannel(); + channel.truncate(size); + return size; + } + + return raf.length(); + } finally { + raf.close(); + } + + + } + + @Override + public boolean canRemoveFileAtLocalURL(LocalFilesystemURL inputURL) { + String path = filesystemPathForURL(inputURL); + File file = new File(path); + return file.exists(); + } + + // This is a copy & paste from CordovaResource API that is required since CordovaResourceApi + // has a bug pre-4.0.0. + // TODO: Once cordova-android@4.0.0 is released, delete this copy and make the plugin depend on + // 4.0.0 with an engine tag. + private static void copyResource(CordovaResourceApi.OpenForReadResult input, OutputStream outputStream) throws IOException { + try { + InputStream inputStream = input.inputStream; + if (inputStream instanceof FileInputStream && outputStream instanceof FileOutputStream) { + FileChannel inChannel = ((FileInputStream)input.inputStream).getChannel(); + FileChannel outChannel = ((FileOutputStream)outputStream).getChannel(); + long offset = 0; + long length = input.length; + if (input.assetFd != null) { + offset = input.assetFd.getStartOffset(); + } + // transferFrom()'s 2nd arg is a relative position. Need to set the absolute + // position first. + inChannel.position(offset); + outChannel.transferFrom(inChannel, 0, length); + } else { + final int BUFFER_SIZE = 8192; + byte[] buffer = new byte[BUFFER_SIZE]; + + for (;;) { + int bytesRead = inputStream.read(buffer, 0, BUFFER_SIZE); + + if (bytesRead <= 0) { + break; + } + outputStream.write(buffer, 0, bytesRead); + } + } + } finally { + input.inputStream.close(); + if (outputStream != null) { + outputStream.close(); + } + } + } +} diff --git a/plugins/cordova-plugin-file/src/android/LocalFilesystemURL.java b/plugins/cordova-plugin-file/src/android/LocalFilesystemURL.java new file mode 100644 index 0000000..b96b6ee --- /dev/null +++ b/plugins/cordova-plugin-file/src/android/LocalFilesystemURL.java @@ -0,0 +1,64 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. + */ +package org.apache.cordova.file; + +import android.net.Uri; + +public class LocalFilesystemURL { + + public static final String FILESYSTEM_PROTOCOL = "cdvfile"; + + public final Uri uri; + public final String fsName; + public final String path; + public final boolean isDirectory; + + private LocalFilesystemURL(Uri uri, String fsName, String fsPath, boolean isDirectory) { + this.uri = uri; + this.fsName = fsName; + this.path = fsPath; + this.isDirectory = isDirectory; + } + + public static LocalFilesystemURL parse(Uri uri) { + if (!FILESYSTEM_PROTOCOL.equals(uri.getScheme())) { + return null; + } + String path = uri.getPath(); + if (path.length() < 1) { + return null; + } + int firstSlashIdx = path.indexOf('/', 1); + if (firstSlashIdx < 0) { + return null; + } + String fsName = path.substring(1, firstSlashIdx); + path = path.substring(firstSlashIdx); + boolean isDirectory = path.charAt(path.length() - 1) == '/'; + return new LocalFilesystemURL(uri, fsName, path, isDirectory); + } + + public static LocalFilesystemURL parse(String uri) { + return parse(Uri.parse(uri)); + } + + public String toString() { + return uri.toString(); + } +} diff --git a/plugins/cordova-plugin-file/src/android/NoModificationAllowedException.java b/plugins/cordova-plugin-file/src/android/NoModificationAllowedException.java new file mode 100644 index 0000000..627eafb --- /dev/null +++ b/plugins/cordova-plugin-file/src/android/NoModificationAllowedException.java @@ -0,0 +1,29 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. +*/ + +package org.apache.cordova.file; + +@SuppressWarnings("serial") +public class NoModificationAllowedException extends Exception { + + public NoModificationAllowedException(String message) { + super(message); + } + +} diff --git a/plugins/cordova-plugin-file/src/android/PendingRequests.java b/plugins/cordova-plugin-file/src/android/PendingRequests.java new file mode 100644 index 0000000..23d6d73 --- /dev/null +++ b/plugins/cordova-plugin-file/src/android/PendingRequests.java @@ -0,0 +1,94 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. +*/ +package org.apache.cordova.file; + +import android.util.SparseArray; + +import org.apache.cordova.CallbackContext; + +/** + * Holds pending runtime permission requests + */ +class PendingRequests { + private int currentReqId = 0; + private SparseArray requests = new SparseArray(); + + /** + * Creates a request and adds it to the array of pending requests. Each created request gets a + * unique result code for use with requestPermission() + * @param rawArgs The raw arguments passed to the plugin + * @param action The action this request corresponds to (get file, etc.) + * @param callbackContext The CallbackContext for this plugin call + * @return The request code that can be used to retrieve the Request object + */ + public synchronized int createRequest(String rawArgs, int action, CallbackContext callbackContext) { + Request req = new Request(rawArgs, action, callbackContext); + requests.put(req.requestCode, req); + return req.requestCode; + } + + /** + * Gets the request corresponding to this request code and removes it from the pending requests + * @param requestCode The request code for the desired request + * @return The request corresponding to the given request code or null if such a + * request is not found + */ + public synchronized Request getAndRemove(int requestCode) { + Request result = requests.get(requestCode); + requests.remove(requestCode); + return result; + } + + /** + * Holds the options and CallbackContext for a call made to the plugin. + */ + public class Request { + + // Unique int used to identify this request in any Android permission callback + private int requestCode; + + // Action to be performed after permission request result + private int action; + + // Raw arguments passed to plugin + private String rawArgs; + + // The callback context for this plugin request + private CallbackContext callbackContext; + + private Request(String rawArgs, int action, CallbackContext callbackContext) { + this.rawArgs = rawArgs; + this.action = action; + this.callbackContext = callbackContext; + this.requestCode = currentReqId ++; + } + + public int getAction() { + return this.action; + } + + public String getRawArgs() { + return rawArgs; + } + + public CallbackContext getCallbackContext() { + return callbackContext; + } + } +} diff --git a/plugins/cordova-plugin-file/src/android/TypeMismatchException.java b/plugins/cordova-plugin-file/src/android/TypeMismatchException.java new file mode 100644 index 0000000..1315f9a --- /dev/null +++ b/plugins/cordova-plugin-file/src/android/TypeMismatchException.java @@ -0,0 +1,30 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. +*/ + + +package org.apache.cordova.file; + +@SuppressWarnings("serial") +public class TypeMismatchException extends Exception { + + public TypeMismatchException(String message) { + super(message); + } + +} diff --git a/plugins/cordova-plugin-file/src/android/build-extras.gradle b/plugins/cordova-plugin-file/src/android/build-extras.gradle new file mode 100644 index 0000000..a0a7844 --- /dev/null +++ b/plugins/cordova-plugin-file/src/android/build-extras.gradle @@ -0,0 +1,47 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. + */ +ext.postBuildExtras = { + def inAssetsDir = file("assets") + def outAssetsDir = inAssetsDir + def outFile = new File(outAssetsDir, "cdvasset.manifest") + + def newTask = task("cdvCreateAssetManifest") << { + def contents = new HashMap() + def sizes = new HashMap() + contents[""] = inAssetsDir.list() + def tree = fileTree(dir: inAssetsDir) + tree.visit { fileDetails -> + if (fileDetails.isDirectory()) { + contents[fileDetails.relativePath.toString()] = fileDetails.file.list() + } else { + sizes[fileDetails.relativePath.toString()] = fileDetails.file.length() + } + } + + outAssetsDir.mkdirs() + outFile.withObjectOutputStream { oos -> + oos.writeObject(contents) + oos.writeObject(sizes) + } + } + newTask.inputs.dir inAssetsDir + newTask.outputs.file outFile + def preBuildTask = tasks["preBuild"] + preBuildTask.dependsOn(newTask) +} diff --git a/plugins/cordova-plugin-file/src/blackberry10/index.js b/plugins/cordova-plugin-file/src/blackberry10/index.js new file mode 100644 index 0000000..e995986 --- /dev/null +++ b/plugins/cordova-plugin-file/src/blackberry10/index.js @@ -0,0 +1,47 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ + +/* global PluginResult */ + +module.exports = { + setSandbox : function (success, fail, args, env) { + require("lib/webview").setSandbox(JSON.parse(decodeURIComponent(args[0]))); + new PluginResult(args, env).ok(); + }, + + getHomePath: function (success, fail, args, env) { + var homeDir = window.qnx.webplatform.getApplication().getEnv("HOME"); + new PluginResult(args, env).ok(homeDir); + }, + + requestAllPaths: function (success, fail, args, env) { + var homeDir = 'file://' + window.qnx.webplatform.getApplication().getEnv("HOME").replace('/data', ''), + paths = { + applicationDirectory: homeDir + '/app/native/', + applicationStorageDirectory: homeDir + '/', + dataDirectory: homeDir + '/data/webviews/webfs/persistent/local__0/', + cacheDirectory: homeDir + '/data/webviews/webfs/temporary/local__0/', + externalRootDirectory: 'file:///accounts/1000/removable/sdcard/', + sharedDirectory: homeDir + '/shared/' + }; + success(paths); + } +}; diff --git a/plugins/cordova-plugin-file/src/browser/FileProxy.js b/plugins/cordova-plugin-file/src/browser/FileProxy.js new file mode 100644 index 0000000..2d937f4 --- /dev/null +++ b/plugins/cordova-plugin-file/src/browser/FileProxy.js @@ -0,0 +1,984 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +(function() { + /*global require, exports, module*/ + /*global FILESYSTEM_PREFIX*/ + /*global IDBKeyRange*/ + + /* Heavily based on https://github.com/ebidel/idb.filesystem.js */ + + // For chrome we don't need to implement proxy methods + // All functionality can be accessed natively. + if (require('./isChrome')()) { + var pathsPrefix = { + // Read-only directory where the application is installed. + applicationDirectory: location.origin + "/", + // Where to put app-specific data files. + dataDirectory: 'filesystem:file:///persistent/', + // Cached files that should survive app restarts. + // Apps should not rely on the OS to delete files in here. + cacheDirectory: 'filesystem:file:///temporary/', + }; + + exports.requestAllPaths = function(successCallback) { + successCallback(pathsPrefix); + }; + + require("cordova/exec/proxy").add("File", module.exports); + return; + } + + var LocalFileSystem = require('./LocalFileSystem'), + FileSystem = require('./FileSystem'), + FileEntry = require('./FileEntry'), + FileError = require('./FileError'), + DirectoryEntry = require('./DirectoryEntry'), + File = require('./File'); + + (function(exports, global) { + var indexedDB = global.indexedDB || global.mozIndexedDB; + if (!indexedDB) { + throw "Firefox OS File plugin: indexedDB not supported"; + } + + var fs_ = null; + + var idb_ = {}; + idb_.db = null; + var FILE_STORE_ = 'entries'; + + var DIR_SEPARATOR = '/'; + + var pathsPrefix = { + // Read-only directory where the application is installed. + applicationDirectory: location.origin + "/", + // Where to put app-specific data files. + dataDirectory: 'file:///persistent/', + // Cached files that should survive app restarts. + // Apps should not rely on the OS to delete files in here. + cacheDirectory: 'file:///temporary/', + }; + + var unicodeLastChar = 65535; + + /*** Exported functionality ***/ + + exports.requestFileSystem = function(successCallback, errorCallback, args) { + var type = args[0]; + // Size is ignored since IDB filesystem size depends + // on browser implementation and can't be set up by user + var size = args[1]; // jshint ignore: line + + if (type !== LocalFileSystem.TEMPORARY && type !== LocalFileSystem.PERSISTENT) { + if (errorCallback) { + errorCallback(FileError.INVALID_MODIFICATION_ERR); + } + return; + } + + var name = type === LocalFileSystem.TEMPORARY ? 'temporary' : 'persistent'; + var storageName = (location.protocol + location.host).replace(/:/g, '_'); + + var root = new DirectoryEntry('', DIR_SEPARATOR); + fs_ = new FileSystem(name, root); + + idb_.open(storageName, function() { + successCallback(fs_); + }, errorCallback); + }; + + // Overridden by Android, BlackBerry 10 and iOS to populate fsMap + require('./fileSystems').getFs = function(name, callback) { + callback(new FileSystem(name, fs_.root)); + }; + + // list a directory's contents (files and folders). + exports.readEntries = function(successCallback, errorCallback, args) { + var fullPath = args[0]; + + if (typeof successCallback !== 'function') { + throw Error('Expected successCallback argument.'); + } + + var path = resolveToFullPath_(fullPath); + + exports.getDirectory(function() { + idb_.getAllEntries(path.fullPath + DIR_SEPARATOR, path.storagePath, function(entries) { + successCallback(entries); + }, errorCallback); + }, function() { + if (errorCallback) { + errorCallback(FileError.NOT_FOUND_ERR); + } + }, [path.storagePath, path.fullPath, {create: false}]); + }; + + exports.getFile = function(successCallback, errorCallback, args) { + var fullPath = args[0]; + var path = args[1]; + var options = args[2] || {}; + + // Create an absolute path if we were handed a relative one. + path = resolveToFullPath_(fullPath, path); + + idb_.get(path.storagePath, function(fileEntry) { + if (options.create === true && options.exclusive === true && fileEntry) { + // If create and exclusive are both true, and the path already exists, + // getFile must fail. + + if (errorCallback) { + errorCallback(FileError.PATH_EXISTS_ERR); + } + } else if (options.create === true && !fileEntry) { + // If create is true, the path doesn't exist, and no other error occurs, + // getFile must create it as a zero-length file and return a corresponding + // FileEntry. + var newFileEntry = new FileEntry(path.fileName, path.fullPath, new FileSystem(path.fsName, fs_.root)); + + newFileEntry.file_ = new MyFile({ + size: 0, + name: newFileEntry.name, + lastModifiedDate: new Date(), + storagePath: path.storagePath + }); + + idb_.put(newFileEntry, path.storagePath, successCallback, errorCallback); + } else if (options.create === true && fileEntry) { + if (fileEntry.isFile) { + // Overwrite file, delete then create new. + idb_['delete'](path.storagePath, function() { + var newFileEntry = new FileEntry(path.fileName, path.fullPath, new FileSystem(path.fsName, fs_.root)); + + newFileEntry.file_ = new MyFile({ + size: 0, + name: newFileEntry.name, + lastModifiedDate: new Date(), + storagePath: path.storagePath + }); + + idb_.put(newFileEntry, path.storagePath, successCallback, errorCallback); + }, errorCallback); + } else { + if (errorCallback) { + errorCallback(FileError.INVALID_MODIFICATION_ERR); + } + } + } else if ((!options.create || options.create === false) && !fileEntry) { + // If create is not true and the path doesn't exist, getFile must fail. + if (errorCallback) { + errorCallback(FileError.NOT_FOUND_ERR); + } + } else if ((!options.create || options.create === false) && fileEntry && + fileEntry.isDirectory) { + // If create is not true and the path exists, but is a directory, getFile + // must fail. + if (errorCallback) { + errorCallback(FileError.TYPE_MISMATCH_ERR); + } + } else { + // Otherwise, if no other error occurs, getFile must return a FileEntry + // corresponding to path. + + successCallback(fileEntryFromIdbEntry(fileEntry)); + } + }, errorCallback); + }; + + exports.getFileMetadata = function(successCallback, errorCallback, args) { + var fullPath = args[0]; + + exports.getFile(function(fileEntry) { + successCallback(new File(fileEntry.file_.name, fileEntry.fullPath, '', fileEntry.file_.lastModifiedDate, + fileEntry.file_.size)); + }, errorCallback, [fullPath, null]); + }; + + exports.getMetadata = function(successCallback, errorCallback, args) { + exports.getFile(function (fileEntry) { + successCallback( + { + modificationTime: fileEntry.file_.lastModifiedDate, + size: fileEntry.file_.lastModifiedDate + }); + }, errorCallback, args); + }; + + exports.setMetadata = function(successCallback, errorCallback, args) { + var fullPath = args[0]; + var metadataObject = args[1]; + + exports.getFile(function (fileEntry) { + fileEntry.file_.lastModifiedDate = metadataObject.modificationTime; + idb_.put(fileEntry, fileEntry.file_.storagePath, successCallback, errorCallback); + }, errorCallback, [fullPath, null]); + }; + + exports.write = function(successCallback, errorCallback, args) { + var fileName = args[0], + data = args[1], + position = args[2], + isBinary = args[3]; // jshint ignore: line + + if (!data) { + if (errorCallback) { + errorCallback(FileError.INVALID_MODIFICATION_ERR); + } + return; + } + + if (typeof data === 'string' || data instanceof String) { + data = new Blob([data]); + } + + exports.getFile(function(fileEntry) { + var blob_ = fileEntry.file_.blob_; + + if (!blob_) { + blob_ = new Blob([data], {type: data.type}); + } else { + // Calc the head and tail fragments + var head = blob_.slice(0, position); + var tail = blob_.slice(position + (data.size || data.byteLength)); + + // Calc the padding + var padding = position - head.size; + if (padding < 0) { + padding = 0; + } + + // Do the "write". In fact, a full overwrite of the Blob. + blob_ = new Blob([head, new Uint8Array(padding), data, tail], + {type: data.type}); + } + + // Set the blob we're writing on this file entry so we can recall it later. + fileEntry.file_.blob_ = blob_; + fileEntry.file_.lastModifiedDate = new Date() || null; + fileEntry.file_.size = blob_.size; + fileEntry.file_.name = blob_.name; + fileEntry.file_.type = blob_.type; + + idb_.put(fileEntry, fileEntry.file_.storagePath, function() { + successCallback(data.size || data.byteLength); + }, errorCallback); + }, errorCallback, [fileName, null]); + }; + + exports.readAsText = function(successCallback, errorCallback, args) { + var fileName = args[0], + enc = args[1], + startPos = args[2], + endPos = args[3]; + + readAs('text', fileName, enc, startPos, endPos, successCallback, errorCallback); + }; + + exports.readAsDataURL = function(successCallback, errorCallback, args) { + var fileName = args[0], + startPos = args[1], + endPos = args[2]; + + readAs('dataURL', fileName, null, startPos, endPos, successCallback, errorCallback); + }; + + exports.readAsBinaryString = function(successCallback, errorCallback, args) { + var fileName = args[0], + startPos = args[1], + endPos = args[2]; + + readAs('binaryString', fileName, null, startPos, endPos, successCallback, errorCallback); + }; + + exports.readAsArrayBuffer = function(successCallback, errorCallback, args) { + var fileName = args[0], + startPos = args[1], + endPos = args[2]; + + readAs('arrayBuffer', fileName, null, startPos, endPos, successCallback, errorCallback); + }; + + exports.removeRecursively = exports.remove = function(successCallback, errorCallback, args) { + if (typeof successCallback !== 'function') { + throw Error('Expected successCallback argument.'); + } + + var fullPath = resolveToFullPath_(args[0]).storagePath; + if (fullPath === pathsPrefix.cacheDirectory || fullPath === pathsPrefix.dataDirectory) { + errorCallback(FileError.NO_MODIFICATION_ALLOWED_ERR); + return; + } + + function deleteEntry(isDirectory) { + // TODO: This doesn't protect against directories that have content in it. + // Should throw an error instead if the dirEntry is not empty. + idb_['delete'](fullPath, function() { + successCallback(); + }, function() { + if (errorCallback) { errorCallback(); } + }, isDirectory); + } + + // We need to to understand what we are deleting: + exports.getDirectory(function(entry) { + deleteEntry(entry.isDirectory); + }, function(){ + //DirectoryEntry was already deleted or entry is FileEntry + deleteEntry(false); + }, [fullPath, null, {create: false}]); + }; + + exports.getDirectory = function(successCallback, errorCallback, args) { + var fullPath = args[0]; + var path = args[1]; + var options = args[2]; + + // Create an absolute path if we were handed a relative one. + path = resolveToFullPath_(fullPath, path); + + idb_.get(path.storagePath, function(folderEntry) { + if (!options) { + options = {}; + } + + if (options.create === true && options.exclusive === true && folderEntry) { + // If create and exclusive are both true, and the path already exists, + // getDirectory must fail. + if (errorCallback) { + errorCallback(FileError.PATH_EXISTS_ERR); + } + // There is a strange bug in mobilespec + FF, which results in coming to multiple else-if's + // so we are shielding from it with returns. + return; + } + + if (options.create === true && !folderEntry) { + // If create is true, the path doesn't exist, and no other error occurs, + // getDirectory must create it as a zero-length file and return a corresponding + // MyDirectoryEntry. + var dirEntry = new DirectoryEntry(path.fileName, path.fullPath, new FileSystem(path.fsName, fs_.root)); + + idb_.put(dirEntry, path.storagePath, successCallback, errorCallback); + return; + } + + if (options.create === true && folderEntry) { + + if (folderEntry.isDirectory) { + // IDB won't save methods, so we need re-create the MyDirectoryEntry. + successCallback(new DirectoryEntry(folderEntry.name, folderEntry.fullPath, folderEntry.filesystem)); + } else { + if (errorCallback) { + errorCallback(FileError.INVALID_MODIFICATION_ERR); + } + } + return; + } + + if ((!options.create || options.create === false) && !folderEntry) { + // Handle root special. It should always exist. + if (path.fullPath === DIR_SEPARATOR) { + successCallback(fs_.root); + return; + } + + // If create is not true and the path doesn't exist, getDirectory must fail. + if (errorCallback) { + errorCallback(FileError.NOT_FOUND_ERR); + } + + return; + } + if ((!options.create || options.create === false) && folderEntry && folderEntry.isFile) { + // If create is not true and the path exists, but is a file, getDirectory + // must fail. + if (errorCallback) { + errorCallback(FileError.TYPE_MISMATCH_ERR); + } + return; + } + + // Otherwise, if no other error occurs, getDirectory must return a + // MyDirectoryEntry corresponding to path. + + // IDB won't' save methods, so we need re-create MyDirectoryEntry. + successCallback(new DirectoryEntry(folderEntry.name, folderEntry.fullPath, folderEntry.filesystem)); + }, errorCallback); + }; + + exports.getParent = function(successCallback, errorCallback, args) { + if (typeof successCallback !== 'function') { + throw Error('Expected successCallback argument.'); + } + + var fullPath = args[0]; + //fullPath is like this: + //file:///persistent/path/to/file or + //file:///persistent/path/to/directory/ + + if (fullPath === DIR_SEPARATOR || fullPath === pathsPrefix.cacheDirectory || + fullPath === pathsPrefix.dataDirectory) { + successCallback(fs_.root); + return; + } + + //To delete all slashes at the end + while (fullPath[fullPath.length - 1] === '/') { + fullPath = fullPath.substr(0, fullPath.length - 1); + } + + var pathArr = fullPath.split(DIR_SEPARATOR); + pathArr.pop(); + var parentName = pathArr.pop(); + var path = pathArr.join(DIR_SEPARATOR) + DIR_SEPARATOR; + + //To get parent of root files + var joined = path + parentName + DIR_SEPARATOR;//is like this: file:///persistent/ + if (joined === pathsPrefix.cacheDirectory || joined === pathsPrefix.dataDirectory) { + exports.getDirectory(successCallback, errorCallback, [joined, DIR_SEPARATOR, {create: false}]); + return; + } + + exports.getDirectory(successCallback, errorCallback, [path, parentName, {create: false}]); + }; + + exports.copyTo = function(successCallback, errorCallback, args) { + var srcPath = args[0]; + var parentFullPath = args[1]; + var name = args[2]; + + if (name.indexOf('/') !== -1 || srcPath === parentFullPath + name) { + if (errorCallback) { + errorCallback(FileError.INVALID_MODIFICATION_ERR); + } + + return; + } + + // Read src file + exports.getFile(function(srcFileEntry) { + + var path = resolveToFullPath_(parentFullPath); + //Check directory + exports.getDirectory(function() { + + // Create dest file + exports.getFile(function(dstFileEntry) { + + exports.write(function() { + successCallback(dstFileEntry); + }, errorCallback, [dstFileEntry.file_.storagePath, srcFileEntry.file_.blob_, 0]); + + }, errorCallback, [parentFullPath, name, {create: true}]); + + }, function() { if (errorCallback) { errorCallback(FileError.NOT_FOUND_ERR); }}, + [path.storagePath, null, {create:false}]); + + }, errorCallback, [srcPath, null]); + }; + + exports.moveTo = function(successCallback, errorCallback, args) { + var srcPath = args[0]; + // parentFullPath and name parameters is ignored because + // args is being passed downstream to exports.copyTo method + var parentFullPath = args[1]; // jshint ignore: line + var name = args[2]; // jshint ignore: line + + exports.copyTo(function (fileEntry) { + + exports.remove(function () { + successCallback(fileEntry); + }, errorCallback, [srcPath]); + + }, errorCallback, args); + }; + + exports.resolveLocalFileSystemURI = function(successCallback, errorCallback, args) { + var path = args[0]; + + // Ignore parameters + if (path.indexOf('?') !== -1) { + path = String(path).split("?")[0]; + } + + // support for encodeURI + if (/\%5/g.test(path) || /\%20/g.test(path)) { + path = decodeURI(path); + } + + if (path.trim()[0] === '/') { + if (errorCallback) { + errorCallback(FileError.ENCODING_ERR); + } + return; + } + + //support for cdvfile + if (path.trim().substr(0,7) === "cdvfile") { + if (path.indexOf("cdvfile://localhost") === -1) { + if (errorCallback) { + errorCallback(FileError.ENCODING_ERR); + } + return; + } + + var indexPersistent = path.indexOf("persistent"); + var indexTemporary = path.indexOf("temporary"); + + //cdvfile://localhost/persistent/path/to/file + if (indexPersistent !== -1) { + path = "file:///persistent" + path.substr(indexPersistent + 10); + } else if (indexTemporary !== -1) { + path = "file:///temporary" + path.substr(indexTemporary + 9); + } else { + if (errorCallback) { + errorCallback(FileError.ENCODING_ERR); + } + return; + } + } + + // to avoid path form of '///path/to/file' + function handlePathSlashes(path) { + var cutIndex = 0; + for (var i = 0; i < path.length - 1; i++) { + if (path[i] === DIR_SEPARATOR && path[i + 1] === DIR_SEPARATOR) { + cutIndex = i + 1; + } else break; + } + + return path.substr(cutIndex); + } + + // Handle localhost containing paths (see specs ) + if (path.indexOf('file://localhost/') === 0) { + path = path.replace('file://localhost/', 'file:///'); + } + + if (path.indexOf(pathsPrefix.dataDirectory) === 0) { + path = path.substring(pathsPrefix.dataDirectory.length - 1); + path = handlePathSlashes(path); + + exports.requestFileSystem(function() { + exports.getFile(successCallback, function() { + exports.getDirectory(successCallback, errorCallback, [pathsPrefix.dataDirectory, path, + {create: false}]); + }, [pathsPrefix.dataDirectory, path, {create: false}]); + }, errorCallback, [LocalFileSystem.PERSISTENT]); + } else if (path.indexOf(pathsPrefix.cacheDirectory) === 0) { + path = path.substring(pathsPrefix.cacheDirectory.length - 1); + path = handlePathSlashes(path); + + exports.requestFileSystem(function() { + exports.getFile(successCallback, function() { + exports.getDirectory(successCallback, errorCallback, [pathsPrefix.cacheDirectory, path, + {create: false}]); + }, [pathsPrefix.cacheDirectory, path, {create: false}]); + }, errorCallback, [LocalFileSystem.TEMPORARY]); + } else if (path.indexOf(pathsPrefix.applicationDirectory) === 0) { + path = path.substring(pathsPrefix.applicationDirectory.length); + //TODO: need to cut out redundant slashes? + + var xhr = new XMLHttpRequest(); + xhr.open("GET", path, true); + xhr.onreadystatechange = function () { + if (xhr.status === 200 && xhr.readyState === 4) { + exports.requestFileSystem(function(fs) { + fs.name = location.hostname; + + //TODO: need to call exports.getFile(...) to handle errors correct + fs.root.getFile(path, {create: true}, writeFile, errorCallback); + }, errorCallback, [LocalFileSystem.PERSISTENT]); + } + }; + + xhr.onerror = function () { + if(errorCallback) { + errorCallback(FileError.NOT_READABLE_ERR); + } + }; + + xhr.send(); + } else { + if(errorCallback) { + errorCallback(FileError.NOT_FOUND_ERR); + } + } + + function writeFile(entry) { + entry.createWriter(function (fileWriter) { + fileWriter.onwriteend = function (evt) { + if (!evt.target.error) { + entry.filesystemName = location.hostname; + successCallback(entry); + } + }; + fileWriter.onerror = function () { + if (errorCallback) { + errorCallback(FileError.NOT_READABLE_ERR); + } + }; + fileWriter.write(new Blob([xhr.response])); + }, errorCallback); + } + }; + + exports.requestAllPaths = function(successCallback) { + successCallback(pathsPrefix); + }; + + /*** Helpers ***/ + + /** + * Interface to wrap the native File interface. + * + * This interface is necessary for creating zero-length (empty) files, + * something the Filesystem API allows you to do. Unfortunately, File's + * constructor cannot be called directly, making it impossible to instantiate + * an empty File in JS. + * + * @param {Object} opts Initial values. + * @constructor + */ + function MyFile(opts) { + var blob_ = new Blob(); + + this.size = opts.size || 0; + this.name = opts.name || ''; + this.type = opts.type || ''; + this.lastModifiedDate = opts.lastModifiedDate || null; + this.storagePath = opts.storagePath || ''; + + // Need some black magic to correct the object's size/name/type based on the + // blob that is saved. + Object.defineProperty(this, 'blob_', { + enumerable: true, + get: function() { + return blob_; + }, + set: function(val) { + blob_ = val; + this.size = blob_.size; + this.name = blob_.name; + this.type = blob_.type; + this.lastModifiedDate = blob_.lastModifiedDate; + }.bind(this) + }); + } + + MyFile.prototype.constructor = MyFile; + + // When saving an entry, the fullPath should always lead with a slash and never + // end with one (e.g. a directory). Also, resolve '.' and '..' to an absolute + // one. This method ensures path is legit! + function resolveToFullPath_(cwdFullPath, path) { + path = path || ''; + var fullPath = path; + var prefix = ''; + + cwdFullPath = cwdFullPath || DIR_SEPARATOR; + if (cwdFullPath.indexOf(FILESYSTEM_PREFIX) === 0) { + prefix = cwdFullPath.substring(0, cwdFullPath.indexOf(DIR_SEPARATOR, FILESYSTEM_PREFIX.length)); + cwdFullPath = cwdFullPath.substring(cwdFullPath.indexOf(DIR_SEPARATOR, FILESYSTEM_PREFIX.length)); + } + + var relativePath = path[0] !== DIR_SEPARATOR; + if (relativePath) { + fullPath = cwdFullPath; + if (cwdFullPath !== DIR_SEPARATOR) { + fullPath += DIR_SEPARATOR + path; + } else { + fullPath += path; + } + } + + // Remove doubled separator substrings + var re = new RegExp(DIR_SEPARATOR + DIR_SEPARATOR, 'g'); + fullPath = fullPath.replace(re, DIR_SEPARATOR); + + // Adjust '..'s by removing parent directories when '..' flows in path. + var parts = fullPath.split(DIR_SEPARATOR); + for (var i = 0; i < parts.length; ++i) { + var part = parts[i]; + if (part === '..') { + parts[i - 1] = ''; + parts[i] = ''; + } + } + fullPath = parts.filter(function(el) { + return el; + }).join(DIR_SEPARATOR); + + // Add back in leading slash. + if (fullPath[0] !== DIR_SEPARATOR) { + fullPath = DIR_SEPARATOR + fullPath; + } + + // Replace './' by current dir. ('./one/./two' -> one/two) + fullPath = fullPath.replace(/\.\//g, DIR_SEPARATOR); + + // Replace '//' with '/'. + fullPath = fullPath.replace(/\/\//g, DIR_SEPARATOR); + + // Replace '/.' with '/'. + fullPath = fullPath.replace(/\/\./g, DIR_SEPARATOR); + + // Remove '/' if it appears on the end. + if (fullPath[fullPath.length - 1] === DIR_SEPARATOR && + fullPath !== DIR_SEPARATOR) { + fullPath = fullPath.substring(0, fullPath.length - 1); + } + + var storagePath = prefix + fullPath; + storagePath = decodeURI(storagePath); + fullPath = decodeURI(fullPath); + + return { + storagePath: storagePath, + fullPath: fullPath, + fileName: fullPath.split(DIR_SEPARATOR).pop(), + fsName: prefix.split(DIR_SEPARATOR).pop() + }; + } + + function fileEntryFromIdbEntry(fileEntry) { + // IDB won't save methods, so we need re-create the FileEntry. + var clonedFileEntry = new FileEntry(fileEntry.name, fileEntry.fullPath, fileEntry.filesystem); + clonedFileEntry.file_ = fileEntry.file_; + + return clonedFileEntry; + } + + function readAs(what, fullPath, encoding, startPos, endPos, successCallback, errorCallback) { + exports.getFile(function(fileEntry) { + var fileReader = new FileReader(), + blob = fileEntry.file_.blob_.slice(startPos, endPos); + + fileReader.onload = function(e) { + successCallback(e.target.result); + }; + + fileReader.onerror = errorCallback; + + switch (what) { + case 'text': + fileReader.readAsText(blob, encoding); + break; + case 'dataURL': + fileReader.readAsDataURL(blob); + break; + case 'arrayBuffer': + fileReader.readAsArrayBuffer(blob); + break; + case 'binaryString': + fileReader.readAsBinaryString(blob); + break; + } + + }, errorCallback, [fullPath, null]); + } + + /*** Core logic to handle IDB operations ***/ + + idb_.open = function(dbName, successCallback, errorCallback) { + var self = this; + + // TODO: FF 12.0a1 isn't liking a db name with : in it. + var request = indexedDB.open(dbName.replace(':', '_')/*, 1 /*version*/); + + request.onerror = errorCallback || onError; + + request.onupgradeneeded = function(e) { + // First open was called or higher db version was used. + + // console.log('onupgradeneeded: oldVersion:' + e.oldVersion, + // 'newVersion:' + e.newVersion); + + self.db = e.target.result; + self.db.onerror = onError; + + if (!self.db.objectStoreNames.contains(FILE_STORE_)) { + self.db.createObjectStore(FILE_STORE_/*,{keyPath: 'id', autoIncrement: true}*/); + } + }; + + request.onsuccess = function(e) { + self.db = e.target.result; + self.db.onerror = onError; + successCallback(e); + }; + + request.onblocked = errorCallback || onError; + }; + + idb_.close = function() { + this.db.close(); + this.db = null; + }; + + idb_.get = function(fullPath, successCallback, errorCallback) { + if (!this.db) { + if (errorCallback) { + errorCallback(FileError.INVALID_MODIFICATION_ERR); + } + return; + } + + var tx = this.db.transaction([FILE_STORE_], 'readonly'); + + var request = tx.objectStore(FILE_STORE_).get(fullPath); + + tx.onabort = errorCallback || onError; + tx.oncomplete = function() { + successCallback(request.result); + }; + }; + + idb_.getAllEntries = function(fullPath, storagePath, successCallback, errorCallback) { + if (!this.db) { + if (errorCallback) { + errorCallback(FileError.INVALID_MODIFICATION_ERR); + } + return; + } + + var results = []; + + if (storagePath[storagePath.length - 1] === DIR_SEPARATOR) { + storagePath = storagePath.substring(0, storagePath.length - 1); + } + + var range = IDBKeyRange.bound(storagePath + DIR_SEPARATOR + ' ', + storagePath + DIR_SEPARATOR + String.fromCharCode(unicodeLastChar)); + + var tx = this.db.transaction([FILE_STORE_], 'readonly'); + tx.onabort = errorCallback || onError; + tx.oncomplete = function() { + results = results.filter(function(val) { + var pathWithoutSlash = val.fullPath; + + if (val.fullPath[val.fullPath.length - 1] === DIR_SEPARATOR) { + pathWithoutSlash = pathWithoutSlash.substr(0, pathWithoutSlash.length - 1); + } + + var valPartsLen = pathWithoutSlash.split(DIR_SEPARATOR).length; + var fullPathPartsLen = fullPath.split(DIR_SEPARATOR).length; + + /* Input fullPath parameter equals '//' for root folder */ + /* Entries in root folder has valPartsLen equals 2 (see below) */ + if (fullPath[fullPath.length -1] === DIR_SEPARATOR && fullPath.trim().length === 2) { + fullPathPartsLen = 1; + } else if (fullPath[fullPath.length -1] === DIR_SEPARATOR) { + fullPathPartsLen = fullPath.substr(0, fullPath.length - 1).split(DIR_SEPARATOR).length; + } else { + fullPathPartsLen = fullPath.split(DIR_SEPARATOR).length; + } + + if (valPartsLen === fullPathPartsLen + 1) { + // If this a subfolder and entry is a direct child, include it in + // the results. Otherwise, it's not an entry of this folder. + return val; + } else return false; + }); + + successCallback(results); + }; + + var request = tx.objectStore(FILE_STORE_).openCursor(range); + + request.onsuccess = function(e) { + var cursor = e.target.result; + if (cursor) { + var val = cursor.value; + + results.push(val.isFile ? fileEntryFromIdbEntry(val) : new DirectoryEntry(val.name, val.fullPath, val.filesystem)); + cursor['continue'](); + } + }; + }; + + idb_['delete'] = function(fullPath, successCallback, errorCallback, isDirectory) { + if (!idb_.db) { + if (errorCallback) { + errorCallback(FileError.INVALID_MODIFICATION_ERR); + } + return; + } + + var tx = this.db.transaction([FILE_STORE_], 'readwrite'); + tx.oncomplete = successCallback; + tx.onabort = errorCallback || onError; + tx.oncomplete = function() { + if (isDirectory) { + //We delete nested files and folders after deleting parent folder + //We use ranges: https://developer.mozilla.org/en-US/docs/Web/API/IDBKeyRange + fullPath = fullPath + DIR_SEPARATOR; + + //Range contains all entries in the form fullPath where + //symbol in the range from ' ' to symbol which has code `unicodeLastChar` + var range = IDBKeyRange.bound(fullPath + ' ', fullPath + String.fromCharCode(unicodeLastChar)); + + var newTx = this.db.transaction([FILE_STORE_], 'readwrite'); + newTx.oncomplete = successCallback; + newTx.onabort = errorCallback || onError; + newTx.objectStore(FILE_STORE_)['delete'](range); + } else { + successCallback(); + } + }; + tx.objectStore(FILE_STORE_)['delete'](fullPath); + }; + + idb_.put = function(entry, storagePath, successCallback, errorCallback) { + if (!this.db) { + if (errorCallback) { + errorCallback(FileError.INVALID_MODIFICATION_ERR); + } + return; + } + + var tx = this.db.transaction([FILE_STORE_], 'readwrite'); + tx.onabort = errorCallback || onError; + tx.oncomplete = function() { + // TODO: Error is thrown if we pass the request event back instead. + successCallback(entry); + }; + + tx.objectStore(FILE_STORE_).put(entry, storagePath); + }; + + // Global error handler. Errors bubble from request, to transaction, to db. + function onError(e) { + switch (e.target.errorCode) { + case 12: + console.log('Error - Attempt to open db with a lower version than the ' + + 'current one.'); + break; + default: + console.log('errorCode: ' + e.target.errorCode); + } + + console.log(e, e.code, e.message); + } + + })(module.exports, window); + + require("cordova/exec/proxy").add("File", module.exports); +})(); diff --git a/plugins/cordova-plugin-file/src/firefoxos/FileProxy.js b/plugins/cordova-plugin-file/src/firefoxos/FileProxy.js new file mode 100644 index 0000000..946304b --- /dev/null +++ b/plugins/cordova-plugin-file/src/firefoxos/FileProxy.js @@ -0,0 +1,805 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +/* global IDBKeyRange */ + +var LocalFileSystem = require('./LocalFileSystem'), + FileSystem = require('./FileSystem'), + FileEntry = require('./FileEntry'), + FileError = require('./FileError'), + DirectoryEntry = require('./DirectoryEntry'), + File = require('./File'); + +/* +QUIRKS: + Does not fail when removing non-empty directories + Does not support metadata for directories + Does not support requestAllFileSystems + Does not support resolveLocalFileSystemURI + Methods copyTo and moveTo do not support directories + + Heavily based on https://github.com/ebidel/idb.filesystem.js + */ + + +(function(exports, global) { + var indexedDB = global.indexedDB || global.mozIndexedDB; + if (!indexedDB) { + throw "Firefox OS File plugin: indexedDB not supported"; + } + + var fs_ = null; + + var idb_ = {}; + idb_.db = null; + var FILE_STORE_ = 'entries'; + + var DIR_SEPARATOR = '/'; + var DIR_OPEN_BOUND = String.fromCharCode(DIR_SEPARATOR.charCodeAt(0) + 1); + + var pathsPrefix = { + // Read-only directory where the application is installed. + applicationDirectory: location.origin + "/", + // Where to put app-specific data files. + dataDirectory: 'file:///persistent/', + // Cached files that should survive app restarts. + // Apps should not rely on the OS to delete files in here. + cacheDirectory: 'file:///temporary/', + }; + +/*** Exported functionality ***/ + + exports.requestFileSystem = function(successCallback, errorCallback, args) { + var type = args[0]; + //var size = args[1]; + + if (type !== LocalFileSystem.TEMPORARY && type !== LocalFileSystem.PERSISTENT) { + if (errorCallback) { + errorCallback(FileError.INVALID_MODIFICATION_ERR); + } + return; + } + + var name = type === LocalFileSystem.TEMPORARY ? 'temporary' : 'persistent'; + var storageName = (location.protocol + location.host).replace(/:/g, '_'); + + var root = new DirectoryEntry('', DIR_SEPARATOR); + fs_ = new FileSystem(name, root); + + idb_.open(storageName, function() { + successCallback(fs_); + }, errorCallback); + }; + + require('./fileSystems').getFs = function(name, callback) { + callback(new FileSystem(name, fs_.root)); + }; + + // list a directory's contents (files and folders). + exports.readEntries = function(successCallback, errorCallback, args) { + var fullPath = args[0]; + + if (!successCallback) { + throw Error('Expected successCallback argument.'); + } + + var path = resolveToFullPath_(fullPath); + + idb_.getAllEntries(path.fullPath, path.storagePath, function(entries) { + successCallback(entries); + }, errorCallback); + }; + + exports.getFile = function(successCallback, errorCallback, args) { + var fullPath = args[0]; + var path = args[1]; + var options = args[2] || {}; + + // Create an absolute path if we were handed a relative one. + path = resolveToFullPath_(fullPath, path); + + idb_.get(path.storagePath, function(fileEntry) { + if (options.create === true && options.exclusive === true && fileEntry) { + // If create and exclusive are both true, and the path already exists, + // getFile must fail. + + if (errorCallback) { + errorCallback(FileError.PATH_EXISTS_ERR); + } + } else if (options.create === true && !fileEntry) { + // If create is true, the path doesn't exist, and no other error occurs, + // getFile must create it as a zero-length file and return a corresponding + // FileEntry. + var newFileEntry = new FileEntry(path.fileName, path.fullPath, new FileSystem(path.fsName, fs_.root)); + + newFileEntry.file_ = new MyFile({ + size: 0, + name: newFileEntry.name, + lastModifiedDate: new Date(), + storagePath: path.storagePath + }); + + idb_.put(newFileEntry, path.storagePath, successCallback, errorCallback); + } else if (options.create === true && fileEntry) { + if (fileEntry.isFile) { + // Overwrite file, delete then create new. + idb_['delete'](path.storagePath, function() { + var newFileEntry = new FileEntry(path.fileName, path.fullPath, new FileSystem(path.fsName, fs_.root)); + + newFileEntry.file_ = new MyFile({ + size: 0, + name: newFileEntry.name, + lastModifiedDate: new Date(), + storagePath: path.storagePath + }); + + idb_.put(newFileEntry, path.storagePath, successCallback, errorCallback); + }, errorCallback); + } else { + if (errorCallback) { + errorCallback(FileError.INVALID_MODIFICATION_ERR); + } + } + } else if ((!options.create || options.create === false) && !fileEntry) { + // If create is not true and the path doesn't exist, getFile must fail. + if (errorCallback) { + errorCallback(FileError.NOT_FOUND_ERR); + } + } else if ((!options.create || options.create === false) && fileEntry && + fileEntry.isDirectory) { + // If create is not true and the path exists, but is a directory, getFile + // must fail. + if (errorCallback) { + errorCallback(FileError.INVALID_MODIFICATION_ERR); + } + } else { + // Otherwise, if no other error occurs, getFile must return a FileEntry + // corresponding to path. + + successCallback(fileEntryFromIdbEntry(fileEntry)); + } + }, errorCallback); + }; + + exports.getFileMetadata = function(successCallback, errorCallback, args) { + var fullPath = args[0]; + + exports.getFile(function(fileEntry) { + successCallback(new File(fileEntry.file_.name, fileEntry.fullPath, '', fileEntry.file_.lastModifiedDate, + fileEntry.file_.size)); + }, errorCallback, [fullPath, null]); + }; + + exports.getMetadata = function(successCallback, errorCallback, args) { + exports.getFile(function (fileEntry) { + successCallback( + { + modificationTime: fileEntry.file_.lastModifiedDate, + size: fileEntry.file_.lastModifiedDate + }); + }, errorCallback, args); + }; + + exports.setMetadata = function(successCallback, errorCallback, args) { + var fullPath = args[0]; + var metadataObject = args[1]; + + exports.getFile(function (fileEntry) { + fileEntry.file_.lastModifiedDate = metadataObject.modificationTime; + }, errorCallback, [fullPath, null]); + }; + + exports.write = function(successCallback, errorCallback, args) { + var fileName = args[0], + data = args[1], + position = args[2]; + //isBinary = args[3]; + + if (!data) { + if (errorCallback) { + errorCallback(FileError.INVALID_MODIFICATION_ERR); + } + return; + } + + exports.getFile(function(fileEntry) { + var blob_ = fileEntry.file_.blob_; + + if (!blob_) { + blob_ = new Blob([data], {type: data.type}); + } else { + // Calc the head and tail fragments + var head = blob_.slice(0, position); + var tail = blob_.slice(position + data.byteLength); + + // Calc the padding + var padding = position - head.size; + if (padding < 0) { + padding = 0; + } + + // Do the "write". In fact, a full overwrite of the Blob. + blob_ = new Blob([head, new Uint8Array(padding), data, tail], + {type: data.type}); + } + + // Set the blob we're writing on this file entry so we can recall it later. + fileEntry.file_.blob_ = blob_; + fileEntry.file_.lastModifiedDate = data.lastModifiedDate || null; + fileEntry.file_.size = blob_.size; + fileEntry.file_.name = blob_.name; + fileEntry.file_.type = blob_.type; + + idb_.put(fileEntry, fileEntry.file_.storagePath, function() { + successCallback(data.byteLength); + }, errorCallback); + }, errorCallback, [fileName, null]); + }; + + exports.readAsText = function(successCallback, errorCallback, args) { + var fileName = args[0], + enc = args[1], + startPos = args[2], + endPos = args[3]; + + readAs('text', fileName, enc, startPos, endPos, successCallback, errorCallback); + }; + + exports.readAsDataURL = function(successCallback, errorCallback, args) { + var fileName = args[0], + startPos = args[1], + endPos = args[2]; + + readAs('dataURL', fileName, null, startPos, endPos, successCallback, errorCallback); + }; + + exports.readAsBinaryString = function(successCallback, errorCallback, args) { + var fileName = args[0], + startPos = args[1], + endPos = args[2]; + + readAs('binaryString', fileName, null, startPos, endPos, successCallback, errorCallback); + }; + + exports.readAsArrayBuffer = function(successCallback, errorCallback, args) { + var fileName = args[0], + startPos = args[1], + endPos = args[2]; + + readAs('arrayBuffer', fileName, null, startPos, endPos, successCallback, errorCallback); + }; + + exports.removeRecursively = exports.remove = function(successCallback, errorCallback, args) { + var fullPath = args[0]; + + // TODO: This doesn't protect against directories that have content in it. + // Should throw an error instead if the dirEntry is not empty. + idb_['delete'](fullPath, function() { + successCallback(); + }, errorCallback); + }; + + exports.getDirectory = function(successCallback, errorCallback, args) { + var fullPath = args[0]; + var path = args[1]; + var options = args[2]; + + // Create an absolute path if we were handed a relative one. + path = resolveToFullPath_(fullPath, path); + + idb_.get(path.storagePath, function(folderEntry) { + if (!options) { + options = {}; + } + + if (options.create === true && options.exclusive === true && folderEntry) { + // If create and exclusive are both true, and the path already exists, + // getDirectory must fail. + if (errorCallback) { + errorCallback(FileError.INVALID_MODIFICATION_ERR); + } + } else if (options.create === true && !folderEntry) { + // If create is true, the path doesn't exist, and no other error occurs, + // getDirectory must create it as a zero-length file and return a corresponding + // MyDirectoryEntry. + var dirEntry = new DirectoryEntry(path.fileName, path.fullPath, new FileSystem(path.fsName, fs_.root)); + + idb_.put(dirEntry, path.storagePath, successCallback, errorCallback); + } else if (options.create === true && folderEntry) { + + if (folderEntry.isDirectory) { + // IDB won't save methods, so we need re-create the MyDirectoryEntry. + successCallback(new DirectoryEntry(folderEntry.name, folderEntry.fullPath, folderEntry.fileSystem)); + } else { + if (errorCallback) { + errorCallback(FileError.INVALID_MODIFICATION_ERR); + } + } + } else if ((!options.create || options.create === false) && !folderEntry) { + // Handle root special. It should always exist. + if (path.fullPath === DIR_SEPARATOR) { + successCallback(fs_.root); + return; + } + + // If create is not true and the path doesn't exist, getDirectory must fail. + if (errorCallback) { + errorCallback(FileError.NOT_FOUND_ERR); + } + } else if ((!options.create || options.create === false) && folderEntry && + folderEntry.isFile) { + // If create is not true and the path exists, but is a file, getDirectory + // must fail. + if (errorCallback) { + errorCallback(FileError.INVALID_MODIFICATION_ERR); + } + } else { + // Otherwise, if no other error occurs, getDirectory must return a + // MyDirectoryEntry corresponding to path. + + // IDB won't' save methods, so we need re-create MyDirectoryEntry. + successCallback(new DirectoryEntry(folderEntry.name, folderEntry.fullPath, folderEntry.fileSystem)); + } + }, errorCallback); + }; + + exports.getParent = function(successCallback, errorCallback, args) { + var fullPath = args[0]; + + if (fullPath === DIR_SEPARATOR) { + successCallback(fs_.root); + return; + } + + var pathArr = fullPath.split(DIR_SEPARATOR); + pathArr.pop(); + var namesa = pathArr.pop(); + var path = pathArr.join(DIR_SEPARATOR); + + exports.getDirectory(successCallback, errorCallback, [path, namesa, {create: false}]); + }; + + exports.copyTo = function(successCallback, errorCallback, args) { + var srcPath = args[0]; + var parentFullPath = args[1]; + var name = args[2]; + + // Read src file + exports.getFile(function(srcFileEntry) { + + // Create dest file + exports.getFile(function(dstFileEntry) { + + exports.write(function() { + successCallback(dstFileEntry); + }, errorCallback, [dstFileEntry.file_.storagePath, srcFileEntry.file_.blob_, 0]); + + }, errorCallback, [parentFullPath, name, {create: true}]); + + }, errorCallback, [srcPath, null]); + }; + + exports.moveTo = function(successCallback, errorCallback, args) { + var srcPath = args[0]; + //var parentFullPath = args[1]; + //var name = args[2]; + + exports.copyTo(function (fileEntry) { + + exports.remove(function () { + successCallback(fileEntry); + }, errorCallback, [srcPath]); + + }, errorCallback, args); + }; + + exports.resolveLocalFileSystemURI = function(successCallback, errorCallback, args) { + var path = args[0]; + + // Ignore parameters + if (path.indexOf('?') !== -1) { + path = String(path).split("?")[0]; + } + + // support for encodeURI + if (/\%5/g.test(path)) { + path = decodeURI(path); + } + + if (path.indexOf(pathsPrefix.dataDirectory) === 0) { + path = path.substring(pathsPrefix.dataDirectory.length - 1); + + exports.requestFileSystem(function(fs) { + fs.root.getFile(path, {create: false}, successCallback, function() { + fs.root.getDirectory(path, {create: false}, successCallback, errorCallback); + }); + }, errorCallback, [LocalFileSystem.PERSISTENT]); + } else if (path.indexOf(pathsPrefix.cacheDirectory) === 0) { + path = path.substring(pathsPrefix.cacheDirectory.length - 1); + + exports.requestFileSystem(function(fs) { + fs.root.getFile(path, {create: false}, successCallback, function() { + fs.root.getDirectory(path, {create: false}, successCallback, errorCallback); + }); + }, errorCallback, [LocalFileSystem.TEMPORARY]); + } else if (path.indexOf(pathsPrefix.applicationDirectory) === 0) { + path = path.substring(pathsPrefix.applicationDirectory.length); + + var xhr = new XMLHttpRequest(); + xhr.open("GET", path, true); + xhr.onreadystatechange = function () { + if (xhr.status === 200 && xhr.readyState === 4) { + exports.requestFileSystem(function(fs) { + fs.name = location.hostname; + fs.root.getFile(path, {create: true}, writeFile, errorCallback); + }, errorCallback, [LocalFileSystem.PERSISTENT]); + } + }; + + xhr.onerror = function () { + if (errorCallback) { + errorCallback(FileError.NOT_READABLE_ERR); + } + }; + + xhr.send(); + } else { + if (errorCallback) { + errorCallback(FileError.NOT_FOUND_ERR); + } + } + + function writeFile(entry) { + entry.createWriter(function (fileWriter) { + fileWriter.onwriteend = function (evt) { + if (!evt.target.error) { + entry.filesystemName = location.hostname; + successCallback(entry); + } + }; + fileWriter.onerror = function () { + if (errorCallback) { + errorCallback(FileError.NOT_READABLE_ERR); + } + }; + fileWriter.write(new Blob([xhr.response])); + }, errorCallback); + } + }; + + exports.requestAllPaths = function(successCallback) { + successCallback(pathsPrefix); + }; + +/*** Helpers ***/ + + /** + * Interface to wrap the native File interface. + * + * This interface is necessary for creating zero-length (empty) files, + * something the Filesystem API allows you to do. Unfortunately, File's + * constructor cannot be called directly, making it impossible to instantiate + * an empty File in JS. + * + * @param {Object} opts Initial values. + * @constructor + */ + function MyFile(opts) { + var blob_ = new Blob(); + + this.size = opts.size || 0; + this.name = opts.name || ''; + this.type = opts.type || ''; + this.lastModifiedDate = opts.lastModifiedDate || null; + this.storagePath = opts.storagePath || ''; + + // Need some black magic to correct the object's size/name/type based on the + // blob that is saved. + Object.defineProperty(this, 'blob_', { + enumerable: true, + get: function() { + return blob_; + }, + set: function(val) { + blob_ = val; + this.size = blob_.size; + this.name = blob_.name; + this.type = blob_.type; + this.lastModifiedDate = blob_.lastModifiedDate; + }.bind(this) + }); + } + + MyFile.prototype.constructor = MyFile; + + // When saving an entry, the fullPath should always lead with a slash and never + // end with one (e.g. a directory). Also, resolve '.' and '..' to an absolute + // one. This method ensures path is legit! + function resolveToFullPath_(cwdFullPath, path) { + path = path || ''; + var fullPath = path; + var prefix = ''; + + cwdFullPath = cwdFullPath || DIR_SEPARATOR; + if (cwdFullPath.indexOf(FILESYSTEM_PREFIX) === 0) { + prefix = cwdFullPath.substring(0, cwdFullPath.indexOf(DIR_SEPARATOR, FILESYSTEM_PREFIX.length)); + cwdFullPath = cwdFullPath.substring(cwdFullPath.indexOf(DIR_SEPARATOR, FILESYSTEM_PREFIX.length)); + } + + var relativePath = path[0] !== DIR_SEPARATOR; + if (relativePath) { + fullPath = cwdFullPath; + if (cwdFullPath != DIR_SEPARATOR) { + fullPath += DIR_SEPARATOR + path; + } else { + fullPath += path; + } + } + + // Adjust '..'s by removing parent directories when '..' flows in path. + var parts = fullPath.split(DIR_SEPARATOR); + for (var i = 0; i < parts.length; ++i) { + var part = parts[i]; + if (part == '..') { + parts[i - 1] = ''; + parts[i] = ''; + } + } + fullPath = parts.filter(function(el) { + return el; + }).join(DIR_SEPARATOR); + + // Add back in leading slash. + if (fullPath[0] !== DIR_SEPARATOR) { + fullPath = DIR_SEPARATOR + fullPath; + } + + // Replace './' by current dir. ('./one/./two' -> one/two) + fullPath = fullPath.replace(/\.\//g, DIR_SEPARATOR); + + // Replace '//' with '/'. + fullPath = fullPath.replace(/\/\//g, DIR_SEPARATOR); + + // Replace '/.' with '/'. + fullPath = fullPath.replace(/\/\./g, DIR_SEPARATOR); + + // Remove '/' if it appears on the end. + if (fullPath[fullPath.length - 1] == DIR_SEPARATOR && + fullPath != DIR_SEPARATOR) { + fullPath = fullPath.substring(0, fullPath.length - 1); + } + + return { + storagePath: prefix + fullPath, + fullPath: fullPath, + fileName: fullPath.split(DIR_SEPARATOR).pop(), + fsName: prefix.split(DIR_SEPARATOR).pop() + }; + } + + function fileEntryFromIdbEntry(fileEntry) { + // IDB won't save methods, so we need re-create the FileEntry. + var clonedFileEntry = new FileEntry(fileEntry.name, fileEntry.fullPath, fileEntry.fileSystem); + clonedFileEntry.file_ = fileEntry.file_; + + return clonedFileEntry; + } + + function readAs(what, fullPath, encoding, startPos, endPos, successCallback, errorCallback) { + exports.getFile(function(fileEntry) { + var fileReader = new FileReader(), + blob = fileEntry.file_.blob_.slice(startPos, endPos); + + fileReader.onload = function(e) { + successCallback(e.target.result); + }; + + fileReader.onerror = errorCallback; + + switch (what) { + case 'text': + fileReader.readAsText(blob, encoding); + break; + case 'dataURL': + fileReader.readAsDataURL(blob); + break; + case 'arrayBuffer': + fileReader.readAsArrayBuffer(blob); + break; + case 'binaryString': + fileReader.readAsBinaryString(blob); + break; + } + + }, errorCallback, [fullPath, null]); + } + +/*** Core logic to handle IDB operations ***/ + + idb_.open = function(dbName, successCallback, errorCallback) { + var self = this; + + // TODO: FF 12.0a1 isn't liking a db name with : in it. + var request = indexedDB.open(dbName.replace(':', '_')/*, 1 /*version*/); + + request.onerror = errorCallback || onError; + + request.onupgradeneeded = function(e) { + // First open was called or higher db version was used. + + // console.log('onupgradeneeded: oldVersion:' + e.oldVersion, + // 'newVersion:' + e.newVersion); + + self.db = e.target.result; + self.db.onerror = onError; + + if (!self.db.objectStoreNames.contains(FILE_STORE_)) { + self.db.createObjectStore(FILE_STORE_/*,{keyPath: 'id', autoIncrement: true}*/); + } + }; + + request.onsuccess = function(e) { + self.db = e.target.result; + self.db.onerror = onError; + successCallback(e); + }; + + request.onblocked = errorCallback || onError; + }; + + idb_.close = function() { + this.db.close(); + this.db = null; + }; + + idb_.get = function(fullPath, successCallback, errorCallback) { + if (!this.db) { + if (errorCallback) { + errorCallback(FileError.INVALID_MODIFICATION_ERR); + } + return; + } + + var tx = this.db.transaction([FILE_STORE_], 'readonly'); + + //var request = tx.objectStore(FILE_STORE_).get(fullPath); + var range = IDBKeyRange.bound(fullPath, fullPath + DIR_OPEN_BOUND, + false, true); + var request = tx.objectStore(FILE_STORE_).get(range); + + tx.onabort = errorCallback || onError; + tx.oncomplete = function(e) { + successCallback(request.result); + }; + }; + + idb_.getAllEntries = function(fullPath, storagePath, successCallback, errorCallback) { + if (!this.db) { + if (errorCallback) { + errorCallback(FileError.INVALID_MODIFICATION_ERR); + } + return; + } + + var results = []; + + if (storagePath[storagePath.length - 1] === DIR_SEPARATOR) { + storagePath = storagePath.substring(0, storagePath.length - 1); + } + + var range = IDBKeyRange.bound( + storagePath + DIR_SEPARATOR, storagePath + DIR_OPEN_BOUND, false, true); + + var tx = this.db.transaction([FILE_STORE_], 'readonly'); + tx.onabort = errorCallback || onError; + tx.oncomplete = function(e) { + results = results.filter(function(val) { + var valPartsLen = val.fullPath.split(DIR_SEPARATOR).length; + var fullPathPartsLen = fullPath.split(DIR_SEPARATOR).length; + + if (fullPath === DIR_SEPARATOR && valPartsLen < fullPathPartsLen + 1) { + // Hack to filter out entries in the root folder. This is inefficient + // because reading the entires of fs.root (e.g. '/') returns ALL + // results in the database, then filters out the entries not in '/'. + return val; + } else if (fullPath !== DIR_SEPARATOR && + valPartsLen === fullPathPartsLen + 1) { + // If this a subfolder and entry is a direct child, include it in + // the results. Otherwise, it's not an entry of this folder. + return val; + } + }); + + successCallback(results); + }; + + var request = tx.objectStore(FILE_STORE_).openCursor(range); + + request.onsuccess = function(e) { + var cursor = e.target.result; + if (cursor) { + var val = cursor.value; + + results.push(val.isFile ? fileEntryFromIdbEntry(val) : new DirectoryEntry(val.name, val.fullPath, val.fileSystem)); + cursor['continue'](); + } + }; + }; + + idb_['delete'] = function(fullPath, successCallback, errorCallback) { + if (!this.db) { + if (errorCallback) { + errorCallback(FileError.INVALID_MODIFICATION_ERR); + } + return; + } + + var tx = this.db.transaction([FILE_STORE_], 'readwrite'); + tx.oncomplete = successCallback; + tx.onabort = errorCallback || onError; + + //var request = tx.objectStore(FILE_STORE_).delete(fullPath); + var range = IDBKeyRange.bound( + fullPath, fullPath + DIR_OPEN_BOUND, false, true); + tx.objectStore(FILE_STORE_)['delete'](range); + }; + + idb_.put = function(entry, storagePath, successCallback, errorCallback) { + if (!this.db) { + if (errorCallback) { + errorCallback(FileError.INVALID_MODIFICATION_ERR); + } + return; + } + + var tx = this.db.transaction([FILE_STORE_], 'readwrite'); + tx.onabort = errorCallback || onError; + tx.oncomplete = function(e) { + // TODO: Error is thrown if we pass the request event back instead. + successCallback(entry); + }; + + tx.objectStore(FILE_STORE_).put(entry, storagePath); + }; + + // Global error handler. Errors bubble from request, to transaction, to db. + function onError(e) { + switch (e.target.errorCode) { + case 12: + console.log('Error - Attempt to open db with a lower version than the ' + + 'current one.'); + break; + default: + console.log('errorCode: ' + e.target.errorCode); + } + + console.log(e, e.code, e.message); + } + +// Clean up. +// TODO: Is there a place for this? +// global.addEventListener('beforeunload', function(e) { +// idb_.db && idb_.db.close(); +// }, false); + +})(module.exports, window); + +require("cordova/exec/proxy").add("File", module.exports); diff --git a/plugins/cordova-plugin-file/src/ios/CDVAssetLibraryFilesystem.h b/plugins/cordova-plugin-file/src/ios/CDVAssetLibraryFilesystem.h new file mode 100644 index 0000000..e09e225 --- /dev/null +++ b/plugins/cordova-plugin-file/src/ios/CDVAssetLibraryFilesystem.h @@ -0,0 +1,30 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. + */ + +#import "CDVFile.h" + +extern NSString* const kCDVAssetsLibraryPrefix; +extern NSString* const kCDVAssetsLibraryScheme; + +@interface CDVAssetLibraryFilesystem : NSObject { +} + +- (id) initWithName:(NSString *)name; + +@end diff --git a/plugins/cordova-plugin-file/src/ios/CDVAssetLibraryFilesystem.m b/plugins/cordova-plugin-file/src/ios/CDVAssetLibraryFilesystem.m new file mode 100644 index 0000000..8486b7b --- /dev/null +++ b/plugins/cordova-plugin-file/src/ios/CDVAssetLibraryFilesystem.m @@ -0,0 +1,253 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. + */ + +#import "CDVFile.h" +#import "CDVAssetLibraryFilesystem.h" +#import +#import +#import +#import +#import + +NSString* const kCDVAssetsLibraryPrefix = @"assets-library://"; +NSString* const kCDVAssetsLibraryScheme = @"assets-library"; + +@implementation CDVAssetLibraryFilesystem +@synthesize name=_name, urlTransformer; + + +/* + The CDVAssetLibraryFilesystem works with resources which are identified + by iOS as + asset-library:// + and represents them internally as URLs of the form + cdvfile://localhost/assets-library/ + */ + +- (NSURL *)assetLibraryURLForLocalURL:(CDVFilesystemURL *)url +{ + if ([url.url.scheme isEqualToString:kCDVFilesystemURLPrefix]) { + NSString *path = [[url.url absoluteString] substringFromIndex:[@"cdvfile://localhost/assets-library" length]]; + return [NSURL URLWithString:[NSString stringWithFormat:@"assets-library:/%@", path]]; + } + return url.url; +} + +- (CDVPluginResult *)entryForLocalURI:(CDVFilesystemURL *)url +{ + NSDictionary* entry = [self makeEntryForLocalURL:url]; + return [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:entry]; +} + +- (NSDictionary *)makeEntryForLocalURL:(CDVFilesystemURL *)url { + return [self makeEntryForPath:url.fullPath isDirectory:NO]; +} + +- (NSDictionary*)makeEntryForPath:(NSString*)fullPath isDirectory:(BOOL)isDir +{ + NSMutableDictionary* dirEntry = [NSMutableDictionary dictionaryWithCapacity:5]; + NSString* lastPart = [fullPath lastPathComponent]; + if (isDir && ![fullPath hasSuffix:@"/"]) { + fullPath = [fullPath stringByAppendingString:@"/"]; + } + [dirEntry setObject:[NSNumber numberWithBool:!isDir] forKey:@"isFile"]; + [dirEntry setObject:[NSNumber numberWithBool:isDir] forKey:@"isDirectory"]; + [dirEntry setObject:fullPath forKey:@"fullPath"]; + [dirEntry setObject:lastPart forKey:@"name"]; + [dirEntry setObject:self.name forKey: @"filesystemName"]; + + NSURL* nativeURL = [NSURL URLWithString:[NSString stringWithFormat:@"assets-library:/%@",fullPath]]; + if (self.urlTransformer) { + nativeURL = self.urlTransformer(nativeURL); + } + dirEntry[@"nativeURL"] = [nativeURL absoluteString]; + + return dirEntry; +} + +/* helper function to get the mimeType from the file extension + * IN: + * NSString* fullPath - filename (may include path) + * OUT: + * NSString* the mime type as type/subtype. nil if not able to determine + */ ++ (NSString*)getMimeTypeFromPath:(NSString*)fullPath +{ + NSString* mimeType = nil; + + if (fullPath) { + CFStringRef typeId = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)[fullPath pathExtension], NULL); + if (typeId) { + mimeType = (__bridge_transfer NSString*)UTTypeCopyPreferredTagWithClass(typeId, kUTTagClassMIMEType); + if (!mimeType) { + // special case for m4a + if ([(__bridge NSString*)typeId rangeOfString : @"m4a-audio"].location != NSNotFound) { + mimeType = @"audio/mp4"; + } else if ([[fullPath pathExtension] rangeOfString:@"wav"].location != NSNotFound) { + mimeType = @"audio/wav"; + } else if ([[fullPath pathExtension] rangeOfString:@"css"].location != NSNotFound) { + mimeType = @"text/css"; + } + } + CFRelease(typeId); + } + } + return mimeType; +} + +- (id)initWithName:(NSString *)name +{ + if (self) { + self.name = name; + } + return self; +} + +- (CDVPluginResult *)getFileForURL:(CDVFilesystemURL *)baseURI requestedPath:(NSString *)requestedPath options:(NSDictionary *)options +{ + // return unsupported result for assets-library URLs + return [CDVPluginResult resultWithStatus:CDVCommandStatus_MALFORMED_URL_EXCEPTION messageAsString:@"getFile not supported for assets-library URLs."]; +} + +- (CDVPluginResult*)getParentForURL:(CDVFilesystemURL *)localURI +{ + // we don't (yet?) support getting the parent of an asset + return [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NOT_READABLE_ERR]; +} + +- (CDVPluginResult*)setMetadataForURL:(CDVFilesystemURL *)localURI withObject:(NSDictionary *)options +{ + // setMetadata doesn't make sense for asset library files + return [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR]; +} + +- (CDVPluginResult *)removeFileAtURL:(CDVFilesystemURL *)localURI +{ + // return error for assets-library URLs + return [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:INVALID_MODIFICATION_ERR]; +} + +- (CDVPluginResult *)recursiveRemoveFileAtURL:(CDVFilesystemURL *)localURI +{ + // return error for assets-library URLs + return [CDVPluginResult resultWithStatus:CDVCommandStatus_MALFORMED_URL_EXCEPTION messageAsString:@"removeRecursively not supported for assets-library URLs."]; +} + +- (CDVPluginResult *)readEntriesAtURL:(CDVFilesystemURL *)localURI +{ + // return unsupported result for assets-library URLs + return [CDVPluginResult resultWithStatus:CDVCommandStatus_MALFORMED_URL_EXCEPTION messageAsString:@"readEntries not supported for assets-library URLs."]; +} + +- (CDVPluginResult *)truncateFileAtURL:(CDVFilesystemURL *)localURI atPosition:(unsigned long long)pos +{ + // assets-library files can't be truncated + return [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NO_MODIFICATION_ALLOWED_ERR]; +} + +- (CDVPluginResult *)writeToFileAtURL:(CDVFilesystemURL *)localURL withData:(NSData*)encData append:(BOOL)shouldAppend +{ + // text can't be written into assets-library files + return [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NO_MODIFICATION_ALLOWED_ERR]; +} + +- (void)copyFileToURL:(CDVFilesystemURL *)destURL withName:(NSString *)newName fromFileSystem:(NSObject *)srcFs atURL:(CDVFilesystemURL *)srcURL copy:(BOOL)bCopy callback:(void (^)(CDVPluginResult *))callback +{ + // Copying to an assets library file is not doable, since we can't write it. + CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:INVALID_MODIFICATION_ERR]; + callback(result); +} + +- (NSString *)filesystemPathForURL:(CDVFilesystemURL *)url +{ + NSString *path = nil; + if ([[url.url scheme] isEqualToString:kCDVAssetsLibraryScheme]) { + path = [url.url path]; + } else { + path = url.fullPath; + } + if ([path hasSuffix:@"/"]) { + path = [path substringToIndex:([path length]-1)]; + } + return path; +} + +- (void)readFileAtURL:(CDVFilesystemURL *)localURL start:(NSInteger)start end:(NSInteger)end callback:(void (^)(NSData*, NSString* mimeType, CDVFileError))callback +{ + ALAssetsLibraryAssetForURLResultBlock resultBlock = ^(ALAsset* asset) { + if (asset) { + // We have the asset! Get the data and send it off. + ALAssetRepresentation* assetRepresentation = [asset defaultRepresentation]; + NSUInteger size = (end > start) ? (end - start) : [assetRepresentation size]; + Byte* buffer = (Byte*)malloc(size); + NSUInteger bufferSize = [assetRepresentation getBytes:buffer fromOffset:start length:size error:nil]; + NSData* data = [NSData dataWithBytesNoCopy:buffer length:bufferSize freeWhenDone:YES]; + NSString* MIMEType = (__bridge_transfer NSString*)UTTypeCopyPreferredTagWithClass((__bridge CFStringRef)[assetRepresentation UTI], kUTTagClassMIMEType); + + callback(data, MIMEType, NO_ERROR); + } else { + callback(nil, nil, NOT_FOUND_ERR); + } + }; + + ALAssetsLibraryAccessFailureBlock failureBlock = ^(NSError* error) { + // Retrieving the asset failed for some reason. Send the appropriate error. + NSLog(@"Error: %@", error); + callback(nil, nil, SECURITY_ERR); + }; + + ALAssetsLibrary* assetsLibrary = [[ALAssetsLibrary alloc] init]; + [assetsLibrary assetForURL:[self assetLibraryURLForLocalURL:localURL] resultBlock:resultBlock failureBlock:failureBlock]; +} + +- (void)getFileMetadataForURL:(CDVFilesystemURL *)localURL callback:(void (^)(CDVPluginResult *))callback +{ + // In this case, we need to use an asynchronous method to retrieve the file. + // Because of this, we can't just assign to `result` and send it at the end of the method. + // Instead, we return after calling the asynchronous method and send `result` in each of the blocks. + ALAssetsLibraryAssetForURLResultBlock resultBlock = ^(ALAsset* asset) { + if (asset) { + // We have the asset! Populate the dictionary and send it off. + NSMutableDictionary* fileInfo = [NSMutableDictionary dictionaryWithCapacity:5]; + ALAssetRepresentation* assetRepresentation = [asset defaultRepresentation]; + [fileInfo setObject:[NSNumber numberWithUnsignedLongLong:[assetRepresentation size]] forKey:@"size"]; + [fileInfo setObject:localURL.fullPath forKey:@"fullPath"]; + NSString* filename = [assetRepresentation filename]; + [fileInfo setObject:filename forKey:@"name"]; + [fileInfo setObject:[CDVAssetLibraryFilesystem getMimeTypeFromPath:filename] forKey:@"type"]; + NSDate* creationDate = [asset valueForProperty:ALAssetPropertyDate]; + NSNumber* msDate = [NSNumber numberWithDouble:[creationDate timeIntervalSince1970] * 1000]; + [fileInfo setObject:msDate forKey:@"lastModifiedDate"]; + + callback([CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:fileInfo]); + } else { + // We couldn't find the asset. Send the appropriate error. + callback([CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NOT_FOUND_ERR]); + } + }; + ALAssetsLibraryAccessFailureBlock failureBlock = ^(NSError* error) { + // Retrieving the asset failed for some reason. Send the appropriate error. + callback([CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsString:[error localizedDescription]]); + }; + + ALAssetsLibrary* assetsLibrary = [[ALAssetsLibrary alloc] init]; + [assetsLibrary assetForURL:[self assetLibraryURLForLocalURL:localURL] resultBlock:resultBlock failureBlock:failureBlock]; + return; +} +@end diff --git a/plugins/cordova-plugin-file/src/ios/CDVFile.h b/plugins/cordova-plugin-file/src/ios/CDVFile.h new file mode 100644 index 0000000..987c66b --- /dev/null +++ b/plugins/cordova-plugin-file/src/ios/CDVFile.h @@ -0,0 +1,157 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. + */ + +#import +#import + +extern NSString* const kCDVAssetsLibraryPrefix; +extern NSString* const kCDVFilesystemURLPrefix; + +enum CDVFileError { + NO_ERROR = 0, + NOT_FOUND_ERR = 1, + SECURITY_ERR = 2, + ABORT_ERR = 3, + NOT_READABLE_ERR = 4, + ENCODING_ERR = 5, + NO_MODIFICATION_ALLOWED_ERR = 6, + INVALID_STATE_ERR = 7, + SYNTAX_ERR = 8, + INVALID_MODIFICATION_ERR = 9, + QUOTA_EXCEEDED_ERR = 10, + TYPE_MISMATCH_ERR = 11, + PATH_EXISTS_ERR = 12 +}; +typedef int CDVFileError; + +@interface CDVFilesystemURL : NSObject { + NSURL *_url; + NSString *_fileSystemName; + NSString *_fullPath; +} + +- (id) initWithString:(NSString*)strURL; +- (id) initWithURL:(NSURL*)URL; ++ (CDVFilesystemURL *)fileSystemURLWithString:(NSString *)strURL; ++ (CDVFilesystemURL *)fileSystemURLWithURL:(NSURL *)URL; + +- (NSString *)absoluteURL; + +@property (atomic) NSURL *url; +@property (atomic) NSString *fileSystemName; +@property (atomic) NSString *fullPath; + +@end + +@interface CDVFilesystemURLProtocol : NSURLProtocol +@end + +@protocol CDVFileSystem +- (CDVPluginResult *)entryForLocalURI:(CDVFilesystemURL *)url; +- (CDVPluginResult *)getFileForURL:(CDVFilesystemURL *)baseURI requestedPath:(NSString *)requestedPath options:(NSDictionary *)options; +- (CDVPluginResult *)getParentForURL:(CDVFilesystemURL *)localURI; +- (CDVPluginResult *)setMetadataForURL:(CDVFilesystemURL *)localURI withObject:(NSDictionary *)options; +- (CDVPluginResult *)removeFileAtURL:(CDVFilesystemURL *)localURI; +- (CDVPluginResult *)recursiveRemoveFileAtURL:(CDVFilesystemURL *)localURI; +- (CDVPluginResult *)readEntriesAtURL:(CDVFilesystemURL *)localURI; +- (CDVPluginResult *)truncateFileAtURL:(CDVFilesystemURL *)localURI atPosition:(unsigned long long)pos; +- (CDVPluginResult *)writeToFileAtURL:(CDVFilesystemURL *)localURL withData:(NSData*)encData append:(BOOL)shouldAppend; +- (void)copyFileToURL:(CDVFilesystemURL *)destURL withName:(NSString *)newName fromFileSystem:(NSObject *)srcFs atURL:(CDVFilesystemURL *)srcURL copy:(BOOL)bCopy callback:(void (^)(CDVPluginResult *))callback; +- (void)readFileAtURL:(CDVFilesystemURL *)localURL start:(NSInteger)start end:(NSInteger)end callback:(void (^)(NSData*, NSString* mimeType, CDVFileError))callback; +- (void)getFileMetadataForURL:(CDVFilesystemURL *)localURL callback:(void (^)(CDVPluginResult *))callback; + +- (NSDictionary *)makeEntryForLocalURL:(CDVFilesystemURL *)url; +- (NSDictionary*)makeEntryForPath:(NSString*)fullPath isDirectory:(BOOL)isDir; + +@property (nonatomic,strong) NSString *name; +@property (nonatomic, copy) NSURL*(^urlTransformer)(NSURL*); + +@optional +- (NSString *)filesystemPathForURL:(CDVFilesystemURL *)localURI; +- (CDVFilesystemURL *)URLforFilesystemPath:(NSString *)path; + +@end + +@interface CDVFile : CDVPlugin { + NSString* rootDocsPath; + NSString* appDocsPath; + NSString* appLibraryPath; + NSString* appTempPath; + + NSMutableArray* fileSystems_; + BOOL userHasAllowed; +} + +- (NSNumber*)checkFreeDiskSpace:(NSString*)appPath; +- (NSDictionary*)makeEntryForPath:(NSString*)fullPath fileSystemName:(NSString *)fsName isDirectory:(BOOL)isDir; +- (NSDictionary *)makeEntryForURL:(NSURL *)URL; +- (CDVFilesystemURL *)fileSystemURLforLocalPath:(NSString *)localPath; + +- (NSObject *)filesystemForURL:(CDVFilesystemURL *)localURL; + +/* Native Registration API */ +- (void)registerFilesystem:(NSObject *)fs; +- (NSObject *)fileSystemByName:(NSString *)fsName; + +/* Exec API */ +- (void)requestFileSystem:(CDVInvokedUrlCommand*)command; +- (void)resolveLocalFileSystemURI:(CDVInvokedUrlCommand*)command; +- (void)getDirectory:(CDVInvokedUrlCommand*)command; +- (void)getFile:(CDVInvokedUrlCommand*)command; +- (void)getParent:(CDVInvokedUrlCommand*)command; +- (void)removeRecursively:(CDVInvokedUrlCommand*)command; +- (void)remove:(CDVInvokedUrlCommand*)command; +- (void)copyTo:(CDVInvokedUrlCommand*)command; +- (void)moveTo:(CDVInvokedUrlCommand*)command; +- (void)getFileMetadata:(CDVInvokedUrlCommand*)command; +- (void)readEntries:(CDVInvokedUrlCommand*)command; +- (void)readAsText:(CDVInvokedUrlCommand*)command; +- (void)readAsDataURL:(CDVInvokedUrlCommand*)command; +- (void)readAsArrayBuffer:(CDVInvokedUrlCommand*)command; +- (void)write:(CDVInvokedUrlCommand*)command; +- (void)testFileExists:(CDVInvokedUrlCommand*)command; +- (void)testDirectoryExists:(CDVInvokedUrlCommand*)command; +- (void)getFreeDiskSpace:(CDVInvokedUrlCommand*)command; +- (void)truncate:(CDVInvokedUrlCommand*)command; +- (void)doCopyMove:(CDVInvokedUrlCommand*)command isCopy:(BOOL)bCopy; + +/* Compatibilty with older File API */ +- (NSString*)getMimeTypeFromPath:(NSString*)fullPath; +- (NSDictionary *)getDirectoryEntry:(NSString *)target isDirectory:(BOOL)bDirRequest; + +/* Conversion between filesystem paths and URLs */ +- (NSString *)filesystemPathForURL:(CDVFilesystemURL *)URL; + +/* Internal methods for testing */ +- (void)_getLocalFilesystemPath:(CDVInvokedUrlCommand*)command; + +@property (nonatomic, strong) NSString* rootDocsPath; +@property (nonatomic, strong) NSString* appDocsPath; +@property (nonatomic, strong) NSString* appLibraryPath; +@property (nonatomic, strong) NSString* appTempPath; +@property (nonatomic, strong) NSString* persistentPath; +@property (nonatomic, strong) NSString* temporaryPath; +@property (nonatomic, strong) NSMutableArray* fileSystems; + +@property BOOL userHasAllowed; + +@end + +#define kW3FileTemporary @"temporary" +#define kW3FilePersistent @"persistent" diff --git a/plugins/cordova-plugin-file/src/ios/CDVFile.m b/plugins/cordova-plugin-file/src/ios/CDVFile.m new file mode 100644 index 0000000..59e7d64 --- /dev/null +++ b/plugins/cordova-plugin-file/src/ios/CDVFile.m @@ -0,0 +1,1119 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. + */ + +#import +#import "CDVFile.h" +#import "CDVLocalFilesystem.h" +#import "CDVAssetLibraryFilesystem.h" +#import + +static NSString* toBase64(NSData* data) { + SEL s1 = NSSelectorFromString(@"cdv_base64EncodedString"); + SEL s2 = NSSelectorFromString(@"base64EncodedString"); + SEL s3 = NSSelectorFromString(@"base64EncodedStringWithOptions:"); + + if ([data respondsToSelector:s1]) { + NSString* (*func)(id, SEL) = (void *)[data methodForSelector:s1]; + return func(data, s1); + } else if ([data respondsToSelector:s2]) { + NSString* (*func)(id, SEL) = (void *)[data methodForSelector:s2]; + return func(data, s2); + } else if ([data respondsToSelector:s3]) { + NSString* (*func)(id, SEL, NSUInteger) = (void *)[data methodForSelector:s3]; + return func(data, s3, 0); + } else { + return nil; + } +} + +CDVFile *filePlugin = nil; + +extern NSString * const NSURLIsExcludedFromBackupKey __attribute__((weak_import)); + +#ifndef __IPHONE_5_1 + NSString* const NSURLIsExcludedFromBackupKey = @"NSURLIsExcludedFromBackupKey"; +#endif + +NSString* const kCDVFilesystemURLPrefix = @"cdvfile"; + +@implementation CDVFilesystemURL +@synthesize url=_url; +@synthesize fileSystemName=_fileSystemName; +@synthesize fullPath=_fullPath; + +- (id) initWithString:(NSString *)strURL +{ + if ( self = [super init] ) { + NSURL *decodedURL = [NSURL URLWithString:strURL]; + return [self initWithURL:decodedURL]; + } + return nil; +} + +-(id) initWithURL:(NSURL *)URL +{ + if ( self = [super init] ) { + self.url = URL; + self.fileSystemName = [self filesystemNameForLocalURI:URL]; + self.fullPath = [self fullPathForLocalURI:URL]; + } + return self; +} + +/* + * IN + * NSString localURI + * OUT + * NSString FileSystem Name for this URI, or nil if it is not recognized. + */ +- (NSString *)filesystemNameForLocalURI:(NSURL *)uri +{ + if ([[uri scheme] isEqualToString:kCDVFilesystemURLPrefix] && [[uri host] isEqualToString:@"localhost"]) { + NSArray *pathComponents = [uri pathComponents]; + if (pathComponents != nil && pathComponents.count > 1) { + return [pathComponents objectAtIndex:1]; + } + } else if ([[uri scheme] isEqualToString:kCDVAssetsLibraryScheme]) { + return @"assets-library"; + } + return nil; +} + +/* + * IN + * NSString localURI + * OUT + * NSString fullPath component suitable for an Entry object. + * The incoming URI should be properly escaped. The returned fullPath is unescaped. + */ +- (NSString *)fullPathForLocalURI:(NSURL *)uri +{ + if ([[uri scheme] isEqualToString:kCDVFilesystemURLPrefix] && [[uri host] isEqualToString:@"localhost"]) { + NSString *path = [uri path]; + if ([uri query]) { + path = [NSString stringWithFormat:@"%@?%@", path, [uri query]]; + } + NSRange slashRange = [path rangeOfString:@"/" options:0 range:NSMakeRange(1, path.length-1)]; + if (slashRange.location == NSNotFound) { + return @""; + } + return [path substringFromIndex:slashRange.location]; + } else if ([[uri scheme] isEqualToString:kCDVAssetsLibraryScheme]) { + return [[uri absoluteString] substringFromIndex:[kCDVAssetsLibraryScheme length]+2]; + } + return nil; +} + ++ (CDVFilesystemURL *)fileSystemURLWithString:(NSString *)strURL +{ + return [[CDVFilesystemURL alloc] initWithString:strURL]; +} + ++ (CDVFilesystemURL *)fileSystemURLWithURL:(NSURL *)URL +{ + return [[CDVFilesystemURL alloc] initWithURL:URL]; +} + +- (NSString *)absoluteURL +{ + return [NSString stringWithFormat:@"cdvfile://localhost/%@%@", self.fileSystemName, self.fullPath]; +} + +@end + +@implementation CDVFilesystemURLProtocol + ++ (BOOL)canInitWithRequest:(NSURLRequest*)request +{ + NSURL* url = [request URL]; + return [[url scheme] isEqualToString:kCDVFilesystemURLPrefix]; +} + ++ (NSURLRequest*)canonicalRequestForRequest:(NSURLRequest*)request +{ + return request; +} + ++ (BOOL)requestIsCacheEquivalent:(NSURLRequest*)requestA toRequest:(NSURLRequest*)requestB +{ + return [[[requestA URL] resourceSpecifier] isEqualToString:[[requestB URL] resourceSpecifier]]; +} + +- (void)startLoading +{ + CDVFilesystemURL* url = [CDVFilesystemURL fileSystemURLWithURL:[[self request] URL]]; + NSObject *fs = [filePlugin filesystemForURL:url]; + __weak CDVFilesystemURLProtocol* weakSelf = self; + + [fs readFileAtURL:url start:0 end:-1 callback:^void(NSData *data, NSString *mimetype, CDVFileError error) { + NSMutableDictionary* responseHeaders = [[NSMutableDictionary alloc] init]; + responseHeaders[@"Cache-Control"] = @"no-cache"; + + if (!error) { + responseHeaders[@"Content-Type"] = mimetype; + NSURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:url.url statusCode:200 HTTPVersion:@"HTTP/1.1"headerFields:responseHeaders]; + [[weakSelf client] URLProtocol:weakSelf didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed]; + [[weakSelf client] URLProtocol:weakSelf didLoadData:data]; + [[weakSelf client] URLProtocolDidFinishLoading:weakSelf]; + } else { + NSURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:url.url statusCode:404 HTTPVersion:@"HTTP/1.1"headerFields:responseHeaders]; + [[weakSelf client] URLProtocol:weakSelf didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed]; + [[weakSelf client] URLProtocolDidFinishLoading:weakSelf]; + } + }]; +} + +- (void)stopLoading +{} + +- (NSCachedURLResponse *)connection:(NSURLConnection *)connection + willCacheResponse:(NSCachedURLResponse*)cachedResponse { + return nil; +} + +@end + + +@implementation CDVFile + +@synthesize rootDocsPath, appDocsPath, appLibraryPath, appTempPath, userHasAllowed, fileSystems=fileSystems_; + +- (void)registerFilesystem:(NSObject *)fs { + __weak CDVFile* weakSelf = self; + SEL sel = NSSelectorFromString(@"urlTransformer"); + // for backwards compatibility - we check if this property is there + // we create a wrapper block because the urlTransformer property + // on the commandDelegate might be set dynamically at a future time + // (and not dependent on plugin loading order) + if ([self.commandDelegate respondsToSelector:sel]) { + fs.urlTransformer = ^NSURL*(NSURL* urlToTransform) { + // grab the block from the commandDelegate + NSURL* (^urlTransformer)(NSURL*) = ((id(*)(id, SEL))objc_msgSend)(weakSelf.commandDelegate, sel); + // if block is not null, we call it + if (urlTransformer) { + return urlTransformer(urlToTransform); + } else { // else we return the same url + return urlToTransform; + } + }; + } + [fileSystems_ addObject:fs]; +} + +- (NSObject *)fileSystemByName:(NSString *)fsName +{ + if (self.fileSystems != nil) { + for (NSObject *fs in self.fileSystems) { + if ([fs.name isEqualToString:fsName]) { + return fs; + } + } + } + return nil; +} + +- (NSObject *)filesystemForURL:(CDVFilesystemURL *)localURL { + if (localURL.fileSystemName == nil) return nil; + @try { + return [self fileSystemByName:localURL.fileSystemName]; + } + @catch (NSException *e) { + return nil; + } +} + +- (NSArray *)getExtraFileSystemsPreference:(UIViewController *)vc +{ + NSString *filesystemsStr = nil; + if([self.viewController isKindOfClass:[CDVViewController class]]) { + CDVViewController *vc = (CDVViewController *)self.viewController; + NSDictionary *settings = [vc settings]; + filesystemsStr = [settings[@"iosextrafilesystems"] lowercaseString]; + } + if (!filesystemsStr) { + filesystemsStr = @"library,library-nosync,documents,documents-nosync,cache,bundle,root"; + } + return [filesystemsStr componentsSeparatedByString:@","]; +} + +- (void)makeNonSyncable:(NSString*)path { + [[NSFileManager defaultManager] createDirectoryAtPath:path + withIntermediateDirectories:YES + attributes:nil + error:nil]; + NSURL* url = [NSURL fileURLWithPath:path]; + [url setResourceValue: [NSNumber numberWithBool: YES] + forKey: NSURLIsExcludedFromBackupKey error:nil]; + +} + +- (void)registerExtraFileSystems:(NSArray *)filesystems fromAvailableSet:(NSDictionary *)availableFileSystems +{ + NSMutableSet *installedFilesystems = [[NSMutableSet alloc] initWithCapacity:7]; + + /* Build non-syncable directories as necessary */ + for (NSString *nonSyncFS in @[@"library-nosync", @"documents-nosync"]) { + if ([filesystems containsObject:nonSyncFS]) { + [self makeNonSyncable:availableFileSystems[nonSyncFS]]; + } + } + + /* Register filesystems in order */ + for (NSString *fsName in filesystems) { + if (![installedFilesystems containsObject:fsName]) { + NSString *fsRoot = availableFileSystems[fsName]; + if (fsRoot) { + [filePlugin registerFilesystem:[[CDVLocalFilesystem alloc] initWithName:fsName root:fsRoot]]; + [installedFilesystems addObject:fsName]; + } else { + NSLog(@"Unrecognized extra filesystem identifier: %@", fsName); + } + } + } +} + +- (NSDictionary *)getAvailableFileSystems +{ + NSString *libPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0]; + NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; + return @{ + @"library": libPath, + @"library-nosync": [libPath stringByAppendingPathComponent:@"NoCloud"], + @"documents": docPath, + @"documents-nosync": [docPath stringByAppendingPathComponent:@"NoCloud"], + @"cache": [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0], + @"bundle": [[NSBundle mainBundle] bundlePath], + @"root": @"/" + }; +} + +- (void)pluginInitialize +{ + filePlugin = self; + [NSURLProtocol registerClass:[CDVFilesystemURLProtocol class]]; + + fileSystems_ = [[NSMutableArray alloc] initWithCapacity:3]; + + // Get the Library directory path + NSArray* paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES); + self.appLibraryPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"files"]; + + // Get the Temporary directory path + self.appTempPath = [NSTemporaryDirectory()stringByStandardizingPath]; // remove trailing slash from NSTemporaryDirectory() + + // Get the Documents directory path + paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); + self.rootDocsPath = [paths objectAtIndex:0]; + self.appDocsPath = [self.rootDocsPath stringByAppendingPathComponent:@"files"]; + + + NSString *location = nil; + if([self.viewController isKindOfClass:[CDVViewController class]]) { + CDVViewController *vc = (CDVViewController *)self.viewController; + NSMutableDictionary *settings = vc.settings; + location = [[settings objectForKey:@"iospersistentfilelocation"] lowercaseString]; + } + if (location == nil) { + // Compatibilty by default (if the config preference is not set, or + // if we're not embedded in a CDVViewController somehow.) + location = @"compatibility"; + } + + NSError *error; + if ([[NSFileManager defaultManager] createDirectoryAtPath:self.appTempPath + withIntermediateDirectories:YES + attributes:nil + error:&error]) { + [self registerFilesystem:[[CDVLocalFilesystem alloc] initWithName:@"temporary" root:self.appTempPath]]; + } else { + NSLog(@"Unable to create temporary directory: %@", error); + } + if ([location isEqualToString:@"library"]) { + if ([[NSFileManager defaultManager] createDirectoryAtPath:self.appLibraryPath + withIntermediateDirectories:YES + attributes:nil + error:&error]) { + [self registerFilesystem:[[CDVLocalFilesystem alloc] initWithName:@"persistent" root:self.appLibraryPath]]; + } else { + NSLog(@"Unable to create library directory: %@", error); + } + } else if ([location isEqualToString:@"compatibility"]) { + /* + * Fall-back to compatibility mode -- this is the logic implemented in + * earlier versions of this plugin, and should be maintained here so + * that apps which were originally deployed with older versions of the + * plugin can continue to provide access to files stored under those + * versions. + */ + [self registerFilesystem:[[CDVLocalFilesystem alloc] initWithName:@"persistent" root:self.rootDocsPath]]; + } else { + NSAssert(false, + @"File plugin configuration error: Please set iosPersistentFileLocation in config.xml to one of \"library\" (for new applications) or \"compatibility\" (for compatibility with previous versions)"); + } + [self registerFilesystem:[[CDVAssetLibraryFilesystem alloc] initWithName:@"assets-library"]]; + + [self registerExtraFileSystems:[self getExtraFileSystemsPreference:self.viewController] + fromAvailableSet:[self getAvailableFileSystems]]; + +} + +- (CDVFilesystemURL *)fileSystemURLforArg:(NSString *)urlArg +{ + CDVFilesystemURL* ret = nil; + if ([urlArg hasPrefix:@"file://"]) { + /* This looks like a file url. Get the path, and see if any handlers recognize it. */ + NSURL *fileURL = [NSURL URLWithString:urlArg]; + NSURL *resolvedFileURL = [fileURL URLByResolvingSymlinksInPath]; + NSString *path = [resolvedFileURL path]; + ret = [self fileSystemURLforLocalPath:path]; + } else { + ret = [CDVFilesystemURL fileSystemURLWithString:urlArg]; + } + return ret; +} + +- (CDVFilesystemURL *)fileSystemURLforLocalPath:(NSString *)localPath +{ + CDVFilesystemURL *localURL = nil; + NSUInteger shortestFullPath = 0; + + // Try all installed filesystems, in order. Return the most match url. + for (id object in self.fileSystems) { + if ([object respondsToSelector:@selector(URLforFilesystemPath:)]) { + CDVFilesystemURL *url = [object URLforFilesystemPath:localPath]; + if (url){ + // A shorter fullPath would imply that the filesystem is a better match for the local path + if (!localURL || ([[url fullPath] length] < shortestFullPath)) { + localURL = url; + shortestFullPath = [[url fullPath] length]; + } + } + } + } + return localURL; +} + +- (NSNumber*)checkFreeDiskSpace:(NSString*)appPath +{ + NSFileManager* fMgr = [[NSFileManager alloc] init]; + + NSError* __autoreleasing pError = nil; + + NSDictionary* pDict = [fMgr attributesOfFileSystemForPath:appPath error:&pError]; + NSNumber* pNumAvail = (NSNumber*)[pDict objectForKey:NSFileSystemFreeSize]; + + return pNumAvail; +} + +/* Request the File System info + * + * IN: + * arguments[0] - type (number as string) + * TEMPORARY = 0, PERSISTENT = 1; + * arguments[1] - size + * + * OUT: + * Dictionary representing FileSystem object + * name - the human readable directory name + * root = DirectoryEntry object + * bool isDirectory + * bool isFile + * string name + * string fullPath + * fileSystem = FileSystem object - !! ignored because creates circular reference !! + */ + +- (void)requestFileSystem:(CDVInvokedUrlCommand*)command +{ + // arguments + NSString* strType = [command argumentAtIndex:0]; + unsigned long long size = [[command argumentAtIndex:1] longLongValue]; + + int type = [strType intValue]; + CDVPluginResult* result = nil; + + if (type >= self.fileSystems.count) { + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsInt:NOT_FOUND_ERR]; + NSLog(@"No filesystem of type requested"); + } else { + NSString* fullPath = @"/"; + // check for avail space for size request + NSNumber* pNumAvail = [self checkFreeDiskSpace:self.rootDocsPath]; + // NSLog(@"Free space: %@", [NSString stringWithFormat:@"%qu", [ pNumAvail unsignedLongLongValue ]]); + if (pNumAvail && ([pNumAvail unsignedLongLongValue] < size)) { + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:QUOTA_EXCEEDED_ERR]; + } else { + NSObject *rootFs = [self.fileSystems objectAtIndex:type]; + if (rootFs == nil) { + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsInt:NOT_FOUND_ERR]; + NSLog(@"No filesystem of type requested"); + } else { + NSMutableDictionary* fileSystem = [NSMutableDictionary dictionaryWithCapacity:2]; + [fileSystem setObject:rootFs.name forKey:@"name"]; + NSDictionary* dirEntry = [self makeEntryForPath:fullPath fileSystemName:rootFs.name isDirectory:YES]; + [fileSystem setObject:dirEntry forKey:@"root"]; + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:fileSystem]; + } + } + } + [self.commandDelegate sendPluginResult:result callbackId:command.callbackId]; +} + + +- (void)requestAllFileSystems:(CDVInvokedUrlCommand*)command +{ + NSMutableArray* ret = [[NSMutableArray alloc] init]; + for (NSObject* root in fileSystems_) { + [ret addObject:[self makeEntryForPath:@"/" fileSystemName:root.name isDirectory:YES]]; + } + CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:ret]; + [self.commandDelegate sendPluginResult:result callbackId:command.callbackId]; +} + +- (void)requestAllPaths:(CDVInvokedUrlCommand*)command +{ + NSString* libPath = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES)[0]; + NSString* libPathSync = [libPath stringByAppendingPathComponent:@"Cloud"]; + NSString* libPathNoSync = [libPath stringByAppendingPathComponent:@"NoCloud"]; + NSString* docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; + NSString* storagePath = [libPath stringByDeletingLastPathComponent]; + NSString* cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0]; + + // Create the directories if necessary. + [[NSFileManager defaultManager] createDirectoryAtPath:libPathSync withIntermediateDirectories:YES attributes:nil error:nil]; + [[NSFileManager defaultManager] createDirectoryAtPath:libPathNoSync withIntermediateDirectories:YES attributes:nil error:nil]; + // Mark NoSync as non-iCloud. + [[NSURL fileURLWithPath:libPathNoSync] setResourceValue: [NSNumber numberWithBool: YES] + forKey: NSURLIsExcludedFromBackupKey error:nil]; + + NSDictionary* ret = @{ + @"applicationDirectory": [[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]] absoluteString], + @"applicationStorageDirectory": [[NSURL fileURLWithPath:storagePath] absoluteString], + @"dataDirectory": [[NSURL fileURLWithPath:libPathNoSync] absoluteString], + @"syncedDataDirectory": [[NSURL fileURLWithPath:libPathSync] absoluteString], + @"documentsDirectory": [[NSURL fileURLWithPath:docPath] absoluteString], + @"cacheDirectory": [[NSURL fileURLWithPath:cachePath] absoluteString], + @"tempDirectory": [[NSURL fileURLWithPath:NSTemporaryDirectory()] absoluteString] + }; + + CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:ret]; + [self.commandDelegate sendPluginResult:result callbackId:command.callbackId]; +} + +/* Creates and returns a dictionary representing an Entry Object + * + * IN: + * NSString* fullPath of the entry + * int fsType - FileSystem type + * BOOL isDirectory - YES if this is a directory, NO if is a file + * OUT: + * NSDictionary* Entry object + * bool as NSNumber isDirectory + * bool as NSNumber isFile + * NSString* name - last part of path + * NSString* fullPath + * NSString* filesystemName - FileSystem name -- actual filesystem will be created on the JS side if necessary, to avoid + * creating circular reference (FileSystem contains DirectoryEntry which contains FileSystem.....!!) + */ +- (NSDictionary*)makeEntryForPath:(NSString*)fullPath fileSystemName:(NSString *)fsName isDirectory:(BOOL)isDir +{ + NSObject *fs = [self fileSystemByName:fsName]; + return [fs makeEntryForPath:fullPath isDirectory:isDir]; +} + +- (NSDictionary *)makeEntryForLocalURL:(CDVFilesystemURL *)localURL +{ + NSObject *fs = [self filesystemForURL:localURL]; + return [fs makeEntryForLocalURL:localURL]; +} + +- (NSDictionary *)makeEntryForURL:(NSURL *)URL +{ + CDVFilesystemURL* fsURL = [self fileSystemURLforArg:[URL absoluteString]]; + return [self makeEntryForLocalURL:fsURL]; +} + +/* + * Given a URI determine the File System information associated with it and return an appropriate W3C entry object + * IN + * NSString* localURI: Should be an escaped local filesystem URI + * OUT + * Entry object + * bool isDirectory + * bool isFile + * string name + * string fullPath + * fileSystem = FileSystem object - !! ignored because creates circular reference FileSystem contains DirectoryEntry which contains FileSystem.....!! + */ +- (void)resolveLocalFileSystemURI:(CDVInvokedUrlCommand*)command +{ + // arguments + NSString* localURIstr = [command argumentAtIndex:0]; + CDVPluginResult* result; + + localURIstr = [self encodePath:localURIstr]; //encode path before resolving + CDVFilesystemURL* inputURI = [self fileSystemURLforArg:localURIstr]; + + if (inputURI == nil || inputURI.fileSystemName == nil) { + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsInt:ENCODING_ERR]; + } else { + NSObject *fs = [self filesystemForURL:inputURI]; + if (fs == nil) { + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsInt:ENCODING_ERR]; + } else { + result = [fs entryForLocalURI:inputURI]; + } + } + [self.commandDelegate sendPluginResult:result callbackId:command.callbackId]; +} + +//encode path with percent escapes +-(NSString *)encodePath:(NSString *)path +{ + NSString *decodedPath = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; //decode incase it's already encoded to avoid encoding twice + return [decodedPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; +} + + +/* Part of DirectoryEntry interface, creates or returns the specified directory + * IN: + * NSString* localURI - local filesystem URI for this directory + * NSString* path - directory to be created/returned; may be full path or relative path + * NSDictionary* - Flags object + * boolean as NSNumber create - + * if create is true and directory does not exist, create dir and return directory entry + * if create is true and exclusive is true and directory does exist, return error + * if create is false and directory does not exist, return error + * if create is false and the path represents a file, return error + * boolean as NSNumber exclusive - used in conjunction with create + * if exclusive is true and create is true - specifies failure if directory already exists + * + * + */ +- (void)getDirectory:(CDVInvokedUrlCommand*)command +{ + NSMutableArray* arguments = [NSMutableArray arrayWithArray:command.arguments]; + NSMutableDictionary* options = nil; + + if ([arguments count] >= 3) { + options = [command argumentAtIndex:2 withDefault:nil]; + } + // add getDir to options and call getFile() + if (options != nil) { + options = [NSMutableDictionary dictionaryWithDictionary:options]; + } else { + options = [NSMutableDictionary dictionaryWithCapacity:1]; + } + [options setObject:[NSNumber numberWithInt:1] forKey:@"getDir"]; + if ([arguments count] >= 3) { + [arguments replaceObjectAtIndex:2 withObject:options]; + } else { + [arguments addObject:options]; + } + CDVInvokedUrlCommand* subCommand = + [[CDVInvokedUrlCommand alloc] initWithArguments:arguments + callbackId:command.callbackId + className:command.className + methodName:command.methodName]; + + [self getFile:subCommand]; +} + +/* Part of DirectoryEntry interface, creates or returns the specified file + * IN: + * NSString* baseURI - local filesytem URI for the base directory to search + * NSString* requestedPath - file to be created/returned; may be absolute path or relative path + * NSDictionary* options - Flags object + * boolean as NSNumber create - + * if create is true and file does not exist, create file and return File entry + * if create is true and exclusive is true and file does exist, return error + * if create is false and file does not exist, return error + * if create is false and the path represents a directory, return error + * boolean as NSNumber exclusive - used in conjunction with create + * if exclusive is true and create is true - specifies failure if file already exists + */ +- (void)getFile:(CDVInvokedUrlCommand*)command +{ + NSString* baseURIstr = [command argumentAtIndex:0]; + CDVFilesystemURL* baseURI = [self fileSystemURLforArg:baseURIstr]; + NSString* requestedPath = [command argumentAtIndex:1]; + NSDictionary* options = [command argumentAtIndex:2 withDefault:nil]; + + NSObject *fs = [self filesystemForURL:baseURI]; + CDVPluginResult* result = [fs getFileForURL:baseURI requestedPath:requestedPath options:options]; + + + [self.commandDelegate sendPluginResult:result callbackId:command.callbackId]; +} + +/* + * Look up the parent Entry containing this Entry. + * If this Entry is the root of its filesystem, its parent is itself. + * IN: + * NSArray* arguments + * 0 - NSString* localURI + * NSMutableDictionary* options + * empty + */ +- (void)getParent:(CDVInvokedUrlCommand*)command +{ + // arguments are URL encoded + CDVFilesystemURL* localURI = [self fileSystemURLforArg:command.arguments[0]]; + + NSObject *fs = [self filesystemForURL:localURI]; + CDVPluginResult* result = [fs getParentForURL:localURI]; + + [self.commandDelegate sendPluginResult:result callbackId:command.callbackId]; +} + +/* + * set MetaData of entry + * Currently we only support "com.apple.MobileBackup" (boolean) + */ +- (void)setMetadata:(CDVInvokedUrlCommand*)command +{ + // arguments + CDVFilesystemURL* localURI = [self fileSystemURLforArg:command.arguments[0]]; + NSDictionary* options = [command argumentAtIndex:1 withDefault:nil]; + NSObject *fs = [self filesystemForURL:localURI]; + CDVPluginResult* result = [fs setMetadataForURL:localURI withObject:options]; + + [self.commandDelegate sendPluginResult:result callbackId:command.callbackId]; +} + +/* removes the directory or file entry + * IN: + * NSArray* arguments + * 0 - NSString* localURI + * + * returns NO_MODIFICATION_ALLOWED_ERR if is top level directory or no permission to delete dir + * returns INVALID_MODIFICATION_ERR if is non-empty dir or asset library file + * returns NOT_FOUND_ERR if file or dir is not found +*/ +- (void)remove:(CDVInvokedUrlCommand*)command +{ + // arguments + CDVFilesystemURL* localURI = [self fileSystemURLforArg:command.arguments[0]]; + CDVPluginResult* result = nil; + + if ([localURI.fullPath isEqualToString:@""]) { + // error if try to remove top level (documents or tmp) dir + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NO_MODIFICATION_ALLOWED_ERR]; + } else { + NSObject *fs = [self filesystemForURL:localURI]; + result = [fs removeFileAtURL:localURI]; + } + [self.commandDelegate sendPluginResult:result callbackId:command.callbackId]; +} + +/* recursively removes the directory + * IN: + * NSArray* arguments + * 0 - NSString* localURI + * + * returns NO_MODIFICATION_ALLOWED_ERR if is top level directory or no permission to delete dir + * returns NOT_FOUND_ERR if file or dir is not found + */ +- (void)removeRecursively:(CDVInvokedUrlCommand*)command +{ + // arguments + CDVFilesystemURL* localURI = [self fileSystemURLforArg:command.arguments[0]]; + CDVPluginResult* result = nil; + + if ([localURI.fullPath isEqualToString:@""]) { + // error if try to remove top level (documents or tmp) dir + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NO_MODIFICATION_ALLOWED_ERR]; + } else { + NSObject *fs = [self filesystemForURL:localURI]; + result = [fs recursiveRemoveFileAtURL:localURI]; + } + [self.commandDelegate sendPluginResult:result callbackId:command.callbackId]; +} + +- (void)copyTo:(CDVInvokedUrlCommand*)command +{ + [self doCopyMove:command isCopy:YES]; +} + +- (void)moveTo:(CDVInvokedUrlCommand*)command +{ + [self doCopyMove:command isCopy:NO]; +} + +/* Copy/move a file or directory to a new location + * IN: + * NSArray* arguments + * 0 - NSString* URL of entry to copy + * 1 - NSString* URL of the directory into which to copy/move the entry + * 2 - Optionally, the new name of the entry, defaults to the current name + * BOOL - bCopy YES if copy, NO if move + */ +- (void)doCopyMove:(CDVInvokedUrlCommand*)command isCopy:(BOOL)bCopy +{ + NSArray* arguments = command.arguments; + + // arguments + NSString* srcURLstr = [command argumentAtIndex:0]; + NSString* destURLstr = [command argumentAtIndex:1]; + + CDVPluginResult *result; + + if (!srcURLstr || !destURLstr) { + // either no source or no destination provided + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NOT_FOUND_ERR]; + [self.commandDelegate sendPluginResult:result callbackId:command.callbackId]; + return; + } + + CDVFilesystemURL* srcURL = [self fileSystemURLforArg:srcURLstr]; + CDVFilesystemURL* destURL = [self fileSystemURLforArg:destURLstr]; + + NSObject *srcFs = [self filesystemForURL:srcURL]; + NSObject *destFs = [self filesystemForURL:destURL]; + + // optional argument; use last component from srcFullPath if new name not provided + NSString* newName = ([arguments count] > 2) ? [command argumentAtIndex:2] : [srcURL.url lastPathComponent]; + if ([newName rangeOfString:@":"].location != NSNotFound) { + // invalid chars in new name + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:ENCODING_ERR]; + [self.commandDelegate sendPluginResult:result callbackId:command.callbackId]; + return; + } + + __weak CDVFile* weakSelf = self; + [self.commandDelegate runInBackground:^ { + [destFs copyFileToURL:destURL withName:newName fromFileSystem:srcFs atURL:srcURL copy:bCopy callback:^(CDVPluginResult* result) { + [weakSelf.commandDelegate sendPluginResult:result callbackId:command.callbackId]; + }]; + }]; + +} + +- (void)getFileMetadata:(CDVInvokedUrlCommand*)command +{ + // arguments + CDVFilesystemURL* localURI = [self fileSystemURLforArg:command.arguments[0]]; + NSObject *fs = [self filesystemForURL:localURI]; + __weak CDVFile* weakSelf = self; + [fs getFileMetadataForURL:localURI callback:^(CDVPluginResult* result) { + [weakSelf.commandDelegate sendPluginResult:result callbackId:command.callbackId]; + }]; +} + +- (void)readEntries:(CDVInvokedUrlCommand*)command +{ + CDVFilesystemURL* localURI = [self fileSystemURLforArg:command.arguments[0]]; + NSObject *fs = [self filesystemForURL:localURI]; + CDVPluginResult *result = [fs readEntriesAtURL:localURI]; + + [self.commandDelegate sendPluginResult:result callbackId:command.callbackId]; +} + +/* read and return file data + * IN: + * NSArray* arguments + * 0 - NSString* fullPath + * 1 - NSString* encoding + * 2 - NSString* start + * 3 - NSString* end + */ +- (void)readAsText:(CDVInvokedUrlCommand*)command +{ + // arguments + CDVFilesystemURL* localURI = [self fileSystemURLforArg:command.arguments[0]]; + NSString* encoding = [command argumentAtIndex:1]; + NSInteger start = [[command argumentAtIndex:2] integerValue]; + NSInteger end = [[command argumentAtIndex:3] integerValue]; + + NSObject *fs = [self filesystemForURL:localURI]; + + if (fs == nil) { + CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NOT_FOUND_ERR]; + [self.commandDelegate sendPluginResult:result callbackId:command.callbackId]; + return; + } + + // TODO: implement + if ([@"UTF-8" caseInsensitiveCompare : encoding] != NSOrderedSame) { + NSLog(@"Only UTF-8 encodings are currently supported by readAsText"); + CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:ENCODING_ERR]; + [self.commandDelegate sendPluginResult:result callbackId:command.callbackId]; + return; + } + + __weak CDVFile* weakSelf = self; + + [self.commandDelegate runInBackground:^ { + [fs readFileAtURL:localURI start:start end:end callback:^(NSData* data, NSString* mimeType, CDVFileError errorCode) { + CDVPluginResult* result = nil; + if (data != nil) { + NSString* str = [[NSString alloc] initWithBytesNoCopy:(void*)[data bytes] length:[data length] encoding:NSUTF8StringEncoding freeWhenDone:NO]; + // Check that UTF8 conversion did not fail. + if (str != nil) { + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:str]; + result.associatedObject = data; + } else { + errorCode = ENCODING_ERR; + } + } + if (result == nil) { + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:errorCode]; + } + + [weakSelf.commandDelegate sendPluginResult:result callbackId:command.callbackId]; + }]; + }]; +} + +/* Read content of text file and return as base64 encoded data url. + * IN: + * NSArray* arguments + * 0 - NSString* fullPath + * 1 - NSString* start + * 2 - NSString* end + * + * Determines the mime type from the file extension, returns ENCODING_ERR if mimetype can not be determined. + */ + +- (void)readAsDataURL:(CDVInvokedUrlCommand*)command +{ + CDVFilesystemURL* localURI = [self fileSystemURLforArg:command.arguments[0]]; + NSInteger start = [[command argumentAtIndex:1] integerValue]; + NSInteger end = [[command argumentAtIndex:2] integerValue]; + + NSObject *fs = [self filesystemForURL:localURI]; + + __weak CDVFile* weakSelf = self; + [self.commandDelegate runInBackground:^ { + [fs readFileAtURL:localURI start:start end:end callback:^(NSData* data, NSString* mimeType, CDVFileError errorCode) { + CDVPluginResult* result = nil; + if (data != nil) { + NSString* b64Str = toBase64(data); + NSString* output = [NSString stringWithFormat:@"data:%@;base64,%@", mimeType, b64Str]; + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:output]; + } else { + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:errorCode]; + } + + [weakSelf.commandDelegate sendPluginResult:result callbackId:command.callbackId]; + }]; + }]; +} + +/* Read content of text file and return as an arraybuffer + * IN: + * NSArray* arguments + * 0 - NSString* fullPath + * 1 - NSString* start + * 2 - NSString* end + */ + +- (void)readAsArrayBuffer:(CDVInvokedUrlCommand*)command +{ + CDVFilesystemURL* localURI = [self fileSystemURLforArg:command.arguments[0]]; + NSInteger start = [[command argumentAtIndex:1] integerValue]; + NSInteger end = [[command argumentAtIndex:2] integerValue]; + + NSObject *fs = [self filesystemForURL:localURI]; + + __weak CDVFile* weakSelf = self; + + [self.commandDelegate runInBackground:^ { + [fs readFileAtURL:localURI start:start end:end callback:^(NSData* data, NSString* mimeType, CDVFileError errorCode) { + CDVPluginResult* result = nil; + if (data != nil) { + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArrayBuffer:data]; + } else { + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:errorCode]; + } + + [weakSelf.commandDelegate sendPluginResult:result callbackId:command.callbackId]; + }]; + }]; +} + +- (void)readAsBinaryString:(CDVInvokedUrlCommand*)command +{ + CDVFilesystemURL* localURI = [self fileSystemURLforArg:command.arguments[0]]; + NSInteger start = [[command argumentAtIndex:1] integerValue]; + NSInteger end = [[command argumentAtIndex:2] integerValue]; + + NSObject *fs = [self filesystemForURL:localURI]; + + __weak CDVFile* weakSelf = self; + + [self.commandDelegate runInBackground:^ { + [fs readFileAtURL:localURI start:start end:end callback:^(NSData* data, NSString* mimeType, CDVFileError errorCode) { + CDVPluginResult* result = nil; + if (data != nil) { + NSString* payload = [[NSString alloc] initWithBytesNoCopy:(void*)[data bytes] length:[data length] encoding:NSASCIIStringEncoding freeWhenDone:NO]; + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:payload]; + result.associatedObject = data; + } else { + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:errorCode]; + } + + [weakSelf.commandDelegate sendPluginResult:result callbackId:command.callbackId]; + }]; + }]; +} + + +- (void)truncate:(CDVInvokedUrlCommand*)command +{ + // arguments + CDVFilesystemURL* localURI = [self fileSystemURLforArg:command.arguments[0]]; + unsigned long long pos = (unsigned long long)[[command argumentAtIndex:1] longLongValue]; + + NSObject *fs = [self filesystemForURL:localURI]; + CDVPluginResult *result = [fs truncateFileAtURL:localURI atPosition:pos]; + + [self.commandDelegate sendPluginResult:result callbackId:command.callbackId]; +} + +/* write + * IN: + * NSArray* arguments + * 0 - NSString* localURI of file to write to + * 1 - NSString* or NSData* data to write + * 2 - NSNumber* position to begin writing + */ +- (void)write:(CDVInvokedUrlCommand*)command +{ + __weak CDVFile* weakSelf = self; + + [self.commandDelegate runInBackground:^ { + NSString* callbackId = command.callbackId; + + // arguments + CDVFilesystemURL* localURI = [self fileSystemURLforArg:command.arguments[0]]; + id argData = [command argumentAtIndex:1]; + unsigned long long pos = (unsigned long long)[[command argumentAtIndex:2] longLongValue]; + + NSObject *fs = [self filesystemForURL:localURI]; + + + [fs truncateFileAtURL:localURI atPosition:pos]; + CDVPluginResult *result; + if ([argData isKindOfClass:[NSString class]]) { + NSData *encData = [argData dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]; + result = [fs writeToFileAtURL:localURI withData:encData append:YES]; + } else if ([argData isKindOfClass:[NSData class]]) { + result = [fs writeToFileAtURL:localURI withData:argData append:YES]; + } else { + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Invalid parameter type"]; + } + [weakSelf.commandDelegate sendPluginResult:result callbackId:callbackId]; + }]; +} + +#pragma mark Methods for converting between URLs and paths + +- (NSString *)filesystemPathForURL:(CDVFilesystemURL *)localURL +{ + for (NSObject *fs in self.fileSystems) { + if ([fs.name isEqualToString:localURL.fileSystemName]) { + if ([fs respondsToSelector:@selector(filesystemPathForURL:)]) { + return [fs filesystemPathForURL:localURL]; + } + } + } + return nil; +} + +#pragma mark Undocumented Filesystem API + +- (void)testFileExists:(CDVInvokedUrlCommand*)command +{ + // arguments + NSString* argPath = [command argumentAtIndex:0]; + + // Get the file manager + NSFileManager* fMgr = [NSFileManager defaultManager]; + NSString* appFile = argPath; // [ self getFullPath: argPath]; + + BOOL bExists = [fMgr fileExistsAtPath:appFile]; + CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:(bExists ? 1 : 0)]; + + [self.commandDelegate sendPluginResult:result callbackId:command.callbackId]; +} + +- (void)testDirectoryExists:(CDVInvokedUrlCommand*)command +{ + // arguments + NSString* argPath = [command argumentAtIndex:0]; + + // Get the file manager + NSFileManager* fMgr = [[NSFileManager alloc] init]; + NSString* appFile = argPath; // [self getFullPath: argPath]; + BOOL bIsDir = NO; + BOOL bExists = [fMgr fileExistsAtPath:appFile isDirectory:&bIsDir]; + + CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:((bExists && bIsDir) ? 1 : 0)]; + + [self.commandDelegate sendPluginResult:result callbackId:command.callbackId]; +} + +// Returns number of bytes available via callback +- (void)getFreeDiskSpace:(CDVInvokedUrlCommand*)command +{ + // no arguments + + NSNumber* pNumAvail = [self checkFreeDiskSpace:self.rootDocsPath]; + + NSString* strFreeSpace = [NSString stringWithFormat:@"%qu", [pNumAvail unsignedLongLongValue]]; + // NSLog(@"Free space is %@", strFreeSpace ); + + CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:strFreeSpace]; + + [self.commandDelegate sendPluginResult:result callbackId:command.callbackId]; +} + +#pragma mark Compatibility with older File API + +- (NSString*)getMimeTypeFromPath:(NSString*)fullPath +{ + return [CDVLocalFilesystem getMimeTypeFromPath:fullPath]; +} + +- (NSDictionary *)getDirectoryEntry:(NSString *)localPath isDirectory:(BOOL)bDirRequest +{ + CDVFilesystemURL *localURL = [self fileSystemURLforLocalPath:localPath]; + return [self makeEntryForPath:localURL.fullPath fileSystemName:localURL.fileSystemName isDirectory:bDirRequest]; +} + +#pragma mark Internal methods for testing +// Internal methods for testing: Get the on-disk location of a local filesystem url. +// [Currently used for testing file-transfer] + +- (void)_getLocalFilesystemPath:(CDVInvokedUrlCommand*)command +{ + CDVFilesystemURL* localURL = [self fileSystemURLforArg:command.arguments[0]]; + + NSString* fsPath = [self filesystemPathForURL:localURL]; + CDVPluginResult* result; + if (fsPath) { + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:fsPath]; + } else { + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Cannot resolve URL to a file"]; + } + [self.commandDelegate sendPluginResult:result callbackId:command.callbackId]; +} + +@end diff --git a/plugins/cordova-plugin-file/src/ios/CDVLocalFilesystem.h b/plugins/cordova-plugin-file/src/ios/CDVLocalFilesystem.h new file mode 100644 index 0000000..a0186c8 --- /dev/null +++ b/plugins/cordova-plugin-file/src/ios/CDVLocalFilesystem.h @@ -0,0 +1,32 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. + */ + +#import "CDVFile.h" + +@interface CDVLocalFilesystem : NSObject { + NSString *_name; + NSString *_fsRoot; +} + +- (id) initWithName:(NSString *)name root:(NSString *)fsRoot; ++ (NSString*)getMimeTypeFromPath:(NSString*)fullPath; + +@property (nonatomic,strong) NSString *fsRoot; + +@end diff --git a/plugins/cordova-plugin-file/src/ios/CDVLocalFilesystem.m b/plugins/cordova-plugin-file/src/ios/CDVLocalFilesystem.m new file mode 100644 index 0000000..35c8db1 --- /dev/null +++ b/plugins/cordova-plugin-file/src/ios/CDVLocalFilesystem.m @@ -0,0 +1,734 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. + */ + +#import "CDVFile.h" +#import "CDVLocalFilesystem.h" +#import +#import +#import + +@implementation CDVLocalFilesystem +@synthesize name=_name, fsRoot=_fsRoot, urlTransformer; + +- (id) initWithName:(NSString *)name root:(NSString *)fsRoot +{ + if (self) { + self.name = name; + self.fsRoot = fsRoot; + } + return self; +} + +/* + * IN + * NSString localURI + * OUT + * CDVPluginResult result containing a file or directoryEntry for the localURI, or an error if the + * URI represents a non-existent path, or is unrecognized or otherwise malformed. + */ +- (CDVPluginResult *)entryForLocalURI:(CDVFilesystemURL *)url +{ + CDVPluginResult* result = nil; + NSDictionary* entry = [self makeEntryForLocalURL:url]; + if (entry) { + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:entry]; + } else { + // return NOT_FOUND_ERR + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NOT_FOUND_ERR]; + } + return result; +} +- (NSDictionary *)makeEntryForLocalURL:(CDVFilesystemURL *)url { + NSString *path = [self filesystemPathForURL:url]; + NSFileManager* fileMgr = [[NSFileManager alloc] init]; + BOOL isDir = NO; + // see if exists and is file or dir + BOOL bExists = [fileMgr fileExistsAtPath:path isDirectory:&isDir]; + if (bExists) { + return [self makeEntryForPath:url.fullPath isDirectory:isDir]; + } else { + return nil; + } +} +- (NSDictionary*)makeEntryForPath:(NSString*)fullPath isDirectory:(BOOL)isDir +{ + NSMutableDictionary* dirEntry = [NSMutableDictionary dictionaryWithCapacity:5]; + NSString* lastPart = [[self stripQueryParametersFromPath:fullPath] lastPathComponent]; + if (isDir && ![fullPath hasSuffix:@"/"]) { + fullPath = [fullPath stringByAppendingString:@"/"]; + } + [dirEntry setObject:[NSNumber numberWithBool:!isDir] forKey:@"isFile"]; + [dirEntry setObject:[NSNumber numberWithBool:isDir] forKey:@"isDirectory"]; + [dirEntry setObject:fullPath forKey:@"fullPath"]; + [dirEntry setObject:lastPart forKey:@"name"]; + [dirEntry setObject:self.name forKey: @"filesystemName"]; + + NSURL* nativeURL = [NSURL fileURLWithPath:[self filesystemPathForFullPath:fullPath]]; + if (self.urlTransformer) { + nativeURL = self.urlTransformer(nativeURL); + } + + dirEntry[@"nativeURL"] = [nativeURL absoluteString]; + + return dirEntry; +} + +- (NSString *)stripQueryParametersFromPath:(NSString *)fullPath +{ + NSRange questionMark = [fullPath rangeOfString:@"?"]; + if (questionMark.location != NSNotFound) { + return [fullPath substringWithRange:NSMakeRange(0,questionMark.location)]; + } + return fullPath; +} + +- (NSString *)filesystemPathForFullPath:(NSString *)fullPath +{ + NSString *path = nil; + NSString *strippedFullPath = [self stripQueryParametersFromPath:fullPath]; + path = [NSString stringWithFormat:@"%@%@", self.fsRoot, strippedFullPath]; + if ([path length] > 1 && [path hasSuffix:@"/"]) { + path = [path substringToIndex:([path length]-1)]; + } + return path; +} +/* + * IN + * NSString localURI + * OUT + * NSString full local filesystem path for the represented file or directory, or nil if no such path is possible + * The file or directory does not necessarily have to exist. nil is returned if the filesystem type is not recognized, + * or if the URL is malformed. + * The incoming URI should be properly escaped (no raw spaces, etc. URI percent-encoding is expected). + */ +- (NSString *)filesystemPathForURL:(CDVFilesystemURL *)url +{ + return [self filesystemPathForFullPath:url.fullPath]; +} + +- (CDVFilesystemURL *)URLforFullPath:(NSString *)fullPath +{ + if (fullPath) { + NSString* escapedPath = [fullPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + if ([fullPath hasPrefix:@"/"]) { + return [CDVFilesystemURL fileSystemURLWithString:[NSString stringWithFormat:@"%@://localhost/%@%@", kCDVFilesystemURLPrefix, self.name, escapedPath]]; + } + return [CDVFilesystemURL fileSystemURLWithString:[NSString stringWithFormat:@"%@://localhost/%@/%@", kCDVFilesystemURLPrefix, self.name, escapedPath]]; + } + return nil; +} + +- (CDVFilesystemURL *)URLforFilesystemPath:(NSString *)path +{ + return [self URLforFullPath:[self fullPathForFileSystemPath:path]]; + +} + +- (NSString *)normalizePath:(NSString *)rawPath +{ + // If this is an absolute path, the first path component will be '/'. Skip it if that's the case + BOOL isAbsolutePath = [rawPath hasPrefix:@"/"]; + if (isAbsolutePath) { + rawPath = [rawPath substringFromIndex:1]; + } + NSMutableArray *components = [NSMutableArray arrayWithArray:[rawPath pathComponents]]; + for (int index = 0; index < [components count]; ++index) { + if ([[components objectAtIndex:index] isEqualToString:@".."]) { + [components removeObjectAtIndex:index]; + if (index > 0) { + [components removeObjectAtIndex:index-1]; + --index; + } + } + } + + if (isAbsolutePath) { + return [NSString stringWithFormat:@"/%@", [components componentsJoinedByString:@"/"]]; + } else { + return [components componentsJoinedByString:@"/"]; + } + + +} + +- (BOOL)valueForKeyIsNumber:(NSDictionary*)dict key:(NSString*)key +{ + BOOL bNumber = NO; + NSObject* value = dict[key]; + if (value) { + bNumber = [value isKindOfClass:[NSNumber class]]; + } + return bNumber; +} + +- (CDVPluginResult *)getFileForURL:(CDVFilesystemURL *)baseURI requestedPath:(NSString *)requestedPath options:(NSDictionary *)options +{ + CDVPluginResult* result = nil; + BOOL bDirRequest = NO; + BOOL create = NO; + BOOL exclusive = NO; + int errorCode = 0; // !!! risky - no error code currently defined for 0 + + if ([self valueForKeyIsNumber:options key:@"create"]) { + create = [(NSNumber*)[options valueForKey:@"create"] boolValue]; + } + if ([self valueForKeyIsNumber:options key:@"exclusive"]) { + exclusive = [(NSNumber*)[options valueForKey:@"exclusive"] boolValue]; + } + if ([self valueForKeyIsNumber:options key:@"getDir"]) { + // this will not exist for calls directly to getFile but will have been set by getDirectory before calling this method + bDirRequest = [(NSNumber*)[options valueForKey:@"getDir"] boolValue]; + } + // see if the requested path has invalid characters - should we be checking for more than just ":"? + if ([requestedPath rangeOfString:@":"].location != NSNotFound) { + errorCode = ENCODING_ERR; + } else { + // Build new fullPath for the requested resource. + // We concatenate the two paths together, and then scan the resulting string to remove + // parent ("..") references. Any parent references at the beginning of the string are + // silently removed. + NSString *combinedPath = [baseURI.fullPath stringByAppendingPathComponent:requestedPath]; + combinedPath = [self normalizePath:combinedPath]; + CDVFilesystemURL* requestedURL = [self URLforFullPath:combinedPath]; + + NSFileManager* fileMgr = [[NSFileManager alloc] init]; + BOOL bIsDir; + BOOL bExists = [fileMgr fileExistsAtPath:[self filesystemPathForURL:requestedURL] isDirectory:&bIsDir]; + if (bExists && (create == NO) && (bIsDir == !bDirRequest)) { + // path exists and is not of requested type - return TYPE_MISMATCH_ERR + errorCode = TYPE_MISMATCH_ERR; + } else if (!bExists && (create == NO)) { + // path does not exist and create is false - return NOT_FOUND_ERR + errorCode = NOT_FOUND_ERR; + } else if (bExists && (create == YES) && (exclusive == YES)) { + // file/dir already exists and exclusive and create are both true - return PATH_EXISTS_ERR + errorCode = PATH_EXISTS_ERR; + } else { + // if bExists and create == YES - just return data + // if bExists and create == NO - just return data + // if !bExists and create == YES - create and return data + BOOL bSuccess = YES; + NSError __autoreleasing* pError = nil; + if (!bExists && (create == YES)) { + if (bDirRequest) { + // create the dir + bSuccess = [fileMgr createDirectoryAtPath:[self filesystemPathForURL:requestedURL] withIntermediateDirectories:NO attributes:nil error:&pError]; + } else { + // create the empty file + bSuccess = [fileMgr createFileAtPath:[self filesystemPathForURL:requestedURL] contents:nil attributes:nil]; + } + } + if (!bSuccess) { + errorCode = ABORT_ERR; + if (pError) { + NSLog(@"error creating directory: %@", [pError localizedDescription]); + } + } else { + // NSLog(@"newly created file/dir (%@) exists: %d", reqFullPath, [fileMgr fileExistsAtPath:reqFullPath]); + // file existed or was created + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:[self makeEntryForPath:requestedURL.fullPath isDirectory:bDirRequest]]; + } + } // are all possible conditions met? + } + + if (errorCode > 0) { + // create error callback + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:errorCode]; + } + return result; + +} + +- (CDVPluginResult*)getParentForURL:(CDVFilesystemURL *)localURI +{ + CDVPluginResult* result = nil; + CDVFilesystemURL *newURI = nil; + if ([localURI.fullPath isEqualToString:@""]) { + // return self + newURI = localURI; + } else { + newURI = [CDVFilesystemURL fileSystemURLWithURL:[localURI.url URLByDeletingLastPathComponent]]; /* TODO: UGLY - FIX */ + } + NSFileManager* fileMgr = [[NSFileManager alloc] init]; + BOOL bIsDir; + BOOL bExists = [fileMgr fileExistsAtPath:[self filesystemPathForURL:newURI] isDirectory:&bIsDir]; + if (bExists) { + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:[self makeEntryForPath:newURI.fullPath isDirectory:bIsDir]]; + } else { + // invalid path or file does not exist + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NOT_FOUND_ERR]; + } + return result; +} + +- (CDVPluginResult*)setMetadataForURL:(CDVFilesystemURL *)localURI withObject:(NSDictionary *)options +{ + BOOL ok = NO; + + NSString* filePath = [self filesystemPathForURL:localURI]; + // we only care about this iCloud key for now. + // set to 1/true to skip backup, set to 0/false to back it up (effectively removing the attribute) + NSString* iCloudBackupExtendedAttributeKey = @"com.apple.MobileBackup"; + id iCloudBackupExtendedAttributeValue = [options objectForKey:iCloudBackupExtendedAttributeKey]; + + if ((iCloudBackupExtendedAttributeValue != nil) && [iCloudBackupExtendedAttributeValue isKindOfClass:[NSNumber class]]) { + if (IsAtLeastiOSVersion(@"5.1")) { + NSURL* url = [NSURL fileURLWithPath:filePath]; + NSError* __autoreleasing error = nil; + + ok = [url setResourceValue:[NSNumber numberWithBool:[iCloudBackupExtendedAttributeValue boolValue]] forKey:NSURLIsExcludedFromBackupKey error:&error]; + } else { // below 5.1 (deprecated - only really supported in 5.01) + u_int8_t value = [iCloudBackupExtendedAttributeValue intValue]; + if (value == 0) { // remove the attribute (allow backup, the default) + ok = (removexattr([filePath fileSystemRepresentation], [iCloudBackupExtendedAttributeKey cStringUsingEncoding:NSUTF8StringEncoding], 0) == 0); + } else { // set the attribute (skip backup) + ok = (setxattr([filePath fileSystemRepresentation], [iCloudBackupExtendedAttributeKey cStringUsingEncoding:NSUTF8StringEncoding], &value, sizeof(value), 0, 0) == 0); + } + } + } + + if (ok) { + return [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; + } else { + return [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR]; + } +} + +/* remove the file or directory (recursively) + * IN: + * NSString* fullPath - the full path to the file or directory to be removed + * NSString* callbackId + * called from remove and removeRecursively - check all pubic api specific error conditions (dir not empty, etc) before calling + */ + +- (CDVPluginResult*)doRemove:(NSString*)fullPath +{ + CDVPluginResult* result = nil; + BOOL bSuccess = NO; + NSError* __autoreleasing pError = nil; + NSFileManager* fileMgr = [[NSFileManager alloc] init]; + + @try { + bSuccess = [fileMgr removeItemAtPath:fullPath error:&pError]; + if (bSuccess) { + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; + } else { + // see if we can give a useful error + CDVFileError errorCode = ABORT_ERR; + NSLog(@"error removing filesystem entry at %@: %@", fullPath, [pError localizedDescription]); + if ([pError code] == NSFileNoSuchFileError) { + errorCode = NOT_FOUND_ERR; + } else if ([pError code] == NSFileWriteNoPermissionError) { + errorCode = NO_MODIFICATION_ALLOWED_ERR; + } + + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:errorCode]; + } + } @catch(NSException* e) { // NSInvalidArgumentException if path is . or .. + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsInt:SYNTAX_ERR]; + } + + return result; +} + +- (CDVPluginResult *)removeFileAtURL:(CDVFilesystemURL *)localURI +{ + NSString *fileSystemPath = [self filesystemPathForURL:localURI]; + + NSFileManager* fileMgr = [[NSFileManager alloc] init]; + BOOL bIsDir = NO; + BOOL bExists = [fileMgr fileExistsAtPath:fileSystemPath isDirectory:&bIsDir]; + if (!bExists) { + return [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NOT_FOUND_ERR]; + } + if (bIsDir && ([[fileMgr contentsOfDirectoryAtPath:fileSystemPath error:nil] count] != 0)) { + // dir is not empty + return [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:INVALID_MODIFICATION_ERR]; + } + return [self doRemove:fileSystemPath]; +} + +- (CDVPluginResult *)recursiveRemoveFileAtURL:(CDVFilesystemURL *)localURI +{ + NSString *fileSystemPath = [self filesystemPathForURL:localURI]; + return [self doRemove:fileSystemPath]; +} + +/* + * IN + * NSString localURI + * OUT + * NSString full local filesystem path for the represented file or directory, or nil if no such path is possible + * The file or directory does not necessarily have to exist. nil is returned if the filesystem type is not recognized, + * or if the URL is malformed. + * The incoming URI should be properly escaped (no raw spaces, etc. URI percent-encoding is expected). + */ +- (NSString *)fullPathForFileSystemPath:(NSString *)fsPath +{ + if ([fsPath hasPrefix:self.fsRoot]) { + return [fsPath substringFromIndex:[self.fsRoot length]]; + } + return nil; +} + + +- (CDVPluginResult *)readEntriesAtURL:(CDVFilesystemURL *)localURI +{ + NSFileManager* fileMgr = [[NSFileManager alloc] init]; + NSError* __autoreleasing error = nil; + NSString *fileSystemPath = [self filesystemPathForURL:localURI]; + + NSArray* contents = [fileMgr contentsOfDirectoryAtPath:fileSystemPath error:&error]; + + if (contents) { + NSMutableArray* entries = [NSMutableArray arrayWithCapacity:1]; + if ([contents count] > 0) { + // create an Entry (as JSON) for each file/dir + for (NSString* name in contents) { + // see if is dir or file + NSString* entryPath = [fileSystemPath stringByAppendingPathComponent:name]; + BOOL bIsDir = NO; + [fileMgr fileExistsAtPath:entryPath isDirectory:&bIsDir]; + NSDictionary* entryDict = [self makeEntryForPath:[self fullPathForFileSystemPath:entryPath] isDirectory:bIsDir]; + [entries addObject:entryDict]; + } + } + return [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:entries]; + } else { + // assume not found but could check error for more specific error conditions + return [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NOT_FOUND_ERR]; + } +} + +- (unsigned long long)truncateFile:(NSString*)filePath atPosition:(unsigned long long)pos +{ + unsigned long long newPos = 0UL; + + NSFileHandle* file = [NSFileHandle fileHandleForWritingAtPath:filePath]; + + if (file) { + [file truncateFileAtOffset:(unsigned long long)pos]; + newPos = [file offsetInFile]; + [file synchronizeFile]; + [file closeFile]; + } + return newPos; +} + +- (CDVPluginResult *)truncateFileAtURL:(CDVFilesystemURL *)localURI atPosition:(unsigned long long)pos +{ + unsigned long long newPos = [self truncateFile:[self filesystemPathForURL:localURI] atPosition:pos]; + return [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:(int)newPos]; +} + +- (CDVPluginResult *)writeToFileAtURL:(CDVFilesystemURL *)localURL withData:(NSData*)encData append:(BOOL)shouldAppend +{ + NSString *filePath = [self filesystemPathForURL:localURL]; + + CDVPluginResult* result = nil; + CDVFileError errCode = INVALID_MODIFICATION_ERR; + int bytesWritten = 0; + + if (filePath) { + NSOutputStream* fileStream = [NSOutputStream outputStreamToFileAtPath:filePath append:shouldAppend]; + if (fileStream) { + NSUInteger len = [encData length]; + if (len == 0) { + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDouble:(double)len]; + } else { + [fileStream open]; + + bytesWritten = (int)[fileStream write:[encData bytes] maxLength:len]; + + [fileStream close]; + if (bytesWritten > 0) { + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:bytesWritten]; + // } else { + // can probably get more detailed error info via [fileStream streamError] + // errCode already set to INVALID_MODIFICATION_ERR; + // bytesWritten = 0; // may be set to -1 on error + } + } + } // else fileStream not created return INVALID_MODIFICATION_ERR + } else { + // invalid filePath + errCode = NOT_FOUND_ERR; + } + if (!result) { + // was an error + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsInt:errCode]; + } + return result; +} + +/** + * Helper function to check to see if the user attempted to copy an entry into its parent without changing its name, + * or attempted to copy a directory into a directory that it contains directly or indirectly. + * + * IN: + * NSString* srcDir + * NSString* destinationDir + * OUT: + * YES copy/ move is allows + * NO move is onto itself + */ +- (BOOL)canCopyMoveSrc:(NSString*)src ToDestination:(NSString*)dest +{ + // This weird test is to determine if we are copying or moving a directory into itself. + // Copy /Documents/myDir to /Documents/myDir-backup is okay but + // Copy /Documents/myDir to /Documents/myDir/backup not okay + BOOL copyOK = YES; + NSRange range = [dest rangeOfString:src]; + + if (range.location != NSNotFound) { + NSRange testRange = {range.length - 1, ([dest length] - range.length)}; + NSRange resultRange = [dest rangeOfString:@"/" options:0 range:testRange]; + if (resultRange.location != NSNotFound) { + copyOK = NO; + } + } + return copyOK; +} + +- (void)copyFileToURL:(CDVFilesystemURL *)destURL withName:(NSString *)newName fromFileSystem:(NSObject *)srcFs atURL:(CDVFilesystemURL *)srcURL copy:(BOOL)bCopy callback:(void (^)(CDVPluginResult *))callback +{ + NSFileManager *fileMgr = [[NSFileManager alloc] init]; + NSString *destRootPath = [self filesystemPathForURL:destURL]; + BOOL bDestIsDir = NO; + BOOL bDestExists = [fileMgr fileExistsAtPath:destRootPath isDirectory:&bDestIsDir]; + + NSString *newFileSystemPath = [destRootPath stringByAppendingPathComponent:newName]; + NSString *newFullPath = [self fullPathForFileSystemPath:newFileSystemPath]; + + BOOL bNewIsDir = NO; + BOOL bNewExists = [fileMgr fileExistsAtPath:newFileSystemPath isDirectory:&bNewIsDir]; + + CDVPluginResult *result = nil; + int errCode = 0; + + if (!bDestExists) { + // the destination root does not exist + errCode = NOT_FOUND_ERR; + } + + else if ([srcFs isKindOfClass:[CDVLocalFilesystem class]]) { + /* Same FS, we can shortcut with NSFileManager operations */ + NSString *srcFullPath = [srcFs filesystemPathForURL:srcURL]; + + BOOL bSrcIsDir = NO; + BOOL bSrcExists = [fileMgr fileExistsAtPath:srcFullPath isDirectory:&bSrcIsDir]; + + if (!bSrcExists) { + // the source does not exist + errCode = NOT_FOUND_ERR; + } else if ([newFileSystemPath isEqualToString:srcFullPath]) { + // source and destination can not be the same + errCode = INVALID_MODIFICATION_ERR; + } else if (bSrcIsDir && (bNewExists && !bNewIsDir)) { + // can't copy/move dir to file + errCode = INVALID_MODIFICATION_ERR; + } else { // no errors yet + NSError* __autoreleasing error = nil; + BOOL bSuccess = NO; + if (bCopy) { + if (bSrcIsDir && ![self canCopyMoveSrc:srcFullPath ToDestination:newFileSystemPath]) { + // can't copy dir into self + errCode = INVALID_MODIFICATION_ERR; + } else if (bNewExists) { + // the full destination should NOT already exist if a copy + errCode = PATH_EXISTS_ERR; + } else { + bSuccess = [fileMgr copyItemAtPath:srcFullPath toPath:newFileSystemPath error:&error]; + } + } else { // move + // iOS requires that destination must not exist before calling moveTo + // is W3C INVALID_MODIFICATION_ERR error if destination dir exists and has contents + // + if (!bSrcIsDir && (bNewExists && bNewIsDir)) { + // can't move a file to directory + errCode = INVALID_MODIFICATION_ERR; + } else if (bSrcIsDir && ![self canCopyMoveSrc:srcFullPath ToDestination:newFileSystemPath]) { + // can't move a dir into itself + errCode = INVALID_MODIFICATION_ERR; + } else if (bNewExists) { + if (bNewIsDir && ([[fileMgr contentsOfDirectoryAtPath:newFileSystemPath error:NULL] count] != 0)) { + // can't move dir to a dir that is not empty + errCode = INVALID_MODIFICATION_ERR; + newFileSystemPath = nil; // so we won't try to move + } else { + // remove destination so can perform the moveItemAtPath + bSuccess = [fileMgr removeItemAtPath:newFileSystemPath error:NULL]; + if (!bSuccess) { + errCode = INVALID_MODIFICATION_ERR; // is this the correct error? + newFileSystemPath = nil; + } + } + } else if (bNewIsDir && [newFileSystemPath hasPrefix:srcFullPath]) { + // can't move a directory inside itself or to any child at any depth; + errCode = INVALID_MODIFICATION_ERR; + newFileSystemPath = nil; + } + + if (newFileSystemPath != nil) { + bSuccess = [fileMgr moveItemAtPath:srcFullPath toPath:newFileSystemPath error:&error]; + } + } + if (bSuccess) { + // should verify it is there and of the correct type??? + NSDictionary* newEntry = [self makeEntryForPath:newFullPath isDirectory:bSrcIsDir]; + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:newEntry]; + } else { + if (error) { + if (([error code] == NSFileReadUnknownError) || ([error code] == NSFileReadTooLargeError)) { + errCode = NOT_READABLE_ERR; + } else if ([error code] == NSFileWriteOutOfSpaceError) { + errCode = QUOTA_EXCEEDED_ERR; + } else if ([error code] == NSFileWriteNoPermissionError) { + errCode = NO_MODIFICATION_ALLOWED_ERR; + } + } + } + } + } else { + // Need to copy the hard way + [srcFs readFileAtURL:srcURL start:0 end:-1 callback:^(NSData* data, NSString* mimeType, CDVFileError errorCode) { + CDVPluginResult* result = nil; + if (data != nil) { + BOOL bSuccess = [data writeToFile:newFileSystemPath atomically:YES]; + if (bSuccess) { + // should verify it is there and of the correct type??? + NSDictionary* newEntry = [self makeEntryForPath:newFullPath isDirectory:NO]; + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:newEntry]; + } else { + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:ABORT_ERR]; + } + } else { + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:errorCode]; + } + callback(result); + }]; + return; // Async IO; return without callback. + } + if (result == nil) { + if (!errCode) { + errCode = INVALID_MODIFICATION_ERR; // Catch-all default + } + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:errCode]; + } + callback(result); +} + +/* helper function to get the mimeType from the file extension + * IN: + * NSString* fullPath - filename (may include path) + * OUT: + * NSString* the mime type as type/subtype. nil if not able to determine + */ ++ (NSString*)getMimeTypeFromPath:(NSString*)fullPath +{ + NSString* mimeType = nil; + + if (fullPath) { + CFStringRef typeId = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)[fullPath pathExtension], NULL); + if (typeId) { + mimeType = (__bridge_transfer NSString*)UTTypeCopyPreferredTagWithClass(typeId, kUTTagClassMIMEType); + if (!mimeType) { + // special case for m4a + if ([(__bridge NSString*)typeId rangeOfString : @"m4a-audio"].location != NSNotFound) { + mimeType = @"audio/mp4"; + } else if ([[fullPath pathExtension] rangeOfString:@"wav"].location != NSNotFound) { + mimeType = @"audio/wav"; + } else if ([[fullPath pathExtension] rangeOfString:@"css"].location != NSNotFound) { + mimeType = @"text/css"; + } + } + CFRelease(typeId); + } + } + return mimeType; +} + +- (void)readFileAtURL:(CDVFilesystemURL *)localURL start:(NSInteger)start end:(NSInteger)end callback:(void (^)(NSData*, NSString* mimeType, CDVFileError))callback +{ + NSString *path = [self filesystemPathForURL:localURL]; + + NSString* mimeType = [CDVLocalFilesystem getMimeTypeFromPath:path]; + if (mimeType == nil) { + mimeType = @"*/*"; + } + NSFileHandle* file = [NSFileHandle fileHandleForReadingAtPath:path]; + if (start > 0) { + [file seekToFileOffset:start]; + } + + NSData* readData; + if (end < 0) { + readData = [file readDataToEndOfFile]; + } else { + readData = [file readDataOfLength:(end - start)]; + } + [file closeFile]; + + callback(readData, mimeType, readData != nil ? NO_ERROR : NOT_FOUND_ERR); +} + +- (void)getFileMetadataForURL:(CDVFilesystemURL *)localURL callback:(void (^)(CDVPluginResult *))callback +{ + NSString *path = [self filesystemPathForURL:localURL]; + CDVPluginResult *result; + NSFileManager* fileMgr = [[NSFileManager alloc] init]; + + NSError* __autoreleasing error = nil; + NSDictionary* fileAttrs = [fileMgr attributesOfItemAtPath:path error:&error]; + + if (fileAttrs) { + + // create dictionary of file info + NSMutableDictionary* fileInfo = [NSMutableDictionary dictionaryWithCapacity:5]; + + [fileInfo setObject:localURL.fullPath forKey:@"fullPath"]; + [fileInfo setObject:@"" forKey:@"type"]; // can't easily get the mimetype unless create URL, send request and read response so skipping + [fileInfo setObject:[path lastPathComponent] forKey:@"name"]; + + // Ensure that directories (and other non-regular files) report size of 0 + unsigned long long size = ([fileAttrs fileType] == NSFileTypeRegular ? [fileAttrs fileSize] : 0); + [fileInfo setObject:[NSNumber numberWithUnsignedLongLong:size] forKey:@"size"]; + + NSDate* modDate = [fileAttrs fileModificationDate]; + if (modDate) { + [fileInfo setObject:[NSNumber numberWithDouble:[modDate timeIntervalSince1970] * 1000] forKey:@"lastModifiedDate"]; + } + + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:fileInfo]; + + } else { + // didn't get fileAttribs + CDVFileError errorCode = ABORT_ERR; + NSLog(@"error getting metadata: %@", [error localizedDescription]); + if ([error code] == NSFileNoSuchFileError || [error code] == NSFileReadNoSuchFileError) { + errorCode = NOT_FOUND_ERR; + } + // log [NSNumber numberWithDouble: theMessage] objCtype to see what it returns + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsInt:errorCode]; + } + + callback(result); +} + +@end diff --git a/plugins/cordova-plugin-file/src/osx/CDVFile.h b/plugins/cordova-plugin-file/src/osx/CDVFile.h new file mode 100644 index 0000000..13a9360 --- /dev/null +++ b/plugins/cordova-plugin-file/src/osx/CDVFile.h @@ -0,0 +1,189 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. + */ + +#import +#import + +NSString* const kCDVFilesystemURLPrefix; + +/** +* The default filesystems if non are specified. +*/ +#define CDV_FILESYSTEMS_DEFAULT @"documents,cache,bundle,root" + +/** +* Preference name of the extra filesystems to be "mounted". the following are supported: +* 'bundle' - mounts the application directory +* 'documents' - mounts the users Documents directory (~/Documents) +* 'root' - mounts the root file system +* 'cache' - mounts the caches directory (~/Library/Caches/ *)srcFs atURL:(CDVFilesystemURL *)srcURL copy:(BOOL)bCopy callback:(void (^)(CDVPluginResult *))callback; +- (void)readFileAtURL:(CDVFilesystemURL *)localURL start:(NSInteger)start end:(NSInteger)end callback:(void (^)(NSData*, NSString* mimeType, CDVFileError))callback; +- (void)getFileMetadataForURL:(CDVFilesystemURL *)localURL callback:(void (^)(CDVPluginResult *))callback; + +- (NSDictionary *)makeEntryForLocalURL:(CDVFilesystemURL *)url; +- (NSDictionary*)makeEntryForPath:(NSString*)fullPath isDirectory:(BOOL)isDir; + +@property (nonatomic,strong) NSString *name; +@property (nonatomic, copy) NSURL*(^urlTransformer)(NSURL*); + +@optional +- (NSString *)filesystemPathForURL:(CDVFilesystemURL *)localURI; +- (CDVFilesystemURL *)URLforFilesystemPath:(NSString *)path; + +@end + +@interface CDVFile : CDVPlugin { + NSString* rootDocsPath; + NSString* appDocsPath; + NSString* appLibraryPath; + NSString* appTempPath; + + NSMutableArray* fileSystems_; + BOOL userHasAllowed; +} + +- (NSNumber*)checkFreeDiskSpace:(NSString*)appPath; +- (NSDictionary*)makeEntryForPath:(NSString*)fullPath fileSystemName:(NSString *)fsName isDirectory:(BOOL)isDir; +- (NSDictionary *)makeEntryForURL:(NSURL *)URL; +- (CDVFilesystemURL *)fileSystemURLforLocalPath:(NSString *)localPath; + +- (NSObject *)filesystemForURL:(CDVFilesystemURL *)localURL; + +/* Native Registration API */ +- (void)registerFilesystem:(NSObject *)fs; +- (NSObject *)fileSystemByName:(NSString *)fsName; + +/* Exec API */ +- (void)requestFileSystem:(CDVInvokedUrlCommand*)command; +- (void)resolveLocalFileSystemURI:(CDVInvokedUrlCommand*)command; +- (void)getDirectory:(CDVInvokedUrlCommand*)command; +- (void)getFile:(CDVInvokedUrlCommand*)command; +- (void)getParent:(CDVInvokedUrlCommand*)command; +- (void)removeRecursively:(CDVInvokedUrlCommand*)command; +- (void)remove:(CDVInvokedUrlCommand*)command; +- (void)copyTo:(CDVInvokedUrlCommand*)command; +- (void)moveTo:(CDVInvokedUrlCommand*)command; +- (void)getFileMetadata:(CDVInvokedUrlCommand*)command; +- (void)readEntries:(CDVInvokedUrlCommand*)command; +- (void)readAsText:(CDVInvokedUrlCommand*)command; +- (void)readAsDataURL:(CDVInvokedUrlCommand*)command; +- (void)readAsArrayBuffer:(CDVInvokedUrlCommand*)command; +- (void)write:(CDVInvokedUrlCommand*)command; +- (void)testFileExists:(CDVInvokedUrlCommand*)command; +- (void)testDirectoryExists:(CDVInvokedUrlCommand*)command; +- (void)getFreeDiskSpace:(CDVInvokedUrlCommand*)command; +- (void)truncate:(CDVInvokedUrlCommand*)command; +- (void)doCopyMove:(CDVInvokedUrlCommand*)command isCopy:(BOOL)bCopy; + +/* Compatibilty with older File API */ +- (NSString*)getMimeTypeFromPath:(NSString*)fullPath; +- (NSDictionary *)getDirectoryEntry:(NSString *)target isDirectory:(BOOL)bDirRequest; + +/* Conversion between filesystem paths and URLs */ +- (NSString *)filesystemPathForURL:(CDVFilesystemURL *)URL; + +/* Internal methods for testing */ +- (void)_getLocalFilesystemPath:(CDVInvokedUrlCommand*)command; + +/** + * local path of the 'documents' file system (~/Documents) + */ +@property (nonatomic, strong) NSString* appDocsPath; + +/** +* local path of the 'applicationStorageDirectory' file system (~/Library/Application Support/) +*/ +@property (nonatomic, strong) NSString* appSupportPath; + +/** +* local path of the 'persistent' file system (~/Library/Application Support//files) +*/ +@property (nonatomic, strong) NSString* appDataPath; + +/** +* local path of the 'documents' file system (~/Documents) +*/ +@property (nonatomic, strong) NSString* appTempPath; + +/** +* local path of the 'cache' file system (~/Library/Caches/) +*/ +@property (nonatomic, strong) NSString* appCachePath; + +/** + * registered file systems + */ +@property (nonatomic, strong) NSMutableArray* fileSystems; + +@property BOOL userHasAllowed; + +@end diff --git a/plugins/cordova-plugin-file/src/osx/CDVFile.m b/plugins/cordova-plugin-file/src/osx/CDVFile.m new file mode 100644 index 0000000..75a6001 --- /dev/null +++ b/plugins/cordova-plugin-file/src/osx/CDVFile.m @@ -0,0 +1,1056 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. + */ + +#import "CDVFile.h" +#import "CDVLocalFilesystem.h" +#import + +static NSString* toBase64(NSData* data) { + SEL s1 = NSSelectorFromString(@"cdv_base64EncodedString"); + SEL s2 = NSSelectorFromString(@"base64EncodedString"); + SEL s3 = NSSelectorFromString(@"base64EncodedStringWithOptions:"); + + if ([data respondsToSelector:s1]) { + NSString* (*func)(id, SEL) = (void *)[data methodForSelector:s1]; + return func(data, s1); + } else if ([data respondsToSelector:s2]) { + NSString* (*func)(id, SEL) = (void *)[data methodForSelector:s2]; + return func(data, s2); + } else if ([data respondsToSelector:s3]) { + NSString* (*func)(id, SEL, NSUInteger) = (void *)[data methodForSelector:s3]; + return func(data, s3, 0); + } else { + return nil; + } +} + +CDVFile *filePlugin = nil; + +extern NSString * const NSURLIsExcludedFromBackupKey __attribute__((weak_import)); + +#ifndef __IPHONE_5_1 + NSString* const NSURLIsExcludedFromBackupKey = @"NSURLIsExcludedFromBackupKey"; +#endif + +NSString* const kCDVFilesystemURLPrefix = @"cdvfile"; + +@implementation CDVFilesystemURL +@synthesize url=_url; +@synthesize fileSystemName=_fileSystemName; +@synthesize fullPath=_fullPath; + +- (id) initWithString:(NSString *)strURL +{ + if ( self = [super init] ) { + NSURL *decodedURL = [NSURL URLWithString:strURL]; + return [self initWithURL:decodedURL]; + } + return nil; +} + +-(id) initWithURL:(NSURL *)URL +{ + if ( self = [super init] ) { + _url = URL; + _fileSystemName = [self filesystemNameForLocalURI:URL]; + _fullPath = [self fullPathForLocalURI:URL]; + } + return self; +} + +/* + * IN + * NSString localURI + * OUT + * NSString FileSystem Name for this URI, or nil if it is not recognized. + */ +- (NSString *)filesystemNameForLocalURI:(NSURL *)uri +{ + if ([[uri scheme] isEqualToString:kCDVFilesystemURLPrefix] && [[uri host] isEqualToString:@"localhost"]) { + NSArray *pathComponents = [uri pathComponents]; + if (pathComponents != nil && pathComponents.count > 1) { + return [pathComponents objectAtIndex:1]; + } + } + return nil; +} + +/* + * IN + * NSString localURI + * OUT + * NSString fullPath component suitable for an Entry object. + * The incoming URI should be properly escaped. The returned fullPath is unescaped. + */ +- (NSString *)fullPathForLocalURI:(NSURL *)uri +{ + if ([[uri scheme] isEqualToString:kCDVFilesystemURLPrefix] && [[uri host] isEqualToString:@"localhost"]) { + NSString *path = [uri path]; + if ([uri query]) { + path = [NSString stringWithFormat:@"%@?%@", path, [uri query]]; + } + NSRange slashRange = [path rangeOfString:@"/" options:0 range:NSMakeRange(1, path.length-1)]; + if (slashRange.location == NSNotFound) { + return @""; + } + return [path substringFromIndex:slashRange.location]; + } + return nil; +} + ++ (CDVFilesystemURL *)fileSystemURLWithString:(NSString *)strURL +{ + return [[CDVFilesystemURL alloc] initWithString:strURL]; +} + ++ (CDVFilesystemURL *)fileSystemURLWithURL:(NSURL *)URL +{ + return [[CDVFilesystemURL alloc] initWithURL:URL]; +} + +- (NSString *)absoluteURL +{ + return [NSString stringWithFormat:@"cdvfile://localhost/%@%@", self.fileSystemName, self.fullPath]; +} + +@end + +@implementation CDVFilesystemURLProtocol + ++ (BOOL)canInitWithRequest:(NSURLRequest*)request +{ + NSURL* url = [request URL]; + return [[url scheme] isEqualToString:kCDVFilesystemURLPrefix]; +} + ++ (NSURLRequest*)canonicalRequestForRequest:(NSURLRequest*)request +{ + return request; +} + ++ (BOOL)requestIsCacheEquivalent:(NSURLRequest*)requestA toRequest:(NSURLRequest*)requestB +{ + return [[[requestA URL] resourceSpecifier] isEqualToString:[[requestB URL] resourceSpecifier]]; +} + +- (void)startLoading +{ + CDVFilesystemURL* url = [CDVFilesystemURL fileSystemURLWithURL:[[self request] URL]]; + NSObject *fs = [filePlugin filesystemForURL:url]; + [fs readFileAtURL:url start:0 end:-1 callback:^void(NSData *data, NSString *mimetype, CDVFileError error) { + NSMutableDictionary* responseHeaders = [[NSMutableDictionary alloc] init]; + responseHeaders[@"Cache-Control"] = @"no-cache"; + + if (!error) { + responseHeaders[@"Content-Type"] = mimetype; + NSURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:url.url statusCode:200 HTTPVersion:@"HTTP/1.1"headerFields:responseHeaders]; + [[self client] URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed]; + [[self client] URLProtocol:self didLoadData:data]; + [[self client] URLProtocolDidFinishLoading:self]; + } else { + NSURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:url.url statusCode:404 HTTPVersion:@"HTTP/1.1"headerFields:responseHeaders]; + [[self client] URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed]; + [[self client] URLProtocolDidFinishLoading:self]; + } + }]; +} + +- (void)stopLoading +{} + +- (NSCachedURLResponse *)connection:(NSURLConnection *)connection + willCacheResponse:(NSCachedURLResponse*)cachedResponse { + return nil; +} + +@end + + +@implementation CDVFile + +@synthesize appDocsPath, appDataPath, appSupportPath, appTempPath, appCachePath, userHasAllowed, fileSystems=fileSystems_; + +- (void)registerFilesystem:(NSObject *)fs { + __weak CDVFile* weakSelf = self; + SEL sel = NSSelectorFromString(@"urlTransformer"); + // for backwards compatibility - we check if this property is there + // we create a wrapper block because the urlTransformer property + // on the commandDelegate might be set dynamically at a future time + // (and not dependent on plugin loading order) + if ([self.commandDelegate respondsToSelector:sel]) { + fs.urlTransformer = ^NSURL*(NSURL* urlToTransform) { + // grab the block from the commandDelegate + NSURL* (^urlTransformer)(NSURL*) = ((id(*)(id, SEL))objc_msgSend)(weakSelf.commandDelegate, sel); + // if block is not null, we call it + if (urlTransformer) { + return urlTransformer(urlToTransform); + } else { // else we return the same url + return urlToTransform; + } + }; + } + [fileSystems_ addObject:fs]; +} + +- (NSObject *)fileSystemByName:(NSString *)fsName +{ + if (self.fileSystems != nil) { + for (NSObject *fs in self.fileSystems) { + if ([fs.name isEqualToString:fsName]) { + return fs; + } + } + } + return nil; + +} + +- (NSObject *)filesystemForURL:(CDVFilesystemURL *)localURL { + if (localURL.fileSystemName == nil) return nil; + @try { + return [self fileSystemByName:localURL.fileSystemName]; + } + @catch (NSException *e) { + return nil; + } +} + +- (NSArray *)getExtraFileSystemsPreference:(NSWindowController *)vc +{ + NSString *filesystemsStr = nil; + if([self.viewController isKindOfClass:[CDVViewController class]]) { + CDVViewController *vc = self.viewController; + NSDictionary *settings = [vc settings]; + filesystemsStr = [settings[CDV_PREF_EXTRA_FILESYSTEM] lowercaseString]; + } + if (!filesystemsStr) { + filesystemsStr = CDV_FILESYSTEMS_DEFAULT; + } + return [filesystemsStr componentsSeparatedByString:@","]; +} + +- (void)makeNonSyncable:(NSString*)path { + [[NSFileManager defaultManager] createDirectoryAtPath:path + withIntermediateDirectories:YES + attributes:nil + error:nil]; + NSURL* url = [NSURL fileURLWithPath:path]; + [url setResourceValue: [NSNumber numberWithBool: YES] + forKey: NSURLIsExcludedFromBackupKey error:nil]; + +} + +- (void)registerExtraFileSystems:(NSArray *)filesystems fromAvailableSet:(NSDictionary *)availableFileSystems +{ + NSMutableSet *installedFilesystems = [[NSMutableSet alloc] initWithCapacity:7]; + + /* Register filesystems in order */ + for (NSString *fsName in filesystems) { + if (![installedFilesystems containsObject:fsName]) { + NSString *fsRoot = availableFileSystems[fsName]; + if (fsRoot) { + [filePlugin registerFilesystem:[[CDVLocalFilesystem alloc] initWithName:fsName root:fsRoot]]; + [installedFilesystems addObject:fsName]; + } else { + NSLog(@"Unrecognized extra filesystem identifier: %@", fsName); + } + } + } +} + +- (NSDictionary *)getAvailableFileSystems +{ + return @{ + @"documents": self.appDocsPath, + @"cache": self.appCachePath, + @"bundle": [[NSBundle mainBundle] bundlePath], + @"root": @"/" + }; +} + +- (void)pluginInitialize +{ filePlugin = self; + [NSURLProtocol registerClass:[CDVFilesystemURLProtocol class]]; + + fileSystems_ = [[NSMutableArray alloc] initWithCapacity:3]; + + // Get the Temporary directory path + self.appTempPath = [NSTemporaryDirectory()stringByStandardizingPath]; // remove trailing slash from NSTemporaryDirectory() + [self registerFilesystem:[[CDVLocalFilesystem alloc] initWithName:@"temporary" root:self.appTempPath]]; + + // ~/Library/Application Support/ + self.appSupportPath = [self getSupportDirectoryFor:NSApplicationSupportDirectory pathComponents:nil]; + + // ~/Library/Application Support//files + self.appDataPath = [self getSupportDirectoryFor:NSApplicationSupportDirectory pathComponents:@[@"files"]]; + [self registerFilesystem:[[CDVLocalFilesystem alloc] initWithName:@"persistent" root:self.appDataPath]]; + + // ~/Documents/ + self.appDocsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; + + // ~/Library/Caches//files + self.appCachePath = [self getSupportDirectoryFor:NSCachesDirectory pathComponents:nil]; + + [self registerExtraFileSystems:[self getExtraFileSystemsPreference:self.viewController] + fromAvailableSet:[self getAvailableFileSystems]]; +} + +- (NSString*) getSupportDirectoryFor: (NSSearchPathDirectory) directory pathComponents: (NSArray*) components { + NSError* error; + NSFileManager* fm = [NSFileManager defaultManager]; + NSURL* supportDir = [fm URLForDirectory:directory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:&error]; + if (supportDir == nil) { + NSLog(@"unable to get support directory: %@", error); + return nil; + } + + NSString* bundleID = [[NSBundle mainBundle] bundleIdentifier]; + NSURL *dirPath = [supportDir URLByAppendingPathComponent:bundleID]; + for (NSString* pathComponent in components) { + dirPath = [dirPath URLByAppendingPathComponent:pathComponent]; + } + + if (![fm fileExistsAtPath:dirPath.path]) { + if (![fm createDirectoryAtURL:dirPath withIntermediateDirectories:YES attributes:nil error:&error]) { + NSLog(@"unable to create support directory: %@", error); + return nil; + } + } + return dirPath.path; +} + + +- (CDVFilesystemURL *)fileSystemURLforArg:(NSString *)urlArg +{ + CDVFilesystemURL* ret = nil; + if ([urlArg hasPrefix:@"file://"]) { + /* This looks like a file url. Get the path, and see if any handlers recognize it. */ + NSURL *fileURL = [NSURL URLWithString:urlArg]; + NSURL *resolvedFileURL = [fileURL URLByResolvingSymlinksInPath]; + NSString *path = [resolvedFileURL path]; + ret = [self fileSystemURLforLocalPath:path]; + } else { + ret = [CDVFilesystemURL fileSystemURLWithString:urlArg]; + } + return ret; +} + +- (CDVFilesystemURL *)fileSystemURLforLocalPath:(NSString *)localPath +{ + CDVFilesystemURL *localURL = nil; + NSUInteger shortestFullPath = 0; + + // Try all installed filesystems, in order. Return the most match url. + for (id object in self.fileSystems) { + if ([object respondsToSelector:@selector(URLforFilesystemPath:)]) { + CDVFilesystemURL *url = [object URLforFilesystemPath:localPath]; + if (url){ + // A shorter fullPath would imply that the filesystem is a better match for the local path + if (!localURL || ([[url fullPath] length] < shortestFullPath)) { + localURL = url; + shortestFullPath = [[url fullPath] length]; + } + } + } + } + return localURL; +} + +- (NSNumber*)checkFreeDiskSpace:(NSString*)appPath +{ + NSFileManager* fMgr = [[NSFileManager alloc] init]; + + NSError* __autoreleasing pError = nil; + + NSDictionary* pDict = [fMgr attributesOfFileSystemForPath:appPath error:&pError]; + NSNumber* pNumAvail = (NSNumber*)[pDict objectForKey:NSFileSystemFreeSize]; + + return pNumAvail; +} + +/* Request the File System info + * + * IN: + * arguments[0] - type (number as string) + * TEMPORARY = 0, PERSISTENT = 1; + * arguments[1] - size + * + * OUT: + * Dictionary representing FileSystem object + * name - the human readable directory name + * root = DirectoryEntry object + * bool isDirectory + * bool isFile + * string name + * string fullPath + * fileSystem = FileSystem object - !! ignored because creates circular reference !! + */ + +- (void)requestFileSystem:(CDVInvokedUrlCommand*)command +{ + // arguments + NSString* strType = [command argumentAtIndex:0]; + unsigned long long size = [[command argumentAtIndex:1] longLongValue]; + + int type = [strType intValue]; + CDVPluginResult* result = nil; + + if (type > self.fileSystems.count) { + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsInt:NOT_FOUND_ERR]; + NSLog(@"No filesystem of type requested"); + } else { + NSString* fullPath = @"/"; + // check for avail space for size request + NSNumber* pNumAvail = [self checkFreeDiskSpace:self.appSupportPath]; + // NSLog(@"Free space: %@", [NSString stringWithFormat:@"%qu", [ pNumAvail unsignedLongLongValue ]]); + if (pNumAvail && ([pNumAvail unsignedLongLongValue] < size)) { + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:QUOTA_EXCEEDED_ERR]; + } else { + NSObject *rootFs = [self.fileSystems objectAtIndex:type]; + if (rootFs == nil) { + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsInt:NOT_FOUND_ERR]; + NSLog(@"No filesystem of type requested"); + } else { + NSMutableDictionary* fileSystem = [NSMutableDictionary dictionaryWithCapacity:2]; + [fileSystem setObject:rootFs.name forKey:@"name"]; + NSDictionary* dirEntry = [self makeEntryForPath:fullPath fileSystemName:rootFs.name isDirectory:YES]; + [fileSystem setObject:dirEntry forKey:@"root"]; + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:fileSystem]; + } + } + } + [self.commandDelegate sendPluginResult:result callbackId:command.callbackId]; +} + + +- (void)requestAllFileSystems:(CDVInvokedUrlCommand*)command +{ + NSMutableArray* ret = [[NSMutableArray alloc] init]; + for (NSObject* root in fileSystems_) { + [ret addObject:[self makeEntryForPath:@"/" fileSystemName:root.name isDirectory:YES]]; + } + CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:ret]; + [self.commandDelegate sendPluginResult:result callbackId:command.callbackId]; +} + +- (void)requestAllPaths:(CDVInvokedUrlCommand*)command +{ + NSDictionary* ret = @{ + @"applicationDirectory": [[NSURL fileURLWithPath:[[NSBundle mainBundle] resourcePath]] absoluteString], + @"applicationStorageDirectory": [[NSURL fileURLWithPath:self.appSupportPath] absoluteString], + @"dataDirectory": [[NSURL fileURLWithPath:self.appDataPath] absoluteString], + @"documentsDirectory": [[NSURL fileURLWithPath:self.appDocsPath] absoluteString], + @"cacheDirectory": [[NSURL fileURLWithPath:self.appCachePath] absoluteString], + @"tempDirectory":[[NSURL fileURLWithPath:self.appTempPath] absoluteString], + @"rootDirectory": @"file:///", + }; + + CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:ret]; + [self.commandDelegate sendPluginResult:result callbackId:command.callbackId]; +} + +/* Creates and returns a dictionary representing an Entry Object + * + * IN: + * NSString* fullPath of the entry + * int fsType - FileSystem type + * BOOL isDirectory - YES if this is a directory, NO if is a file + * OUT: + * NSDictionary* Entry object + * bool as NSNumber isDirectory + * bool as NSNumber isFile + * NSString* name - last part of path + * NSString* fullPath + * NSString* filesystemName - FileSystem name -- actual filesystem will be created on the JS side if necessary, to avoid + * creating circular reference (FileSystem contains DirectoryEntry which contains FileSystem.....!!) + */ +- (NSDictionary*)makeEntryForPath:(NSString*)fullPath fileSystemName:(NSString *)fsName isDirectory:(BOOL)isDir +{ + NSObject *fs = [self fileSystemByName:fsName]; + return [fs makeEntryForPath:fullPath isDirectory:isDir]; +} + +- (NSDictionary *)makeEntryForLocalURL:(CDVFilesystemURL *)localURL +{ + NSObject *fs = [self filesystemForURL:localURL]; + return [fs makeEntryForLocalURL:localURL]; +} + +- (NSDictionary *)makeEntryForURL:(NSURL *)URL +{ + CDVFilesystemURL* fsURL = [self fileSystemURLforArg:[URL absoluteString]]; + return [self makeEntryForLocalURL:fsURL]; +} + +/* + * Given a URI determine the File System information associated with it and return an appropriate W3C entry object + * IN + * NSString* localURI: Should be an escaped local filesystem URI + * OUT + * Entry object + * bool isDirectory + * bool isFile + * string name + * string fullPath + * fileSystem = FileSystem object - !! ignored because creates circular reference FileSystem contains DirectoryEntry which contains FileSystem.....!! + */ +- (void)resolveLocalFileSystemURI:(CDVInvokedUrlCommand*)command +{ + // arguments + NSString* localURIstr = [command argumentAtIndex:0]; + CDVPluginResult* result; + + localURIstr = [self encodePath:localURIstr]; //encode path before resolving + CDVFilesystemURL* inputURI = [self fileSystemURLforArg:localURIstr]; + + if (inputURI == nil || inputURI.fileSystemName == nil) { + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsInt:ENCODING_ERR]; + } else { + NSObject *fs = [self filesystemForURL:inputURI]; + if (fs == nil) { + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsInt:ENCODING_ERR]; + } else { + result = [fs entryForLocalURI:inputURI]; + } + } + [self.commandDelegate sendPluginResult:result callbackId:command.callbackId]; +} + +//encode path with percent escapes +-(NSString *)encodePath:(NSString *)path +{ + NSString *decodedPath = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; //decode incase it's already encoded to avoid encoding twice + return [decodedPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; +} + + +/* Part of DirectoryEntry interface, creates or returns the specified directory + * IN: + * NSString* localURI - local filesystem URI for this directory + * NSString* path - directory to be created/returned; may be full path or relative path + * NSDictionary* - Flags object + * boolean as NSNumber create - + * if create is true and directory does not exist, create dir and return directory entry + * if create is true and exclusive is true and directory does exist, return error + * if create is false and directory does not exist, return error + * if create is false and the path represents a file, return error + * boolean as NSNumber exclusive - used in conjunction with create + * if exclusive is true and create is true - specifies failure if directory already exists + * + * + */ +- (void)getDirectory:(CDVInvokedUrlCommand*)command +{ + NSMutableArray* arguments = [NSMutableArray arrayWithArray:command.arguments]; + NSMutableDictionary* options = nil; + + if ([arguments count] >= 3) { + options = [command argumentAtIndex:2 withDefault:nil]; + } + // add getDir to options and call getFile() + if (options != nil) { + options = [NSMutableDictionary dictionaryWithDictionary:options]; + } else { + options = [NSMutableDictionary dictionaryWithCapacity:1]; + } + [options setObject:[NSNumber numberWithInt:1] forKey:@"getDir"]; + if ([arguments count] >= 3) { + [arguments replaceObjectAtIndex:2 withObject:options]; + } else { + [arguments addObject:options]; + } + CDVInvokedUrlCommand* subCommand = + [[CDVInvokedUrlCommand alloc] initWithArguments:arguments + callbackId:command.callbackId + className:command.className + methodName:command.methodName]; + + [self getFile:subCommand]; +} + +/* Part of DirectoryEntry interface, creates or returns the specified file + * IN: + * NSString* baseURI - local filesytem URI for the base directory to search + * NSString* requestedPath - file to be created/returned; may be absolute path or relative path + * NSDictionary* options - Flags object + * boolean as NSNumber create - + * if create is true and file does not exist, create file and return File entry + * if create is true and exclusive is true and file does exist, return error + * if create is false and file does not exist, return error + * if create is false and the path represents a directory, return error + * boolean as NSNumber exclusive - used in conjunction with create + * if exclusive is true and create is true - specifies failure if file already exists + */ +- (void)getFile:(CDVInvokedUrlCommand*)command +{ + NSString* baseURIstr = [command argumentAtIndex:0]; + CDVFilesystemURL* baseURI = [self fileSystemURLforArg:baseURIstr]; + NSString* requestedPath = [command argumentAtIndex:1]; + NSDictionary* options = [command argumentAtIndex:2 withDefault:nil]; + + NSObject *fs = [self filesystemForURL:baseURI]; + CDVPluginResult* result = [fs getFileForURL:baseURI requestedPath:requestedPath options:options]; + + + [self.commandDelegate sendPluginResult:result callbackId:command.callbackId]; +} + +/* + * Look up the parent Entry containing this Entry. + * If this Entry is the root of its filesystem, its parent is itself. + * IN: + * NSArray* arguments + * 0 - NSString* localURI + * NSMutableDictionary* options + * empty + */ +- (void)getParent:(CDVInvokedUrlCommand*)command +{ + // arguments are URL encoded + CDVFilesystemURL* localURI = [self fileSystemURLforArg:command.arguments[0]]; + + NSObject *fs = [self filesystemForURL:localURI]; + CDVPluginResult* result = [fs getParentForURL:localURI]; + + [self.commandDelegate sendPluginResult:result callbackId:command.callbackId]; +} + +/* + * set MetaData of entry + * Currently we only support "com.apple.MobileBackup" (boolean) + */ +- (void)setMetadata:(CDVInvokedUrlCommand*)command +{ + // arguments + CDVFilesystemURL* localURI = [self fileSystemURLforArg:command.arguments[0]]; + NSDictionary* options = [command argumentAtIndex:1 withDefault:nil]; + NSObject *fs = [self filesystemForURL:localURI]; + CDVPluginResult* result = [fs setMetadataForURL:localURI withObject:options]; + + [self.commandDelegate sendPluginResult:result callbackId:command.callbackId]; +} + +/* removes the directory or file entry + * IN: + * NSArray* arguments + * 0 - NSString* localURI + * + * returns NO_MODIFICATION_ALLOWED_ERR if is top level directory or no permission to delete dir + * returns INVALID_MODIFICATION_ERR if is non-empty dir or asset library file + * returns NOT_FOUND_ERR if file or dir is not found +*/ +- (void)remove:(CDVInvokedUrlCommand*)command +{ + // arguments + CDVFilesystemURL* localURI = [self fileSystemURLforArg:command.arguments[0]]; + CDVPluginResult* result = nil; + + if ([localURI.fullPath isEqualToString:@""]) { + // error if try to remove top level (documents or tmp) dir + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NO_MODIFICATION_ALLOWED_ERR]; + } else { + NSObject *fs = [self filesystemForURL:localURI]; + result = [fs removeFileAtURL:localURI]; + } + [self.commandDelegate sendPluginResult:result callbackId:command.callbackId]; +} + +/* recursively removes the directory + * IN: + * NSArray* arguments + * 0 - NSString* localURI + * + * returns NO_MODIFICATION_ALLOWED_ERR if is top level directory or no permission to delete dir + * returns NOT_FOUND_ERR if file or dir is not found + */ +- (void)removeRecursively:(CDVInvokedUrlCommand*)command +{ + // arguments + CDVFilesystemURL* localURI = [self fileSystemURLforArg:command.arguments[0]]; + CDVPluginResult* result = nil; + + if ([localURI.fullPath isEqualToString:@""]) { + // error if try to remove top level (documents or tmp) dir + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NO_MODIFICATION_ALLOWED_ERR]; + } else { + NSObject *fs = [self filesystemForURL:localURI]; + result = [fs recursiveRemoveFileAtURL:localURI]; + } + [self.commandDelegate sendPluginResult:result callbackId:command.callbackId]; +} + +- (void)copyTo:(CDVInvokedUrlCommand*)command +{ + [self doCopyMove:command isCopy:YES]; +} + +- (void)moveTo:(CDVInvokedUrlCommand*)command +{ + [self doCopyMove:command isCopy:NO]; +} + +/* Copy/move a file or directory to a new location + * IN: + * NSArray* arguments + * 0 - NSString* URL of entry to copy + * 1 - NSString* URL of the directory into which to copy/move the entry + * 2 - Optionally, the new name of the entry, defaults to the current name + * BOOL - bCopy YES if copy, NO if move + */ +- (void)doCopyMove:(CDVInvokedUrlCommand*)command isCopy:(BOOL)bCopy +{ + NSArray* arguments = command.arguments; + + // arguments + NSString* srcURLstr = [command argumentAtIndex:0]; + NSString* destURLstr = [command argumentAtIndex:1]; + + CDVPluginResult *result; + + if (!srcURLstr || !destURLstr) { + // either no source or no destination provided + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NOT_FOUND_ERR]; + [self.commandDelegate sendPluginResult:result callbackId:command.callbackId]; + return; + } + + CDVFilesystemURL* srcURL = [self fileSystemURLforArg:srcURLstr]; + CDVFilesystemURL* destURL = [self fileSystemURLforArg:destURLstr]; + + NSObject *srcFs = [self filesystemForURL:srcURL]; + NSObject *destFs = [self filesystemForURL:destURL]; + + // optional argument; use last component from srcFullPath if new name not provided + NSString* newName = ([arguments count] > 2) ? [command argumentAtIndex:2] : [srcURL.url lastPathComponent]; + if ([newName rangeOfString:@":"].location != NSNotFound) { + // invalid chars in new name + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:ENCODING_ERR]; + [self.commandDelegate sendPluginResult:result callbackId:command.callbackId]; + return; + } + + [destFs copyFileToURL:destURL withName:newName fromFileSystem:srcFs atURL:srcURL copy:bCopy callback:^(CDVPluginResult* result) { + [self.commandDelegate sendPluginResult:result callbackId:command.callbackId]; + }]; + +} + +- (void)getFileMetadata:(CDVInvokedUrlCommand*)command +{ + // arguments + CDVFilesystemURL* localURI = [self fileSystemURLforArg:command.arguments[0]]; + NSObject *fs = [self filesystemForURL:localURI]; + + [fs getFileMetadataForURL:localURI callback:^(CDVPluginResult* result) { + [self.commandDelegate sendPluginResult:result callbackId:command.callbackId]; + }]; +} + +- (void)readEntries:(CDVInvokedUrlCommand*)command +{ + CDVFilesystemURL* localURI = [self fileSystemURLforArg:command.arguments[0]]; + NSObject *fs = [self filesystemForURL:localURI]; + CDVPluginResult *result = [fs readEntriesAtURL:localURI]; + + [self.commandDelegate sendPluginResult:result callbackId:command.callbackId]; +} + +/* read and return file data + * IN: + * NSArray* arguments + * 0 - NSString* fullPath + * 1 - NSString* encoding + * 2 - NSString* start + * 3 - NSString* end + */ +- (void)readAsText:(CDVInvokedUrlCommand*)command +{ + // arguments + CDVFilesystemURL* localURI = [self fileSystemURLforArg:command.arguments[0]]; + NSString* encoding = [command argumentAtIndex:1]; + NSInteger start = [[command argumentAtIndex:2] integerValue]; + NSInteger end = [[command argumentAtIndex:3] integerValue]; + + NSObject *fs = [self filesystemForURL:localURI]; + + if (fs == nil) { + CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NOT_FOUND_ERR]; + [self.commandDelegate sendPluginResult:result callbackId:command.callbackId]; + return; + } + + // TODO: implement + if ([@"UTF-8" caseInsensitiveCompare : encoding] != NSOrderedSame) { + NSLog(@"Only UTF-8 encodings are currently supported by readAsText"); + CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:ENCODING_ERR]; + [self.commandDelegate sendPluginResult:result callbackId:command.callbackId]; + return; + } + + [self.commandDelegate runInBackground:^ { + [fs readFileAtURL:localURI start:start end:end callback:^(NSData* data, NSString* mimeType, CDVFileError errorCode) { + CDVPluginResult* result = nil; + if (data != nil) { + NSString* str = [[NSString alloc] initWithBytesNoCopy:(void*)[data bytes] length:[data length] encoding:NSUTF8StringEncoding freeWhenDone:NO]; + // Check that UTF8 conversion did not fail. + if (str != nil) { + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:str]; + result.associatedObject = data; + } else { + errorCode = ENCODING_ERR; + } + } + if (result == nil) { + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:errorCode]; + } + + [self.commandDelegate sendPluginResult:result callbackId:command.callbackId]; + }]; + }]; +} + +/* Read content of text file and return as base64 encoded data url. + * IN: + * NSArray* arguments + * 0 - NSString* fullPath + * 1 - NSString* start + * 2 - NSString* end + * + * Determines the mime type from the file extension, returns ENCODING_ERR if mimetype can not be determined. + */ + +- (void)readAsDataURL:(CDVInvokedUrlCommand*)command +{ + CDVFilesystemURL* localURI = [self fileSystemURLforArg:command.arguments[0]]; + NSInteger start = [[command argumentAtIndex:1] integerValue]; + NSInteger end = [[command argumentAtIndex:2] integerValue]; + + NSObject *fs = [self filesystemForURL:localURI]; + + [self.commandDelegate runInBackground:^ { + [fs readFileAtURL:localURI start:start end:end callback:^(NSData* data, NSString* mimeType, CDVFileError errorCode) { + CDVPluginResult* result = nil; + if (data != nil) { + NSString* b64Str = toBase64(data); + NSString* output = [NSString stringWithFormat:@"data:%@;base64,%@", mimeType, b64Str]; + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:output]; + } else { + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:errorCode]; + } + + [self.commandDelegate sendPluginResult:result callbackId:command.callbackId]; + }]; + }]; +} + +/* Read content of text file and return as an arraybuffer + * IN: + * NSArray* arguments + * 0 - NSString* fullPath + * 1 - NSString* start + * 2 - NSString* end + */ + +- (void)readAsArrayBuffer:(CDVInvokedUrlCommand*)command +{ + CDVFilesystemURL* localURI = [self fileSystemURLforArg:command.arguments[0]]; + NSInteger start = [[command argumentAtIndex:1] integerValue]; + NSInteger end = [[command argumentAtIndex:2] integerValue]; + + NSObject *fs = [self filesystemForURL:localURI]; + + [self.commandDelegate runInBackground:^ { + [fs readFileAtURL:localURI start:start end:end callback:^(NSData* data, NSString* mimeType, CDVFileError errorCode) { + CDVPluginResult* result = nil; + if (data != nil) { + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArrayBuffer:data]; + } else { + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:errorCode]; + } + + [self.commandDelegate sendPluginResult:result callbackId:command.callbackId]; + }]; + }]; +} + +- (void)readAsBinaryString:(CDVInvokedUrlCommand*)command +{ + CDVFilesystemURL* localURI = [self fileSystemURLforArg:command.arguments[0]]; + NSInteger start = [[command argumentAtIndex:1] integerValue]; + NSInteger end = [[command argumentAtIndex:2] integerValue]; + + NSObject *fs = [self filesystemForURL:localURI]; + + [self.commandDelegate runInBackground:^ { + [fs readFileAtURL:localURI start:start end:end callback:^(NSData* data, NSString* mimeType, CDVFileError errorCode) { + CDVPluginResult* result = nil; + if (data != nil) { + NSString* payload = [[NSString alloc] initWithBytesNoCopy:(void*)[data bytes] length:[data length] encoding:NSASCIIStringEncoding freeWhenDone:NO]; + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:payload]; + result.associatedObject = data; + } else { + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:errorCode]; + } + + [self.commandDelegate sendPluginResult:result callbackId:command.callbackId]; + }]; + }]; +} + + +- (void)truncate:(CDVInvokedUrlCommand*)command +{ + // arguments + CDVFilesystemURL* localURI = [self fileSystemURLforArg:command.arguments[0]]; + unsigned long long pos = (unsigned long long)[[command argumentAtIndex:1] longLongValue]; + + NSObject *fs = [self filesystemForURL:localURI]; + CDVPluginResult *result = [fs truncateFileAtURL:localURI atPosition:pos]; + + [self.commandDelegate sendPluginResult:result callbackId:command.callbackId]; +} + +/* write + * IN: + * NSArray* arguments + * 0 - NSString* localURI of file to write to + * 1 - NSString* or NSData* data to write + * 2 - NSNumber* position to begin writing + */ +- (void)write:(CDVInvokedUrlCommand*)command +{ + [self.commandDelegate runInBackground:^ { + NSString* callbackId = command.callbackId; + + // arguments + CDVFilesystemURL* localURI = [self fileSystemURLforArg:command.arguments[0]]; + id argData = [command argumentAtIndex:1]; + unsigned long long pos = (unsigned long long)[[command argumentAtIndex:2] longLongValue]; + + NSObject *fs = [self filesystemForURL:localURI]; + + + [fs truncateFileAtURL:localURI atPosition:pos]; + CDVPluginResult *result; + if ([argData isKindOfClass:[NSString class]]) { + NSData *encData = [argData dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]; + result = [fs writeToFileAtURL:localURI withData:encData append:YES]; + } else if ([argData isKindOfClass:[NSData class]]) { + result = [fs writeToFileAtURL:localURI withData:argData append:YES]; + } else { + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Invalid parameter type"]; + } + [self.commandDelegate sendPluginResult:result callbackId:callbackId]; + }]; +} + +#pragma mark Methods for converting between URLs and paths + +- (NSString *)filesystemPathForURL:(CDVFilesystemURL *)localURL +{ + for (NSObject *fs in self.fileSystems) { + if ([fs.name isEqualToString:localURL.fileSystemName]) { + if ([fs respondsToSelector:@selector(filesystemPathForURL:)]) { + return [fs filesystemPathForURL:localURL]; + } + } + } + return nil; +} + +#pragma mark Undocumented Filesystem API + +- (void)testFileExists:(CDVInvokedUrlCommand*)command +{ + // arguments + NSString* argPath = [command argumentAtIndex:0]; + + // Get the file manager + NSFileManager* fMgr = [NSFileManager defaultManager]; + NSString* appFile = argPath; // [ self getFullPath: argPath]; + + BOOL bExists = [fMgr fileExistsAtPath:appFile]; + CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:(bExists ? 1 : 0)]; + + [self.commandDelegate sendPluginResult:result callbackId:command.callbackId]; +} + +- (void)testDirectoryExists:(CDVInvokedUrlCommand*)command +{ + // arguments + NSString* argPath = [command argumentAtIndex:0]; + + // Get the file manager + NSFileManager* fMgr = [[NSFileManager alloc] init]; + NSString* appFile = argPath; // [self getFullPath: argPath]; + BOOL bIsDir = NO; + BOOL bExists = [fMgr fileExistsAtPath:appFile isDirectory:&bIsDir]; + + CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:((bExists && bIsDir) ? 1 : 0)]; + + [self.commandDelegate sendPluginResult:result callbackId:command.callbackId]; +} + +// Returns number of bytes available via callback +- (void)getFreeDiskSpace:(CDVInvokedUrlCommand*)command +{ + // no arguments + + NSNumber* pNumAvail = [self checkFreeDiskSpace:self.appDocsPath]; + + NSString* strFreeSpace = [NSString stringWithFormat:@"%qu", [pNumAvail unsignedLongLongValue]]; + // NSLog(@"Free space is %@", strFreeSpace ); + + CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:strFreeSpace]; + + [self.commandDelegate sendPluginResult:result callbackId:command.callbackId]; +} + +#pragma mark Compatibility with older File API + +- (NSString*)getMimeTypeFromPath:(NSString*)fullPath +{ + return [CDVLocalFilesystem getMimeTypeFromPath:fullPath]; +} + +- (NSDictionary *)getDirectoryEntry:(NSString *)localPath isDirectory:(BOOL)bDirRequest +{ + CDVFilesystemURL *localURL = [self fileSystemURLforLocalPath:localPath]; + return [self makeEntryForPath:localURL.fullPath fileSystemName:localURL.fileSystemName isDirectory:bDirRequest]; +} + +#pragma mark Internal methods for testing +// Internal methods for testing: Get the on-disk location of a local filesystem url. +// [Currently used for testing file-transfer] + +- (void)_getLocalFilesystemPath:(CDVInvokedUrlCommand*)command +{ + CDVFilesystemURL* localURL = [self fileSystemURLforArg:command.arguments[0]]; + + NSString* fsPath = [self filesystemPathForURL:localURL]; + CDVPluginResult* result; + if (fsPath) { + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:fsPath]; + } else { + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Cannot resolve URL to a file"]; + } + [self.commandDelegate sendPluginResult:result callbackId:command.callbackId]; +} + +@end diff --git a/plugins/cordova-plugin-file/src/osx/CDVLocalFilesystem.h b/plugins/cordova-plugin-file/src/osx/CDVLocalFilesystem.h new file mode 100644 index 0000000..a0186c8 --- /dev/null +++ b/plugins/cordova-plugin-file/src/osx/CDVLocalFilesystem.h @@ -0,0 +1,32 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. + */ + +#import "CDVFile.h" + +@interface CDVLocalFilesystem : NSObject { + NSString *_name; + NSString *_fsRoot; +} + +- (id) initWithName:(NSString *)name root:(NSString *)fsRoot; ++ (NSString*)getMimeTypeFromPath:(NSString*)fullPath; + +@property (nonatomic,strong) NSString *fsRoot; + +@end diff --git a/plugins/cordova-plugin-file/src/osx/CDVLocalFilesystem.m b/plugins/cordova-plugin-file/src/osx/CDVLocalFilesystem.m new file mode 100644 index 0000000..016e399 --- /dev/null +++ b/plugins/cordova-plugin-file/src/osx/CDVLocalFilesystem.m @@ -0,0 +1,733 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. + */ + +#import "CDVFile.h" +#import "CDVLocalFilesystem.h" +#import + +@implementation CDVLocalFilesystem +@synthesize name=_name, fsRoot=_fsRoot, urlTransformer; + +- (id) initWithName:(NSString *)name root:(NSString *)fsRoot +{ + if (self) { + _name = name; + _fsRoot = fsRoot; + } + return self; +} + +/* + * IN + * NSString localURI + * OUT + * CDVPluginResult result containing a file or directoryEntry for the localURI, or an error if the + * URI represents a non-existent path, or is unrecognized or otherwise malformed. + */ +- (CDVPluginResult *)entryForLocalURI:(CDVFilesystemURL *)url +{ + CDVPluginResult* result = nil; + NSDictionary* entry = [self makeEntryForLocalURL:url]; + if (entry) { + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:entry]; + } else { + // return NOT_FOUND_ERR + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NOT_FOUND_ERR]; + } + return result; +} +- (NSDictionary *)makeEntryForLocalURL:(CDVFilesystemURL *)url { + NSString *path = [self filesystemPathForURL:url]; + NSFileManager* fileMgr = [[NSFileManager alloc] init]; + BOOL isDir = NO; + // see if exists and is file or dir + BOOL bExists = [fileMgr fileExistsAtPath:path isDirectory:&isDir]; + if (bExists) { + return [self makeEntryForPath:url.fullPath isDirectory:isDir]; + } else { + return nil; + } +} +- (NSDictionary*)makeEntryForPath:(NSString*)fullPath isDirectory:(BOOL)isDir +{ + NSMutableDictionary* dirEntry = [NSMutableDictionary dictionaryWithCapacity:5]; + NSString* lastPart = [[self stripQueryParametersFromPath:fullPath] lastPathComponent]; + if (isDir && ![fullPath hasSuffix:@"/"]) { + fullPath = [fullPath stringByAppendingString:@"/"]; + } + [dirEntry setObject:[NSNumber numberWithBool:!isDir] forKey:@"isFile"]; + [dirEntry setObject:[NSNumber numberWithBool:isDir] forKey:@"isDirectory"]; + [dirEntry setObject:fullPath forKey:@"fullPath"]; + [dirEntry setObject:lastPart forKey:@"name"]; + [dirEntry setObject:self.name forKey: @"filesystemName"]; + + NSURL* nativeURL = [NSURL fileURLWithPath:[self filesystemPathForFullPath:fullPath]]; + if (self.urlTransformer) { + nativeURL = self.urlTransformer(nativeURL); + } + + dirEntry[@"nativeURL"] = [nativeURL absoluteString]; + + return dirEntry; +} + +- (NSString *)stripQueryParametersFromPath:(NSString *)fullPath +{ + NSRange questionMark = [fullPath rangeOfString:@"?"]; + if (questionMark.location != NSNotFound) { + return [fullPath substringWithRange:NSMakeRange(0,questionMark.location)]; + } + return fullPath; +} + +- (NSString *)filesystemPathForFullPath:(NSString *)fullPath +{ + NSString *path = nil; + NSString *strippedFullPath = [self stripQueryParametersFromPath:fullPath]; + path = [NSString stringWithFormat:@"%@%@", self.fsRoot, strippedFullPath]; + if ([path length] > 1 && [path hasSuffix:@"/"]) { + path = [path substringToIndex:([path length]-1)]; + } + return path; +} +/* + * IN + * NSString localURI + * OUT + * NSString full local filesystem path for the represented file or directory, or nil if no such path is possible + * The file or directory does not necessarily have to exist. nil is returned if the filesystem type is not recognized, + * or if the URL is malformed. + * The incoming URI should be properly escaped (no raw spaces, etc. URI percent-encoding is expected). + */ +- (NSString *)filesystemPathForURL:(CDVFilesystemURL *)url +{ + return [self filesystemPathForFullPath:url.fullPath]; +} + +- (CDVFilesystemURL *)URLforFullPath:(NSString *)fullPath +{ + if (fullPath) { + NSString* escapedPath = [fullPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + if ([fullPath hasPrefix:@"/"]) { + return [CDVFilesystemURL fileSystemURLWithString:[NSString stringWithFormat:@"%@://localhost/%@%@", kCDVFilesystemURLPrefix, self.name, escapedPath]]; + } + return [CDVFilesystemURL fileSystemURLWithString:[NSString stringWithFormat:@"%@://localhost/%@/%@", kCDVFilesystemURLPrefix, self.name, escapedPath]]; + } + return nil; +} + +- (CDVFilesystemURL *)URLforFilesystemPath:(NSString *)path +{ + return [self URLforFullPath:[self fullPathForFileSystemPath:path]]; + +} + +- (NSString *)normalizePath:(NSString *)rawPath +{ + // If this is an absolute path, the first path component will be '/'. Skip it if that's the case + BOOL isAbsolutePath = [rawPath hasPrefix:@"/"]; + if (isAbsolutePath) { + rawPath = [rawPath substringFromIndex:1]; + } + NSMutableArray *components = [NSMutableArray arrayWithArray:[rawPath pathComponents]]; + for (int index = 0; index < [components count]; ++index) { + if ([[components objectAtIndex:index] isEqualToString:@".."]) { + [components removeObjectAtIndex:index]; + if (index > 0) { + [components removeObjectAtIndex:index-1]; + --index; + } + } + } + + if (isAbsolutePath) { + return [NSString stringWithFormat:@"/%@", [components componentsJoinedByString:@"/"]]; + } else { + return [components componentsJoinedByString:@"/"]; + } + + +} + +- (BOOL)valueForKeyIsNumber:(NSDictionary*)dict key:(NSString*)key +{ + BOOL bNumber = NO; + NSObject* value = dict[key]; + if (value) { + bNumber = [value isKindOfClass:[NSNumber class]]; + } + return bNumber; +} + +- (CDVPluginResult *)getFileForURL:(CDVFilesystemURL *)baseURI requestedPath:(NSString *)requestedPath options:(NSDictionary *)options +{ + CDVPluginResult* result = nil; + BOOL bDirRequest = NO; + BOOL create = NO; + BOOL exclusive = NO; + int errorCode = 0; // !!! risky - no error code currently defined for 0 + + if ([self valueForKeyIsNumber:options key:@"create"]) { + create = [(NSNumber*)[options valueForKey:@"create"] boolValue]; + } + if ([self valueForKeyIsNumber:options key:@"exclusive"]) { + exclusive = [(NSNumber*)[options valueForKey:@"exclusive"] boolValue]; + } + if ([self valueForKeyIsNumber:options key:@"getDir"]) { + // this will not exist for calls directly to getFile but will have been set by getDirectory before calling this method + bDirRequest = [(NSNumber*)[options valueForKey:@"getDir"] boolValue]; + } + // see if the requested path has invalid characters - should we be checking for more than just ":"? + if ([requestedPath rangeOfString:@":"].location != NSNotFound) { + errorCode = ENCODING_ERR; + } else { + // Build new fullPath for the requested resource. + // We concatenate the two paths together, and then scan the resulting string to remove + // parent ("..") references. Any parent references at the beginning of the string are + // silently removed. + NSString *combinedPath = [baseURI.fullPath stringByAppendingPathComponent:requestedPath]; + combinedPath = [self normalizePath:combinedPath]; + CDVFilesystemURL* requestedURL = [self URLforFullPath:combinedPath]; + + NSFileManager* fileMgr = [[NSFileManager alloc] init]; + BOOL bIsDir; + BOOL bExists = [fileMgr fileExistsAtPath:[self filesystemPathForURL:requestedURL] isDirectory:&bIsDir]; + if (bExists && (create == NO) && (bIsDir == !bDirRequest)) { + // path exists and is not of requested type - return TYPE_MISMATCH_ERR + errorCode = TYPE_MISMATCH_ERR; + } else if (!bExists && (create == NO)) { + // path does not exist and create is false - return NOT_FOUND_ERR + errorCode = NOT_FOUND_ERR; + } else if (bExists && (create == YES) && (exclusive == YES)) { + // file/dir already exists and exclusive and create are both true - return PATH_EXISTS_ERR + errorCode = PATH_EXISTS_ERR; + } else { + // if bExists and create == YES - just return data + // if bExists and create == NO - just return data + // if !bExists and create == YES - create and return data + BOOL bSuccess = YES; + NSError __autoreleasing* pError = nil; + if (!bExists && (create == YES)) { + if (bDirRequest) { + // create the dir + bSuccess = [fileMgr createDirectoryAtPath:[self filesystemPathForURL:requestedURL] withIntermediateDirectories:NO attributes:nil error:&pError]; + } else { + // create the empty file + bSuccess = [fileMgr createFileAtPath:[self filesystemPathForURL:requestedURL] contents:nil attributes:nil]; + } + } + if (!bSuccess) { + errorCode = ABORT_ERR; + if (pError) { + NSLog(@"error creating directory: %@", [pError localizedDescription]); + } + } else { + // NSLog(@"newly created file/dir (%@) exists: %d", reqFullPath, [fileMgr fileExistsAtPath:reqFullPath]); + // file existed or was created + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:[self makeEntryForPath:requestedURL.fullPath isDirectory:bDirRequest]]; + } + } // are all possible conditions met? + } + + if (errorCode > 0) { + // create error callback + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:errorCode]; + } + return result; + +} + +- (CDVPluginResult*)getParentForURL:(CDVFilesystemURL *)localURI +{ + CDVPluginResult* result = nil; + CDVFilesystemURL *newURI = nil; + if ([localURI.fullPath isEqualToString:@""]) { + // return self + newURI = localURI; + } else { + newURI = [CDVFilesystemURL fileSystemURLWithURL:[localURI.url URLByDeletingLastPathComponent]]; /* TODO: UGLY - FIX */ + } + NSFileManager* fileMgr = [[NSFileManager alloc] init]; + BOOL bIsDir; + BOOL bExists = [fileMgr fileExistsAtPath:[self filesystemPathForURL:newURI] isDirectory:&bIsDir]; + if (bExists) { + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:[self makeEntryForPath:newURI.fullPath isDirectory:bIsDir]]; + } else { + // invalid path or file does not exist + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NOT_FOUND_ERR]; + } + return result; +} + +- (CDVPluginResult*)setMetadataForURL:(CDVFilesystemURL *)localURI withObject:(NSDictionary *)options +{ + BOOL ok = NO; + + NSString* filePath = [self filesystemPathForURL:localURI]; + // we only care about this iCloud key for now. + // set to 1/true to skip backup, set to 0/false to back it up (effectively removing the attribute) + NSString* iCloudBackupExtendedAttributeKey = @"com.apple.MobileBackup"; + id iCloudBackupExtendedAttributeValue = [options objectForKey:iCloudBackupExtendedAttributeKey]; + + if ((iCloudBackupExtendedAttributeValue != nil) && [iCloudBackupExtendedAttributeValue isKindOfClass:[NSNumber class]]) { +// todo: fix me +// if (IsAtLeastiOSVersion(@"5.1")) { +// NSURL* url = [NSURL fileURLWithPath:filePath]; +// NSError* __autoreleasing error = nil; +// +// ok = [url setResourceValue:[NSNumber numberWithBool:[iCloudBackupExtendedAttributeValue boolValue]] forKey:NSURLIsExcludedFromBackupKey error:&error]; +// } else { // below 5.1 (deprecated - only really supported in 5.01) +// u_int8_t value = [iCloudBackupExtendedAttributeValue intValue]; +// if (value == 0) { // remove the attribute (allow backup, the default) +// ok = (removexattr([filePath fileSystemRepresentation], [iCloudBackupExtendedAttributeKey cStringUsingEncoding:NSUTF8StringEncoding], 0) == 0); +// } else { // set the attribute (skip backup) +// ok = (setxattr([filePath fileSystemRepresentation], [iCloudBackupExtendedAttributeKey cStringUsingEncoding:NSUTF8StringEncoding], &value, sizeof(value), 0, 0) == 0); +// } +// } + } + + if (ok) { + return [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; + } else { + return [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR]; + } +} + +/* remove the file or directory (recursively) + * IN: + * NSString* fullPath - the full path to the file or directory to be removed + * NSString* callbackId + * called from remove and removeRecursively - check all pubic api specific error conditions (dir not empty, etc) before calling + */ + +- (CDVPluginResult*)doRemove:(NSString*)fullPath +{ + CDVPluginResult* result = nil; + BOOL bSuccess = NO; + NSError* __autoreleasing pError = nil; + NSFileManager* fileMgr = [[NSFileManager alloc] init]; + + @try { + bSuccess = [fileMgr removeItemAtPath:fullPath error:&pError]; + if (bSuccess) { + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; + } else { + // see if we can give a useful error + CDVFileError errorCode = ABORT_ERR; + NSLog(@"error removing filesystem entry at %@: %@", fullPath, [pError localizedDescription]); + if ([pError code] == NSFileNoSuchFileError) { + errorCode = NOT_FOUND_ERR; + } else if ([pError code] == NSFileWriteNoPermissionError) { + errorCode = NO_MODIFICATION_ALLOWED_ERR; + } + + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:errorCode]; + } + } @catch(NSException* e) { // NSInvalidArgumentException if path is . or .. + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsInt:SYNTAX_ERR]; + } + + return result; +} + +- (CDVPluginResult *)removeFileAtURL:(CDVFilesystemURL *)localURI +{ + NSString *fileSystemPath = [self filesystemPathForURL:localURI]; + + NSFileManager* fileMgr = [[NSFileManager alloc] init]; + BOOL bIsDir = NO; + BOOL bExists = [fileMgr fileExistsAtPath:fileSystemPath isDirectory:&bIsDir]; + if (!bExists) { + return [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NOT_FOUND_ERR]; + } + if (bIsDir && ([[fileMgr contentsOfDirectoryAtPath:fileSystemPath error:nil] count] != 0)) { + // dir is not empty + return [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:INVALID_MODIFICATION_ERR]; + } + return [self doRemove:fileSystemPath]; +} + +- (CDVPluginResult *)recursiveRemoveFileAtURL:(CDVFilesystemURL *)localURI +{ + NSString *fileSystemPath = [self filesystemPathForURL:localURI]; + return [self doRemove:fileSystemPath]; +} + +/* + * IN + * NSString localURI + * OUT + * NSString full local filesystem path for the represented file or directory, or nil if no such path is possible + * The file or directory does not necessarily have to exist. nil is returned if the filesystem type is not recognized, + * or if the URL is malformed. + * The incoming URI should be properly escaped (no raw spaces, etc. URI percent-encoding is expected). + */ +- (NSString *)fullPathForFileSystemPath:(NSString *)fsPath +{ + if ([fsPath hasPrefix:self.fsRoot]) { + return [fsPath substringFromIndex:[self.fsRoot length]]; + } + return nil; +} + + +- (CDVPluginResult *)readEntriesAtURL:(CDVFilesystemURL *)localURI +{ + NSFileManager* fileMgr = [[NSFileManager alloc] init]; + NSError* __autoreleasing error = nil; + NSString *fileSystemPath = [self filesystemPathForURL:localURI]; + + NSArray* contents = [fileMgr contentsOfDirectoryAtPath:fileSystemPath error:&error]; + + if (contents) { + NSMutableArray* entries = [NSMutableArray arrayWithCapacity:1]; + if ([contents count] > 0) { + // create an Entry (as JSON) for each file/dir + for (NSString* name in contents) { + // see if is dir or file + NSString* entryPath = [fileSystemPath stringByAppendingPathComponent:name]; + BOOL bIsDir = NO; + [fileMgr fileExistsAtPath:entryPath isDirectory:&bIsDir]; + NSDictionary* entryDict = [self makeEntryForPath:[self fullPathForFileSystemPath:entryPath] isDirectory:bIsDir]; + [entries addObject:entryDict]; + } + } + return [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:entries]; + } else { + // assume not found but could check error for more specific error conditions + return [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NOT_FOUND_ERR]; + } +} + +- (unsigned long long)truncateFile:(NSString*)filePath atPosition:(unsigned long long)pos +{ + unsigned long long newPos = 0UL; + + NSFileHandle* file = [NSFileHandle fileHandleForWritingAtPath:filePath]; + + if (file) { + [file truncateFileAtOffset:(unsigned long long)pos]; + newPos = [file offsetInFile]; + [file synchronizeFile]; + [file closeFile]; + } + return newPos; +} + +- (CDVPluginResult *)truncateFileAtURL:(CDVFilesystemURL *)localURI atPosition:(unsigned long long)pos +{ + unsigned long long newPos = [self truncateFile:[self filesystemPathForURL:localURI] atPosition:pos]; + return [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:(int)newPos]; +} + +- (CDVPluginResult *)writeToFileAtURL:(CDVFilesystemURL *)localURL withData:(NSData*)encData append:(BOOL)shouldAppend +{ + NSString *filePath = [self filesystemPathForURL:localURL]; + + CDVPluginResult* result = nil; + CDVFileError errCode = INVALID_MODIFICATION_ERR; + int bytesWritten = 0; + + if (filePath) { + NSOutputStream* fileStream = [NSOutputStream outputStreamToFileAtPath:filePath append:shouldAppend]; + if (fileStream) { + NSUInteger len = [encData length]; + if (len == 0) { + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDouble:(double)len]; + } else { + [fileStream open]; + + bytesWritten = (int)[fileStream write:[encData bytes] maxLength:len]; + + [fileStream close]; + if (bytesWritten > 0) { + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:bytesWritten]; + // } else { + // can probably get more detailed error info via [fileStream streamError] + // errCode already set to INVALID_MODIFICATION_ERR; + // bytesWritten = 0; // may be set to -1 on error + } + } + } // else fileStream not created return INVALID_MODIFICATION_ERR + } else { + // invalid filePath + errCode = NOT_FOUND_ERR; + } + if (!result) { + // was an error + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsInt:errCode]; + } + return result; +} + +/** + * Helper function to check to see if the user attempted to copy an entry into its parent without changing its name, + * or attempted to copy a directory into a directory that it contains directly or indirectly. + * + * IN: + * NSString* srcDir + * NSString* destinationDir + * OUT: + * YES copy/ move is allows + * NO move is onto itself + */ +- (BOOL)canCopyMoveSrc:(NSString*)src ToDestination:(NSString*)dest +{ + // This weird test is to determine if we are copying or moving a directory into itself. + // Copy /Documents/myDir to /Documents/myDir-backup is okay but + // Copy /Documents/myDir to /Documents/myDir/backup not okay + BOOL copyOK = YES; + NSRange range = [dest rangeOfString:src]; + + if (range.location != NSNotFound) { + NSRange testRange = {range.length - 1, ([dest length] - range.length)}; + NSRange resultRange = [dest rangeOfString:@"/" options:0 range:testRange]; + if (resultRange.location != NSNotFound) { + copyOK = NO; + } + } + return copyOK; +} + +- (void)copyFileToURL:(CDVFilesystemURL *)destURL withName:(NSString *)newName fromFileSystem:(NSObject *)srcFs atURL:(CDVFilesystemURL *)srcURL copy:(BOOL)bCopy callback:(void (^)(CDVPluginResult *))callback +{ + NSFileManager *fileMgr = [[NSFileManager alloc] init]; + NSString *destRootPath = [self filesystemPathForURL:destURL]; + BOOL bDestIsDir = NO; + BOOL bDestExists = [fileMgr fileExistsAtPath:destRootPath isDirectory:&bDestIsDir]; + + NSString *newFileSystemPath = [destRootPath stringByAppendingPathComponent:newName]; + NSString *newFullPath = [self fullPathForFileSystemPath:newFileSystemPath]; + + BOOL bNewIsDir = NO; + BOOL bNewExists = [fileMgr fileExistsAtPath:newFileSystemPath isDirectory:&bNewIsDir]; + + CDVPluginResult *result = nil; + int errCode = 0; + + if (!bDestExists) { + // the destination root does not exist + errCode = NOT_FOUND_ERR; + } + + else if ([srcFs isKindOfClass:[CDVLocalFilesystem class]]) { + /* Same FS, we can shortcut with NSFileManager operations */ + NSString *srcFullPath = [srcFs filesystemPathForURL:srcURL]; + + BOOL bSrcIsDir = NO; + BOOL bSrcExists = [fileMgr fileExistsAtPath:srcFullPath isDirectory:&bSrcIsDir]; + + if (!bSrcExists) { + // the source does not exist + errCode = NOT_FOUND_ERR; + } else if ([newFileSystemPath isEqualToString:srcFullPath]) { + // source and destination can not be the same + errCode = INVALID_MODIFICATION_ERR; + } else if (bSrcIsDir && (bNewExists && !bNewIsDir)) { + // can't copy/move dir to file + errCode = INVALID_MODIFICATION_ERR; + } else { // no errors yet + NSError* __autoreleasing error = nil; + BOOL bSuccess = NO; + if (bCopy) { + if (bSrcIsDir && ![self canCopyMoveSrc:srcFullPath ToDestination:newFileSystemPath]) { + // can't copy dir into self + errCode = INVALID_MODIFICATION_ERR; + } else if (bNewExists) { + // the full destination should NOT already exist if a copy + errCode = PATH_EXISTS_ERR; + } else { + bSuccess = [fileMgr copyItemAtPath:srcFullPath toPath:newFileSystemPath error:&error]; + } + } else { // move + // iOS requires that destination must not exist before calling moveTo + // is W3C INVALID_MODIFICATION_ERR error if destination dir exists and has contents + // + if (!bSrcIsDir && (bNewExists && bNewIsDir)) { + // can't move a file to directory + errCode = INVALID_MODIFICATION_ERR; + } else if (bSrcIsDir && ![self canCopyMoveSrc:srcFullPath ToDestination:newFileSystemPath]) { + // can't move a dir into itself + errCode = INVALID_MODIFICATION_ERR; + } else if (bNewExists) { + if (bNewIsDir && ([[fileMgr contentsOfDirectoryAtPath:newFileSystemPath error:NULL] count] != 0)) { + // can't move dir to a dir that is not empty + errCode = INVALID_MODIFICATION_ERR; + newFileSystemPath = nil; // so we won't try to move + } else { + // remove destination so can perform the moveItemAtPath + bSuccess = [fileMgr removeItemAtPath:newFileSystemPath error:NULL]; + if (!bSuccess) { + errCode = INVALID_MODIFICATION_ERR; // is this the correct error? + newFileSystemPath = nil; + } + } + } else if (bNewIsDir && [newFileSystemPath hasPrefix:srcFullPath]) { + // can't move a directory inside itself or to any child at any depth; + errCode = INVALID_MODIFICATION_ERR; + newFileSystemPath = nil; + } + + if (newFileSystemPath != nil) { + bSuccess = [fileMgr moveItemAtPath:srcFullPath toPath:newFileSystemPath error:&error]; + } + } + if (bSuccess) { + // should verify it is there and of the correct type??? + NSDictionary* newEntry = [self makeEntryForPath:newFullPath isDirectory:bSrcIsDir]; + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:newEntry]; + } else { + if (error) { + if (([error code] == NSFileReadUnknownError) || ([error code] == NSFileReadTooLargeError)) { + errCode = NOT_READABLE_ERR; + } else if ([error code] == NSFileWriteOutOfSpaceError) { + errCode = QUOTA_EXCEEDED_ERR; + } else if ([error code] == NSFileWriteNoPermissionError) { + errCode = NO_MODIFICATION_ALLOWED_ERR; + } + } + } + } + } else { + // Need to copy the hard way + [srcFs readFileAtURL:srcURL start:0 end:-1 callback:^(NSData* data, NSString* mimeType, CDVFileError errorCode) { + CDVPluginResult* result = nil; + if (data != nil) { + BOOL bSuccess = [data writeToFile:newFileSystemPath atomically:YES]; + if (bSuccess) { + // should verify it is there and of the correct type??? + NSDictionary* newEntry = [self makeEntryForPath:newFullPath isDirectory:NO]; + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:newEntry]; + } else { + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:ABORT_ERR]; + } + } else { + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:errorCode]; + } + callback(result); + }]; + return; // Async IO; return without callback. + } + if (result == nil) { + if (!errCode) { + errCode = INVALID_MODIFICATION_ERR; // Catch-all default + } + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:errCode]; + } + callback(result); +} + +/* helper function to get the mimeType from the file extension + * IN: + * NSString* fullPath - filename (may include path) + * OUT: + * NSString* the mime type as type/subtype. nil if not able to determine + */ ++ (NSString*)getMimeTypeFromPath:(NSString*)fullPath +{ + NSString* mimeType = nil; + + if (fullPath) { + CFStringRef typeId = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)[fullPath pathExtension], NULL); + if (typeId) { + mimeType = (__bridge_transfer NSString*)UTTypeCopyPreferredTagWithClass(typeId, kUTTagClassMIMEType); + if (!mimeType) { + // special case for m4a + if ([(__bridge NSString*)typeId rangeOfString : @"m4a-audio"].location != NSNotFound) { + mimeType = @"audio/mp4"; + } else if ([[fullPath pathExtension] rangeOfString:@"wav"].location != NSNotFound) { + mimeType = @"audio/wav"; + } else if ([[fullPath pathExtension] rangeOfString:@"css"].location != NSNotFound) { + mimeType = @"text/css"; + } + } + CFRelease(typeId); + } + } + return mimeType; +} + +- (void)readFileAtURL:(CDVFilesystemURL *)localURL start:(NSInteger)start end:(NSInteger)end callback:(void (^)(NSData*, NSString* mimeType, CDVFileError))callback +{ + NSString *path = [self filesystemPathForURL:localURL]; + + NSString* mimeType = [CDVLocalFilesystem getMimeTypeFromPath:path]; + if (mimeType == nil) { + mimeType = @"*/*"; + } + NSFileHandle* file = [NSFileHandle fileHandleForReadingAtPath:path]; + if (start > 0) { + [file seekToFileOffset:start]; + } + + NSData* readData; + if (end < 0) { + readData = [file readDataToEndOfFile]; + } else { + readData = [file readDataOfLength:(end - start)]; + } + [file closeFile]; + + callback(readData, mimeType, readData != nil ? NO_ERROR : NOT_FOUND_ERR); +} + +- (void)getFileMetadataForURL:(CDVFilesystemURL *)localURL callback:(void (^)(CDVPluginResult *))callback +{ + NSString *path = [self filesystemPathForURL:localURL]; + CDVPluginResult *result; + NSFileManager* fileMgr = [[NSFileManager alloc] init]; + + NSError* __autoreleasing error = nil; + NSDictionary* fileAttrs = [fileMgr attributesOfItemAtPath:path error:&error]; + + if (fileAttrs) { + + // create dictionary of file info + NSMutableDictionary* fileInfo = [NSMutableDictionary dictionaryWithCapacity:5]; + + [fileInfo setObject:localURL.fullPath forKey:@"fullPath"]; + [fileInfo setObject:@"" forKey:@"type"]; // can't easily get the mimetype unless create URL, send request and read response so skipping + [fileInfo setObject:[path lastPathComponent] forKey:@"name"]; + + // Ensure that directories (and other non-regular files) report size of 0 + unsigned long long size = ([fileAttrs fileType] == NSFileTypeRegular ? [fileAttrs fileSize] : 0); + [fileInfo setObject:[NSNumber numberWithUnsignedLongLong:size] forKey:@"size"]; + + NSDate* modDate = [fileAttrs fileModificationDate]; + if (modDate) { + [fileInfo setObject:[NSNumber numberWithDouble:[modDate timeIntervalSince1970] * 1000] forKey:@"lastModifiedDate"]; + } + + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:fileInfo]; + + } else { + // didn't get fileAttribs + CDVFileError errorCode = ABORT_ERR; + NSLog(@"error getting metadata: %@", [error localizedDescription]); + if ([error code] == NSFileNoSuchFileError || [error code] == NSFileReadNoSuchFileError) { + errorCode = NOT_FOUND_ERR; + } + // log [NSNumber numberWithDouble: theMessage] objCtype to see what it returns + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsInt:errorCode]; + } + + callback(result); +} + +@end diff --git a/plugins/cordova-plugin-file/src/ubuntu/file.cpp b/plugins/cordova-plugin-file/src/ubuntu/file.cpp new file mode 100644 index 0000000..395ab2d --- /dev/null +++ b/plugins/cordova-plugin-file/src/ubuntu/file.cpp @@ -0,0 +1,912 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "file.h" + +#include + +namespace { + class FileError { + public: + static const QString kEncodingErr; + static const QString kTypeMismatchErr; + static const QString kNotFoundErr; + static const QString kSecurityErr; + static const QString kAbortErr; + static const QString kNotReadableErr; + static const QString kNoModificationAllowedErr; + static const QString kInvalidStateErr; + static const QString kSyntaxErr; + static const QString kInvalidModificationErr; + static const QString kQuotaExceededErr; + static const QString kPathExistsErr; + }; + + bool checkFileName(const QString &name) { + if (name.contains(":")){ + return false; + } + return true; + } +}; + +const QString FileError::kEncodingErr("FileError.ENCODING_ERR"); +const QString FileError::kTypeMismatchErr("FileError.TYPE_MISMATCH_ERR"); +const QString FileError::kNotFoundErr("FileError.NOT_FOUND_ERR"); +const QString FileError::kSecurityErr("FileError.SECURITY_ERR"); +const QString FileError::kAbortErr("FileError.ABORT_ERR"); +const QString FileError::kNotReadableErr("FileError.NOT_READABLE_ERR"); +const QString FileError::kNoModificationAllowedErr("FileError.NO_MODIFICATION_ALLOWED_ERR"); +const QString FileError::kInvalidStateErr("FileError.INVALID_STATE_ERR"); +const QString FileError::kSyntaxErr("FileError.SYNTAX_ERR"); +const QString FileError::kInvalidModificationErr("FileError.INVALID_MODIFICATION_ERR"); +const QString FileError::kQuotaExceededErr("FileError.QUOTA_EXCEEDED_ERR"); +const QString FileError::kPathExistsErr("FileError.PATH_EXISTS_ERR"); + +File::File(Cordova *cordova) : + CPlugin(cordova), + _persistentDir(QString("%1/.local/share/%2/persistent").arg(QDir::homePath()).arg(QCoreApplication::applicationName())) { + QDir::root().mkpath(_persistentDir.absolutePath()); +} + +QVariantMap File::file2map(const QFileInfo &fileInfo) { + QVariantMap res; + + res.insert("name", fileInfo.fileName()); + QPair r = GetRelativePath(fileInfo); + res.insert("fullPath", QString("/") + r.second); + res.insert("filesystemName", r.first); + + res.insert("nativeURL", QString("file://localhost") + fileInfo.absoluteFilePath()); + res.insert("isDirectory", (int)fileInfo.isDir()); + res.insert("isFile", (int)fileInfo.isFile()); + + return res; +} + +QVariantMap File::dir2map(const QDir &dir) { + return file2map(QFileInfo(dir.absolutePath())); +} + +QPair File::GetRelativePath(const QFileInfo &fileInfo) { + QString fullPath = fileInfo.isDir() ? QDir::cleanPath(fileInfo.absoluteFilePath()) : fileInfo.absoluteFilePath(); + + QString relativePath1 = _persistentDir.relativeFilePath(fullPath); + QString relativePath2 = QDir::temp().relativeFilePath(fullPath); + + if (!(relativePath1[0] != '.' || relativePath2[0] != '.')) { + if (relativePath1.size() > relativePath2.size()) { + return QPair("temporary", relativePath2); + } else { + return QPair("persistent", relativePath1); + } + } + + if (relativePath1[0] != '.') + return QPair("persistent", relativePath1); + return QPair("temporary", relativePath2); +} + +void File::requestFileSystem(int scId, int ecId, unsigned short type, unsigned long long size) { + QDir dir; + + if (size >= 1000485760){ + this->callback(ecId, FileError::kQuotaExceededErr); + return; + } + + if (type == 0) + dir = QDir::temp(); + else + dir = _persistentDir; + + if (type > 1) { + this->callback(ecId, FileError::kSyntaxErr); + return; + } else { + QVariantMap res; + res.insert("root", dir2map(dir)); + if (type == 0) + res.insert("name", "temporary"); + else + res.insert("name", "persistent"); + + this->cb(scId, res); + } +} + +QPair File::resolveURI(int ecId, const QString &uri) { + QPair result; + + result.first = false; + + QUrl url = QUrl::fromUserInput(uri); + + if (url.scheme() == "file" && url.isValid()) { + result.first = true; + result.second = QFileInfo(url.path()); + return result; + } + + if (url.scheme() != "cdvfile") { + if (ecId) + this->callback(ecId, FileError::kTypeMismatchErr); + return result; + } + + QString path = url.path().replace("//", "/"); + //NOTE: colon is not safe in url, it is not a valid path in Win and Mac, simple disable it here. + if (path.contains(":") || !url.isValid()){ + if (ecId) + this->callback(ecId, FileError::kEncodingErr); + return result; + } + if (!path.startsWith("/persistent/") && !path.startsWith("/temporary/")) { + if (ecId) + this->callback(ecId, FileError::kEncodingErr); + return result; + } + + result.first = true; + if (path.startsWith("/persistent/")) { + QString relativePath = path.mid(QString("/persistent/").size()); + result.second = QFileInfo(_persistentDir.filePath(relativePath)); + } else { + QString relativePath = path.mid(QString("/temporary/").size()); + result.second = QFileInfo(QDir::temp().filePath(relativePath)); + } + return result; +} + +QPair File::resolveURI(const QString &uri) { + return resolveURI(0, uri); +} + + +void File::_getLocalFilesystemPath(int scId, int ecId, const QString& uri) { + QPair f1 = resolveURI(ecId, uri); + + if (!f1.first) + return; + + this->cb(scId, f1.second.absoluteFilePath()); +} + +void File::resolveLocalFileSystemURI(int scId, int ecId, const QString &uri) { + if (uri[0] == '/' || uri[0] == '.') { + this->callback(ecId, FileError::kEncodingErr); + return; + } + + QPair f1 = resolveURI(ecId, uri); + + if (!f1.first) + return; + + QFileInfo fileInfo = f1.second; + if (!fileInfo.exists()) { + this->callback(ecId, FileError::kNotFoundErr); + return; + } + + this->cb(scId, file2map(fileInfo)); +} + +void File::getFile(int scId, int ecId, const QString &parentPath, const QString &rpath, const QVariantMap &options) { + QPair f1 = resolveURI(ecId, parentPath + "/" + rpath); + if (!f1.first) + return; + + bool create = options.value("create").toBool(); + bool exclusive = options.value("exclusive").toBool(); + QFile file(f1.second.absoluteFilePath()); + + // if create is false and the path represents a directory, return error + QFileInfo fileInfo = f1.second; + if ((!create) && fileInfo.isDir()) { + this->callback(ecId, FileError::kTypeMismatchErr); + return; + } + + // if file does exist, and create is true and exclusive is true, return error + if (file.exists()) { + if (create && exclusive) { + this->callback(ecId, FileError::kPathExistsErr); + return; + } + } + else { + // if file does not exist and create is false, return error + if (!create) { + this->callback(ecId, FileError::kNotFoundErr); + return; + } + + file.open(QIODevice::WriteOnly); + file.close(); + + // Check if creation was successfull + if (!file.exists()) { + this->callback(ecId, FileError::kNoModificationAllowedErr); + return; + } + } + + this->cb(scId, file2map(QFileInfo(file))); +} + +void File::getDirectory(int scId, int ecId, const QString &parentPath, const QString &rpath, const QVariantMap &options) { + QPair f1 = resolveURI(ecId, parentPath + "/" + rpath); + if (!f1.first) + return; + + bool create = options.value("create").toBool(); + bool exclusive = options.value("exclusive").toBool(); + QDir dir(f1.second.absoluteFilePath()); + + QFileInfo &fileInfo = f1.second; + if ((!create) && fileInfo.isFile()) { + this->callback(ecId, FileError::kTypeMismatchErr); + return; + } + + if (dir.exists()) { + if (create && exclusive) { + this->callback(ecId, FileError::kPathExistsErr); + return; + } + } + else { + if (!create) { + this->callback(ecId, FileError::kNotFoundErr); + return; + } + + QString folderName = dir.dirName(); + dir.cdUp(); + dir.mkdir(folderName); + dir.cd(folderName); + + if (!dir.exists()) { + this->callback(ecId, FileError::kNoModificationAllowedErr); + return; + } + } + + this->cb(scId, dir2map(dir)); +} + +void File::removeRecursively(int scId, int ecId, const QString &uri) { + QPair f1 = resolveURI(ecId, uri); + + if (!f1.first) + return; + + QDir dir(f1.second.absoluteFilePath()); + if (File::rmDir(dir)) + this->cb(scId); + else + this->callback(ecId, FileError::kNoModificationAllowedErr); +} + +void File::write(int scId, int ecId, const QString &uri, const QString &_data, unsigned long long position, bool binary) { + QPair f1 = resolveURI(ecId, uri); + + if (!f1.first) + return; + + QFile file(f1.second.absoluteFilePath()); + + file.open(QIODevice::WriteOnly); + file.close(); + + if (!file.exists()) { + this->callback(ecId, FileError::kNotFoundErr); + return; + } + + QFileInfo fileInfo(file); + if (!file.open(QIODevice::ReadWrite)) { + this->callback(ecId, FileError::kNoModificationAllowedErr); + return; + } + + if (!binary) { + QTextStream textStream(&file); + textStream.setCodec("UTF-8"); + textStream.setAutoDetectUnicode(true); + + if (!textStream.seek(position)) { + file.close(); + fileInfo.refresh(); + + this->callback(ecId, FileError::kInvalidModificationErr); + return; + } + + textStream << _data; + textStream.flush(); + } else { + QByteArray data(_data.toUtf8()); + if (!file.seek(position)) { + file.close(); + fileInfo.refresh(); + + this->callback(ecId, FileError::kInvalidModificationErr); + return; + } + + file.write(data.data(), data.length()); + } + + file.flush(); + file.close(); + fileInfo.refresh(); + + this->cb(scId, fileInfo.size() - position); +} + +void File::truncate(int scId, int ecId, const QString &uri, unsigned long long size) { + QPair f1 = resolveURI(ecId, uri); + + if (!f1.first) + return; + + QFile file(f1.second.absoluteFilePath()); + + if (!file.exists()) { + this->callback(ecId, FileError::kNotFoundErr); + return; + } + + if (!file.resize(size)) { + this->callback(ecId, FileError::kNoModificationAllowedErr); + return; + } + + this->cb(scId, size); +} + +void File::getParent(int scId, int ecId, const QString &uri) { + QPair f1 = resolveURI(ecId, uri); + + if (!f1.first) + return; + QDir dir(f1.second.absoluteFilePath()); + + //can't cdup more than app's root + // Try to change into upper directory + if (dir != _persistentDir && dir != QDir::temp()){ + if (!dir.cdUp()) { + this->callback(ecId, FileError::kNotFoundErr); + return; + } + + } + this->cb(scId, dir2map(dir)); +} + +void File::remove(int scId, int ecId, const QString &uri) { + QPair f1 = resolveURI(ecId, uri); + if (!f1.first) + return; + + QFileInfo &fileInfo = f1.second; + //TODO: fix + if (!fileInfo.exists() || (fileInfo.absoluteFilePath() == _persistentDir.absolutePath()) || (QDir::temp() == fileInfo.absoluteFilePath())) { + this->callback(ecId, FileError::kNoModificationAllowedErr); + return; + } + + if (fileInfo.isDir()) { + QDir dir(fileInfo.absoluteFilePath()); + if (dir.rmdir(dir.absolutePath())) { + this->cb(scId); + return; + } + } else { + QFile file(fileInfo.absoluteFilePath()); + if (file.remove()) { + this->cb(scId); + return; + } + } + + this->callback(ecId, FileError::kInvalidModificationErr); +} + +void File::getFileMetadata(int scId, int ecId, const QString &uri) { + QPair f1 = resolveURI(ecId, uri); + + if (!f1.first) + return; + QFileInfo &fileInfo = f1.second; + + if (!fileInfo.exists()) { + this->callback(ecId, FileError::kNotFoundErr); + } else { + QMimeType mime = _db.mimeTypeForFile(fileInfo.fileName()); + + QString args = QString("{name: %1, fullPath: %2, type: %3, lastModifiedDate: new Date(%4), size: %5}") + .arg(CordovaInternal::format(fileInfo.fileName())).arg(CordovaInternal::format(fileInfo.absoluteFilePath())) + .arg(CordovaInternal::format(mime.name())).arg(fileInfo.lastModified().toMSecsSinceEpoch()) + .arg(fileInfo.size()); + + this->callback(scId, args); + } +} + +void File::getMetadata(int scId, int ecId, const QString &uri) { + QPair f1 = resolveURI(ecId, uri); + + if (!f1.first) + return; + QFileInfo &fileInfo = f1.second; + + if (!fileInfo.exists()) + this->callback(ecId, FileError::kNotFoundErr); + else { + QVariantMap obj; + obj.insert("modificationTime", fileInfo.lastModified().toMSecsSinceEpoch()); + obj.insert("size", fileInfo.isDir() ? 0 : fileInfo.size()); + this->cb(scId, obj); + } +} + +void File::readEntries(int scId, int ecId, const QString &uri) { + QPair f1 = resolveURI(ecId, uri); + + if (!f1.first) + return; + QDir dir(f1.second.absoluteFilePath()); + QString entriesList; + + if (!dir.exists()) { + this->callback(ecId, FileError::kNotFoundErr); + return; + } + + for (const QFileInfo &fileInfo: dir.entryInfoList(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot)) { + entriesList += CordovaInternal::format(file2map(fileInfo)) + ","; + } + // Remove trailing comma + if (entriesList.size() > 0) + entriesList.remove(entriesList.size() - 1, 1); + + entriesList = "new Array(" + entriesList + ")"; + + this->callback(scId, entriesList); +} + +void File::readAsText(int scId, int ecId, const QString &uri, const QString &/*encoding*/, int sliceStart, int sliceEnd) { + QPair f1 = resolveURI(ecId, uri); + + if (!f1.first) + return; + + QFile file(f1.second.absoluteFilePath()); + + if (!file.exists()) { + this->callback(ecId, FileError::kNotFoundErr); + return; + } + + if (!file.open(QIODevice::ReadOnly)) { + this->callback(ecId, FileError::kNotReadableErr); + return; + } + + QByteArray content = file.readAll(); + + if (sliceEnd == -1) + sliceEnd = content.size(); + if (sliceEnd < 0) { + sliceEnd++; + sliceEnd = std::max(0, content.size() + sliceEnd); + } + if (sliceEnd > content.size()) + sliceEnd = content.size(); + + if (sliceStart < 0) + sliceStart = std::max(0, content.size() + sliceStart); + if (sliceStart > content.size()) + sliceStart = content.size(); + + if (sliceStart > sliceEnd) + sliceEnd = sliceStart; + + //FIXME: encoding + content = content.mid(sliceStart, sliceEnd - sliceStart); + + this->cb(scId, content); +} + +void File::readAsArrayBuffer(int scId, int ecId, const QString &uri, int sliceStart, int sliceEnd) { + const QString str2array("\ + (function strToArray(str) { \ + var res = new Uint8Array(str.length); \ + for (var i = 0; i < str.length; i++) { \ + res[i] = str.charCodeAt(i); \ + } \ + return res; \ + })(\"%1\")"); + + QPair f1 = resolveURI(ecId, uri); + + if (!f1.first) + return; + + QFile file(f1.second.absoluteFilePath()); + + if (!file.exists()) { + this->callback(ecId, FileError::kNotFoundErr); + return; + } + + if (!file.open(QIODevice::ReadOnly)) { + this->callback(ecId, FileError::kNotReadableErr); + return; + } + QString res; + QByteArray content = file.readAll(); + + if (sliceEnd == -1) + sliceEnd = content.size(); + if (sliceEnd < 0) { + sliceEnd++; + sliceEnd = std::max(0, content.size() + sliceEnd); + } + if (sliceEnd > content.size()) + sliceEnd = content.size(); + + if (sliceStart < 0) + sliceStart = std::max(0, content.size() + sliceStart); + if (sliceStart > content.size()) + sliceStart = content.size(); + + if (sliceStart > sliceEnd) + sliceEnd = sliceStart; + + content = content.mid(sliceStart, sliceEnd - sliceStart); + + res.reserve(content.length() * 6); + for (uchar c: content) { + res += "\\x"; + res += QString::number(c, 16).rightJustified(2, '0').toUpper(); + } + + this->callback(scId, str2array.arg(res)); +} + +void File::readAsBinaryString(int scId, int ecId, const QString &uri, int sliceStart, int sliceEnd) { + QPair f1 = resolveURI(ecId, uri); + + if (!f1.first) + return; + + QFile file(f1.second.absoluteFilePath()); + + if (!file.exists()) { + this->callback(ecId, FileError::kNotFoundErr); + return; + } + + if (!file.open(QIODevice::ReadOnly)) { + this->callback(ecId, FileError::kNotReadableErr); + return; + } + QString res; + QByteArray content = file.readAll(); + + if (sliceEnd == -1) + sliceEnd = content.size(); + if (sliceEnd < 0) { + sliceEnd++; + sliceEnd = std::max(0, content.size() + sliceEnd); + } + if (sliceEnd > content.size()) + sliceEnd = content.size(); + + if (sliceStart < 0) + sliceStart = std::max(0, content.size() + sliceStart); + if (sliceStart > content.size()) + sliceStart = content.size(); + + if (sliceStart > sliceEnd) + sliceEnd = sliceStart; + + content = content.mid(sliceStart, sliceEnd - sliceStart); + + res.reserve(content.length() * 6); + for (uchar c: content) { + res += "\\x"; + res += QString::number(c, 16).rightJustified(2, '0').toUpper(); + } + this->callback(scId, "\"" + res + "\""); +} + +void File::readAsDataURL(int scId, int ecId, const QString &uri, int sliceStart, int sliceEnd) { + QPair f1 = resolveURI(ecId, uri); + + if (!f1.first) + return; + + QFile file(f1.second.absoluteFilePath()); + QFileInfo &fileInfo = f1.second; + + if (!file.exists()) { + this->callback(ecId, FileError::kNotReadableErr); + return; + } + + if (!file.open(QIODevice::ReadOnly)) { + this->callback(ecId, FileError::kNotReadableErr); + return; + } + + QByteArray content = file.readAll(); + QString contentType(_db.mimeTypeForFile(fileInfo.fileName()).name()); + + if (sliceEnd == -1) + sliceEnd = content.size(); + if (sliceEnd < 0) { + sliceEnd++; + sliceEnd = std::max(0, content.size() + sliceEnd); + } + if (sliceEnd > content.size()) + sliceEnd = content.size(); + + if (sliceStart < 0) + sliceStart = std::max(0, content.size() + sliceStart); + if (sliceStart > content.size()) + sliceStart = content.size(); + + if (sliceStart > sliceEnd) + sliceEnd = sliceStart; + + content = content.mid(sliceStart, sliceEnd - sliceStart); + + this->cb(scId, QString("data:%1;base64,").arg(contentType) + content.toBase64()); +} + +bool File::rmDir(const QDir &dir) { + if (dir == _persistentDir || dir == QDir::temp()) {//can't remove root dir + return false; + } + bool result = true; + if (dir.exists()) { + // Iterate over entries and remove them + Q_FOREACH(const QFileInfo &fileInfo, dir.entryInfoList(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot)) { + if (fileInfo.isDir()) { + result = rmDir(fileInfo.absoluteFilePath()); + } + else { + result = QFile::remove(fileInfo.absoluteFilePath()); + } + + if (!result) { + return result; + } + } + + // Finally remove the current dir + return dir.rmdir(dir.absolutePath()); + } + return result; +} + +bool File::copyFile(int scId, int ecId,const QString& sourceUri, const QString& destinationUri, const QString& newName) { + QPair destDir = resolveURI(ecId, destinationUri); + QPair sourceFile = resolveURI(ecId, sourceUri); + + if (!destDir.first || !sourceFile.first) + return false; + + if (!checkFileName(newName)) { + this->callback(ecId, FileError::kEncodingErr); + return false; + } + + if (destDir.second.isFile()) { + this->callback(ecId, FileError::kInvalidModificationErr); + return false; + } + + if (!destDir.second.isDir()) { + this->callback(ecId, FileError::kNotFoundErr); + return false; + } + + QFileInfo &fileInfo = sourceFile.second; + QString fileName((newName.isEmpty()) ? fileInfo.fileName() : newName); + QString destinationFile(QDir(destDir.second.absoluteFilePath()).filePath(fileName)); + if (QFile::copy(fileInfo.absoluteFilePath(), destinationFile)){ + this->cb(scId, file2map(QFileInfo(destinationFile))); + return true; + } + this->callback(ecId, FileError::kInvalidModificationErr); + return false; +} + +void File::copyDir(int scId, int ecId,const QString& sourceUri, const QString& destinationUri, const QString& newName) { + QPair destDir = resolveURI(ecId, destinationUri); + QPair sourceDir = resolveURI(ecId, sourceUri); + + if (!destDir.first || !sourceDir.first) + return; + if (!checkFileName(newName)) { + this->callback(ecId, FileError::kEncodingErr); + return; + } + + QString targetName = ((newName.isEmpty()) ? sourceDir.second.fileName() : newName); + QString target(QDir(destDir.second.absoluteFilePath()).filePath(targetName)); + + if (QFileInfo(target).isFile()){ + this->callback(ecId, FileError::kInvalidModificationErr); + return; + } + + // check: copy directory into itself + if (QDir(sourceDir.second.absoluteFilePath()).relativeFilePath(target)[0] != '.'){ + this->callback(ecId, FileError::kInvalidModificationErr); + return; + } + + if (!QDir(target).exists()){ + QDir(destDir.second.absoluteFilePath()).mkdir(target);; + } else{ + this->callback(ecId, FileError::kInvalidModificationErr); + return; + } + + if (copyFolder(sourceDir.second.absoluteFilePath(), target)){ + this->cb(scId, dir2map(QDir(target))); + return; + } + this->callback(ecId, FileError::kInvalidModificationErr); + return; +} + +void File::copyTo(int scId, int ecId, const QString& source, const QString& destinationDir, const QString& newName) { + QPair f1 = resolveURI(ecId, source); + + if (!f1.first) + return; + + if (f1.second.isDir()) + copyDir(scId, ecId, source, destinationDir, newName); + else + copyFile(scId, ecId, source, destinationDir, newName); +} + +void File::moveFile(int scId, int ecId,const QString& sourceUri, const QString& destinationUri, const QString& newName) { + QPair sourceFile = resolveURI(ecId, sourceUri); + QPair destDir = resolveURI(ecId, destinationUri); + + if (!destDir.first || !sourceFile.first) + return; + if (!checkFileName(newName)) { + this->callback(ecId, FileError::kEncodingErr); + return; + } + + QString fileName = ((newName.isEmpty()) ? sourceFile.second.fileName() : newName); + QString target = QDir(destDir.second.absoluteFilePath()).filePath(fileName); + + if (sourceFile.second == QFileInfo(target)) { + this->callback(ecId, FileError::kInvalidModificationErr); + return; + } + + if (!destDir.second.exists()) { + this->callback(ecId, FileError::kNotFoundErr); + return; + } + if (!destDir.second.isDir()){ + this->callback(ecId, FileError::kInvalidModificationErr); + return; + } + + if (QFileInfo(target).exists()) { + if (!QFile::remove(target)) { + this->callback(ecId, FileError::kInvalidModificationErr); + return; + } + } + + QFile::rename(sourceFile.second.absoluteFilePath(), target); + this->cb(scId, file2map(QFileInfo(target))); +} + +void File::moveDir(int scId, int ecId,const QString& sourceUri, const QString& destinationUri, const QString& newName){ + QPair sourceDir = resolveURI(ecId, sourceUri); + QPair destDir = resolveURI(ecId, destinationUri); + + if (!destDir.first || !sourceDir.first) + return; + if (!checkFileName(newName)) { + this->callback(ecId, FileError::kEncodingErr); + return; + } + + QString fileName = ((newName.isEmpty()) ? sourceDir.second.fileName() : newName); + QString target = QDir(destDir.second.absoluteFilePath()).filePath(fileName); + + if (!destDir.second.exists()){ + this->callback(ecId, FileError::kNotFoundErr); + return; + } + + if (destDir.second.isFile()){ + this->callback(ecId, FileError::kInvalidModificationErr); + return; + } + + // check: copy directory into itself + if (QDir(sourceDir.second.absoluteFilePath()).relativeFilePath(target)[0] != '.'){ + this->callback(ecId, FileError::kInvalidModificationErr); + return; + } + + if (QFileInfo(target).exists() && !QDir(destDir.second.absoluteFilePath()).rmdir(fileName)) { + this->callback(ecId, FileError::kInvalidModificationErr); + return; + } + + if (copyFolder(sourceDir.second.absoluteFilePath(), target)) { + rmDir(sourceDir.second.absoluteFilePath()); + this->cb(scId, file2map(QFileInfo(target))); + } else { + this->callback(ecId, FileError::kNoModificationAllowedErr); + } +} + +void File::moveTo(int scId, int ecId, const QString& source, const QString& destinationDir, const QString& newName) { + QPair f1 = resolveURI(ecId, source); + + if (!f1.first) + return; + + if (f1.second.isDir()) + moveDir(scId, ecId, source, destinationDir, newName); + else + moveFile(scId, ecId, source, destinationDir, newName); +} + +bool File::copyFolder(const QString& sourceFolder, const QString& destFolder) { + QDir sourceDir(sourceFolder); + if (!sourceDir.exists()) + return false; + QDir destDir(destFolder); + if (!destDir.exists()){ + destDir.mkdir(destFolder); + } + QStringList files = sourceDir.entryList(QDir::Files); + for (int i = 0; i< files.count(); i++) + { + QString srcName = sourceFolder + "/" + files[i]; + QString destName = destFolder + "/" + files[i]; + QFile::copy(srcName, destName); + } + files.clear(); + files = sourceDir.entryList(QDir::AllDirs | QDir::NoDotAndDotDot); + for (int i = 0; i< files.count(); i++) + { + QString srcName = sourceFolder + "/" + files[i]; + QString destName = destFolder + "/" + files[i]; + copyFolder(srcName, destName); + } + return true; +} diff --git a/plugins/cordova-plugin-file/src/ubuntu/file.h b/plugins/cordova-plugin-file/src/ubuntu/file.h new file mode 100644 index 0000000..de27762 --- /dev/null +++ b/plugins/cordova-plugin-file/src/ubuntu/file.h @@ -0,0 +1,81 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FILEAPI_H_SDASDASDAS +#define FILEAPI_H_SDASDASDAS + +#include +#include + +#include +#include + +class File: public CPlugin { + Q_OBJECT +public: + explicit File(Cordova *cordova); + + virtual const QString fullName() override { + return File::fullID(); + } + + virtual const QString shortName() override { + return "File"; + } + + static const QString fullID() { + return "File"; + } + QPair resolveURI(const QString &uri); + QPair resolveURI(int ecId, const QString &uri); + QVariantMap file2map(const QFileInfo &dir); + +public slots: + void requestFileSystem(int scId, int ecId, unsigned short type, unsigned long long size); + void resolveLocalFileSystemURI(int scId, int ecId, const QString&); + void getDirectory(int scId, int ecId, const QString&, const QString&, const QVariantMap&); + void getFile(int scId, int ecId, const QString &parentPath, const QString &rpath, const QVariantMap &options); + void readEntries(int scId, int ecId, const QString &uri); + void getParent(int scId, int ecId, const QString &uri); + void copyTo(int scId, int ecId, const QString& source, const QString& destinationDir, const QString& newName); + void moveTo(int scId, int ecId, const QString& source, const QString& destinationDir, const QString& newName); + void getFileMetadata(int scId, int ecId, const QString &); + void getMetadata(int scId, int ecId, const QString &); + void remove(int scId, int ecId, const QString &); + void removeRecursively(int scId, int ecId, const QString&); + void write(int scId, int ecId, const QString&, const QString&, unsigned long long position, bool binary); + void readAsText(int scId, int ecId, const QString&, const QString &encoding, int sliceStart, int sliceEnd); + void readAsDataURL(int scId, int ecId, const QString&, int sliceStart, int sliceEnd); + void readAsArrayBuffer(int scId, int ecId, const QString&, int sliceStart, int sliceEnd); + void readAsBinaryString(int scId, int ecId, const QString&, int sliceStart, int sliceEnd); + void truncate(int scId, int ecId, const QString&, unsigned long long size); + + void _getLocalFilesystemPath(int scId, int ecId, const QString&); +private: + void moveFile(int scId, int ecId,const QString&, const QString&, const QString&); + void moveDir(int scId, int ecId,const QString&, const QString&, const QString&); + bool copyFile(int scId, int ecId, const QString&, const QString&, const QString&); + void copyDir(int scId, int ecId, const QString&, const QString&, const QString&); + bool rmDir(const QDir &dir); + bool copyFolder(const QString&, const QString&); + + QPair GetRelativePath(const QFileInfo &fileInfo); + QVariantMap dir2map(const QDir &dir); + + QMimeDatabase _db; + const QDir _persistentDir; + QNetworkAccessManager _manager; +}; + +#endif diff --git a/plugins/cordova-plugin-file/src/windows/FileProxy.js b/plugins/cordova-plugin-file/src/windows/FileProxy.js new file mode 100644 index 0000000..fa56a53 --- /dev/null +++ b/plugins/cordova-plugin-file/src/windows/FileProxy.js @@ -0,0 +1,1209 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ + +/* global Windows, WinJS, MSApp */ + +var File = require('./File'), + FileError = require('./FileError'), + Flags = require('./Flags'), + FileSystem = require('./FileSystem'), + LocalFileSystem = require('./LocalFileSystem'), + utils = require('cordova/utils'); + +function Entry(isFile, isDirectory, name, fullPath, filesystemName, nativeURL) { + this.isFile = !!isFile; + this.isDirectory = !!isDirectory; + this.name = name || ''; + this.fullPath = fullPath || ''; + this.filesystemName = filesystemName || null; + this.nativeURL = nativeURL || null; +} + +var FileEntry = function(name, fullPath, filesystemName, nativeURL) { + FileEntry.__super__.constructor.apply(this, [true, false, name, fullPath, filesystemName, nativeURL]); +}; + +utils.extend(FileEntry, Entry); + +var DirectoryEntry = function(name, fullPath, filesystemName, nativeURL) { + DirectoryEntry.__super__.constructor.call(this, false, true, name, fullPath, filesystemName, nativeURL); +}; + +utils.extend(DirectoryEntry, Entry); + + +var getFolderFromPathAsync = Windows.Storage.StorageFolder.getFolderFromPathAsync; +var getFileFromPathAsync = Windows.Storage.StorageFile.getFileFromPathAsync; + +function writeBytesAsync(storageFile, data, position) { + return storageFile.openAsync(Windows.Storage.FileAccessMode.readWrite) + .then(function (output) { + output.seek(position); + var dataWriter = new Windows.Storage.Streams.DataWriter(output); + dataWriter.writeBytes(data); + return dataWriter.storeAsync().then(function (size) { + output.size = position+size; + return dataWriter.flushAsync().then(function() { + output.close(); + return size; + }); + }); + }); +} + +function writeTextAsync(storageFile, data, position) { + return storageFile.openAsync(Windows.Storage.FileAccessMode.readWrite) + .then(function (output) { + output.seek(position); + var dataWriter = new Windows.Storage.Streams.DataWriter(output); + dataWriter.writeString(data); + return dataWriter.storeAsync().then(function (size) { + output.size = position+size; + return dataWriter.flushAsync().then(function() { + output.close(); + return size; + }); + }); + }); +} + +function writeBlobAsync(storageFile, data, position) { + return storageFile.openAsync(Windows.Storage.FileAccessMode.readWrite) + .then(function (output) { + output.seek(position); + var dataSize = data.size; + var input = (data.detachStream || data.msDetachStream).call(data); + + // Copy the stream from the blob to the File stream + return Windows.Storage.Streams.RandomAccessStream.copyAsync(input, output) + .then(function () { + output.size = position+dataSize; + return output.flushAsync().then(function () { + input.close(); + output.close(); + + return dataSize; + }); + }); + }); +} + +function writeArrayBufferAsync(storageFile, data, position) { + return writeBlobAsync(storageFile, new Blob([data]), position); +} + +function cordovaPathToNative(path) { + // turn / into \\ + var cleanPath = path.replace(/\//g, '\\'); + // turn \\ into \ + cleanPath = cleanPath.replace(/\\+/g, '\\'); + return cleanPath; +} + +function nativePathToCordova(path) { + var cleanPath = path.replace(/\\/g, '/'); + return cleanPath; +} + +var driveRE = new RegExp("^[/]*([A-Z]:)"); +var invalidNameRE = /[\\?*|"<>:]/; +function validName(name) { + return !invalidNameRE.test(name.replace(driveRE,'')); +} + +function sanitize(path) { + var slashesRE = new RegExp('/{2,}','g'); + var components = path.replace(slashesRE, '/').split(/\/+/); + // Remove double dots, use old school array iteration instead of RegExp + // since it is impossible to debug them + for (var index = 0; index < components.length; ++index) { + if (components[index] === "..") { + components.splice(index, 1); + if (index > 0) { + // if we're not in the start of array then remove preceeding path component, + // In case if relative path points above the root directory, just ignore double dots + // See file.spec.111 should not traverse above above the root directory for test case + components.splice(index-1, 1); + --index; + } + } + } + return components.join('/'); +} + +var WinFS = function(name, root) { + this.winpath = root.winpath; + if (this.winpath && !/\/$/.test(this.winpath)) { + this.winpath += "/"; + } + this.makeNativeURL = function (path) { + //CB-11848: This RE supposed to match all leading slashes in sanitized path. + //Removing leading slash to avoid duplicating because this.root.nativeURL already has trailing slash + var regLeadingSlashes = /^\/*/; + var sanitizedPath = sanitize(path.replace(':', '%3A')).replace(regLeadingSlashes, ''); + return FileSystem.encodeURIPath(this.root.nativeURL + sanitizedPath); + }; + root.fullPath = '/'; + if (!root.nativeURL) + root.nativeURL = 'file://'+sanitize(this.winpath + root.fullPath).replace(':','%3A'); + WinFS.__super__.constructor.call(this, name, root); +}; + +utils.extend(WinFS, FileSystem); + +WinFS.prototype.__format__ = function(fullPath) { + var path = sanitize('/'+this.name+(fullPath[0]==='/'?'':'/')+FileSystem.encodeURIPath(fullPath)); + return 'cdvfile://localhost' + path; +}; + +var windowsPaths = { + dataDirectory: "ms-appdata:///local/", + cacheDirectory: "ms-appdata:///temp/", + tempDirectory: "ms-appdata:///temp/", + syncedDataDirectory: "ms-appdata:///roaming/", + applicationDirectory: "ms-appx:///", + applicationStorageDirectory: "ms-appx:///" +}; + +var AllFileSystems; + +function getAllFS() { + if (!AllFileSystems) { + AllFileSystems = { + 'persistent': + Object.freeze(new WinFS('persistent', { + name: 'persistent', + nativeURL: 'ms-appdata:///local', + winpath: nativePathToCordova(Windows.Storage.ApplicationData.current.localFolder.path) + })), + 'temporary': + Object.freeze(new WinFS('temporary', { + name: 'temporary', + nativeURL: 'ms-appdata:///temp', + winpath: nativePathToCordova(Windows.Storage.ApplicationData.current.temporaryFolder.path) + })), + 'application': + Object.freeze(new WinFS('application', { + name: 'application', + nativeURL: 'ms-appx:///', + winpath: nativePathToCordova(Windows.ApplicationModel.Package.current.installedLocation.path) + })), + 'root': + Object.freeze(new WinFS('root', { + name: 'root', + //nativeURL: 'file:///' + winpath: '' + })) + }; + } + return AllFileSystems; +} + +function getFS(name) { + return getAllFS()[name]; +} + +FileSystem.prototype.__format__ = function(fullPath) { + return getFS(this.name).__format__(fullPath); +}; + +require('./fileSystems').getFs = function(name, callback) { + setTimeout(function(){callback(getFS(name));}); +}; + +function getFilesystemFromPath(path) { + var res; + var allfs = getAllFS(); + Object.keys(allfs).some(function(fsn) { + var fs = allfs[fsn]; + if (path.indexOf(fs.winpath) === 0) + res = fs; + return res; + }); + return res; +} + +var msapplhRE = new RegExp('^ms-appdata://localhost/'); +function pathFromURL(url) { + url=url.replace(msapplhRE,'ms-appdata:///'); + var path = decodeURIComponent(url); + // support for file name with parameters + if (/\?/g.test(path)) { + path = String(path).split("?")[0]; + } + if (path.indexOf("file:/")===0) { + if (path.indexOf("file://") !== 0) { + url = "file:///" + url.substr(6); + } + } + + ['file://','ms-appdata:///','ms-appx://','cdvfile://localhost/'].every(function(p) { + if (path.indexOf(p)!==0) + return true; + var thirdSlash = path.indexOf("/", p.length); + if (thirdSlash < 0) { + path = ""; + } else { + path = sanitize(path.substr(thirdSlash)); + } + }); + + return path.replace(driveRE,'$1'); +} + +function getFilesystemFromURL(url) { + url=url.replace(msapplhRE,'ms-appdata:///'); + var res; + if (url.indexOf("file:/")===0) + res = getFilesystemFromPath(pathFromURL(url)); + else { + var allfs = getAllFS(); + Object.keys(allfs).every(function(fsn) { + var fs = allfs[fsn]; + if (url.indexOf(fs.root.nativeURL) === 0 || + url.indexOf('cdvfile://localhost/'+fs.name+'/') === 0) + { + res = fs; + return false; + } + return true; + }); + } + return res; +} + +function getFsPathForWinPath(fs, wpath) { + var path = nativePathToCordova(wpath); + if (path.indexOf(fs.winpath) !== 0) + return null; + return path.replace(fs.winpath,'/'); +} + +var WinError = { + invalidArgument: -2147024809, + fileNotFound: -2147024894, + accessDenied: -2147024891 +}; + +function openPath(path, ops) { + ops=ops?ops:{}; + return new WinJS.Promise(function (complete,failed) { + getFileFromPathAsync(path).done( + function(file) { + complete({file:file}); + }, + function(err) { + if (err.number != WinError.fileNotFound && err.number != WinError.invalidArgument) + failed(FileError.NOT_READABLE_ERR); + getFolderFromPathAsync(path) + .done( + function(dir) { + if (!ops.getContent) + complete({folder:dir}); + else + WinJS.Promise.join({ + files:dir.getFilesAsync(), + folders:dir.getFoldersAsync() + }).done( + function(a) { + complete({ + folder:dir, + files:a.files, + folders:a.folders + }); + }, + function(err) { + failed(FileError.NOT_READABLE_ERR); + } + ); + }, + function(err) { + if (err.number == WinError.fileNotFound || err.number == WinError.invalidArgument) + complete({}); + else + failed(FileError.NOT_READABLE_ERR); + } + ); + } + ); + }); +} + +function copyFolder(src,dst,name) { + name = name?name:src.name; + return new WinJS.Promise(function (complete,failed) { + WinJS.Promise.join({ + fld:dst.createFolderAsync(name, Windows.Storage.CreationCollisionOption.openIfExists), + files:src.getFilesAsync(), + folders:src.getFoldersAsync() + }).done( + function(the) { + if (!(the.files.length || the.folders.length)) { + complete(); + return; + } + var todo = the.files.length; + var copyfolders = function() { + if (!(todo--)) { + complete(); + return; + } + copyFolder(the.folders[todo],dst) + .done(function() { copyfolders(); }, failed); + }; + var copyfiles = function() { + if (!(todo--)) { + todo = the.folders.length; + copyfolders(); + return; + } + the.files[todo].copyAsync(the.fld) + .done(function() { copyfiles(); }, failed); + }; + copyfiles(); + }, + failed + ); + }); +} + +function moveFolder(src,dst,name) { + name = name?name:src.name; + return new WinJS.Promise(function (complete,failed) { + WinJS.Promise.join({ + fld: dst.createFolderAsync(name, Windows.Storage.CreationCollisionOption.openIfExists), + files: src.getFilesAsync(), + folders: src.getFoldersAsync() + }).done( + function(the) { + if (!(the.files.length || the.folders.length)) { + complete(); + return; + } + var todo = the.files.length; + var movefolders = function() { + if (!(todo--)) { + src.deleteAsync().done(complete,failed); + return; + } + moveFolder(the.folders[todo], the.fld) + .done(movefolders,failed); + }; + var movefiles = function() { + if (!(todo--)) { + todo = the.folders.length; + movefolders(); + return; + } + the.files[todo].moveAsync(the.fld) + .done(function() { movefiles(); }, failed); + }; + movefiles(); + }, + failed + ); + }); +} + +function transport(success, fail, args, ops) { // ["fullPath","parent", "newName"] + var src = args[0]; + var parent = args[1]; + var name = args[2]; + + var srcFS = getFilesystemFromURL(src); + var dstFS = getFilesystemFromURL(parent); + var srcPath = pathFromURL(src); + var dstPath = pathFromURL(parent); + if (!(srcFS && dstFS && validName(name))){ + fail(FileError.ENCODING_ERR); + return; + } + + var srcWinPath = cordovaPathToNative(sanitize(srcFS.winpath + srcPath)); + var dstWinPath = cordovaPathToNative(sanitize(dstFS.winpath + dstPath)); + var tgtFsPath = sanitize(dstPath+'/'+name); + var tgtWinPath = cordovaPathToNative(sanitize(dstFS.winpath + dstPath+'/'+name)); + if (srcWinPath == dstWinPath || srcWinPath == tgtWinPath) { + fail(FileError.INVALID_MODIFICATION_ERR); + return; + } + + + WinJS.Promise.join({ + src:openPath(srcWinPath), + dst:openPath(dstWinPath), + tgt:openPath(tgtWinPath,{getContent:true}) + }) + .done( + function (the) { + if ((!the.dst.folder) || !(the.src.folder || the.src.file)) { + fail(FileError.NOT_FOUND_ERR); + return; + } + if ((the.src.folder && the.tgt.file) || + (the.src.file && the.tgt.folder) || + (the.tgt.folder && (the.tgt.files.length || the.tgt.folders.length))) { + fail(FileError.INVALID_MODIFICATION_ERR); + return; + } + if (the.src.file) + ops.fileOp(the.src.file,the.dst.folder, name, Windows.Storage.NameCollisionOption.replaceExisting) + .done( + function (storageFile) { + success(new FileEntry( + name, + tgtFsPath, + dstFS.name, + dstFS.makeNativeURL(tgtFsPath) + )); + }, + function (err) { + fail(FileError.INVALID_MODIFICATION_ERR); + } + ); + else + ops.folderOp(the.src.folder, the.dst.folder, name).done( + function () { + success(new DirectoryEntry( + name, + tgtFsPath, + dstFS.name, + dstFS.makeNativeURL(tgtFsPath) + )); + }, + function() { + fail(FileError.INVALID_MODIFICATION_ERR); + } + ); + }, + function(err) { + fail(FileError.INVALID_MODIFICATION_ERR); + } + ); +} + +module.exports = { + requestAllFileSystems: function() { + return getAllFS(); + }, + requestAllPaths: function(success){ + success(windowsPaths); + }, + getFileMetadata: function (success, fail, args) { + module.exports.getMetadata(success, fail, args); + }, + + getMetadata: function (success, fail, args) { + var fs = getFilesystemFromURL(args[0]); + var path = pathFromURL(args[0]); + if (!fs || !validName(path)){ + fail(FileError.ENCODING_ERR); + return; + } + var fullPath = cordovaPathToNative(fs.winpath + path); + + var getMetadataForFile = function (storageFile) { + storageFile.getBasicPropertiesAsync().then( + function (basicProperties) { + success(new File(storageFile.name, storageFile.path, storageFile.fileType, basicProperties.dateModified, basicProperties.size)); + }, function () { + fail(FileError.NOT_READABLE_ERR); + } + ); + }; + + var getMetadataForFolder = function (storageFolder) { + storageFolder.getBasicPropertiesAsync().then( + function (basicProperties) { + var metadata = { + size: basicProperties.size, + lastModifiedDate: basicProperties.dateModified + }; + success(metadata); + }, + function () { + fail(FileError.NOT_READABLE_ERR); + } + ); + }; + + getFileFromPathAsync(fullPath).then(getMetadataForFile, + function () { + getFolderFromPathAsync(fullPath).then(getMetadataForFolder, + function () { + fail(FileError.NOT_FOUND_ERR); + } + ); + } + ); + }, + + getParent: function (win, fail, args) { // ["fullPath"] + var fs = getFilesystemFromURL(args[0]); + var path = pathFromURL(args[0]); + if (!fs || !validName(path)){ + fail(FileError.ENCODING_ERR); + return; + } + if (!path || (new RegExp('/[^/]*/?$')).test(path)) { + win(new DirectoryEntry(fs.root.name, fs.root.fullPath, fs.name, fs.makeNativeURL(fs.root.fullPath))); + return; + } + + var parpath = path.replace(new RegExp('/[^/]+/?$','g'),''); + var parname = path.substr(parpath.length); + var fullPath = cordovaPathToNative(fs.winpath + parpath); + + var result = new DirectoryEntry(parname, parpath, fs.name, fs.makeNativeURL(parpath)); + getFolderFromPathAsync(fullPath).done( + function () { win(result); }, + function () { fail(FileError.INVALID_STATE_ERR); } + ); + }, + + readAsText: function (win, fail, args) { + + var url = args[0], + enc = args[1], + startPos = args[2], + endPos = args[3]; + + var fs = getFilesystemFromURL(url); + var path = pathFromURL(url); + if (!fs){ + fail(FileError.ENCODING_ERR); + return; + } + var wpath = cordovaPathToNative(sanitize(fs.winpath + path)); + + var encoding = Windows.Storage.Streams.UnicodeEncoding.utf8; + if (enc == 'Utf16LE' || enc == 'utf16LE') { + encoding = Windows.Storage.Streams.UnicodeEncoding.utf16LE; + } else if (enc == 'Utf16BE' || enc == 'utf16BE') { + encoding = Windows.Storage.Streams.UnicodeEncoding.utf16BE; + } + + getFileFromPathAsync(wpath).then(function(file) { + return file.openReadAsync(); + }).then(function (stream) { + startPos = (startPos < 0) ? Math.max(stream.size + startPos, 0) : Math.min(stream.size, startPos); + endPos = (endPos < 0) ? Math.max(endPos + stream.size, 0) : Math.min(stream.size, endPos); + stream.seek(startPos); + + var readSize = endPos - startPos, + buffer = new Windows.Storage.Streams.Buffer(readSize); + + return stream.readAsync(buffer, readSize, Windows.Storage.Streams.InputStreamOptions.none); + }).done(function(buffer) { + try { + win(Windows.Security.Cryptography.CryptographicBuffer.convertBinaryToString(encoding, buffer)); + } + catch (e) { + fail(FileError.ENCODING_ERR); + } + },function() { + fail(FileError.NOT_FOUND_ERR); + }); + }, + + readAsBinaryString:function(win,fail,args) { + var url = args[0], + startPos = args[1], + endPos = args[2]; + + var fs = getFilesystemFromURL(url); + var path = pathFromURL(url); + if (!fs){ + fail(FileError.ENCODING_ERR); + return; + } + var wpath = cordovaPathToNative(sanitize(fs.winpath + path)); + + getFileFromPathAsync(wpath).then( + function (storageFile) { + Windows.Storage.FileIO.readBufferAsync(storageFile).done( + function (buffer) { + var dataReader = Windows.Storage.Streams.DataReader.fromBuffer(buffer); + // var fileContent = dataReader.readString(buffer.length); + var byteArray = new Uint8Array(buffer.length), + byteString = ""; + dataReader.readBytes(byteArray); + dataReader.close(); + for (var i = 0; i < byteArray.length; i++) { + var charByte = byteArray[i]; + // var charRepresentation = charByte <= 127 ? String.fromCharCode(charByte) : charByte.toString(16); + var charRepresentation = String.fromCharCode(charByte); + byteString += charRepresentation; + } + win(byteString.slice(startPos, endPos)); + } + ); + }, function () { + fail(FileError.NOT_FOUND_ERR); + } + ); + }, + + readAsArrayBuffer:function(win,fail,args) { + var url = args[0]; + var fs = getFilesystemFromURL(url); + var path = pathFromURL(url); + if (!fs){ + fail(FileError.ENCODING_ERR); + return; + } + var wpath = cordovaPathToNative(sanitize(fs.winpath + path)); + + getFileFromPathAsync(wpath).then( + function (storageFile) { + var blob = MSApp.createFileFromStorageFile(storageFile); + var url = URL.createObjectURL(blob, { oneTimeOnly: true }); + var xhr = new XMLHttpRequest(); + xhr.open("GET", url, true); + xhr.responseType = 'arraybuffer'; + xhr.onload = function () { + var resultArrayBuffer = xhr.response; + // get start and end position of bytes in buffer to be returned + var startPos = args[1] || 0, + endPos = args[2] || resultArrayBuffer.length; + // if any of them is specified, we'll slice output array + if (startPos !== 0 || endPos !== resultArrayBuffer.length) { + // slice method supported only on Windows 8.1, so we need to check if it's available + // see http://msdn.microsoft.com/en-us/library/ie/dn641192(v=vs.94).aspx + if (resultArrayBuffer.slice) { + resultArrayBuffer = resultArrayBuffer.slice(startPos, endPos); + } else { + // if slice isn't available, we'll use workaround method + var tempArray = new Uint8Array(resultArrayBuffer), + resBuffer = new ArrayBuffer(endPos - startPos), + resArray = new Uint8Array(resBuffer); + + for (var i = 0; i < resArray.length; i++) { + resArray[i] = tempArray[i + startPos]; + } + resultArrayBuffer = resBuffer; + } + } + win(resultArrayBuffer); + }; + xhr.send(); + }, function () { + fail(FileError.NOT_FOUND_ERR); + } + ); + }, + + readAsDataURL: function (win, fail, args) { + var url = args[0]; + var fs = getFilesystemFromURL(url); + var path = pathFromURL(url); + if (!fs){ + fail(FileError.ENCODING_ERR); + return; + } + var wpath = cordovaPathToNative(sanitize(fs.winpath + path)); + + getFileFromPathAsync(wpath).then( + function (storageFile) { + Windows.Storage.FileIO.readBufferAsync(storageFile).done( + function (buffer) { + var strBase64 = Windows.Security.Cryptography.CryptographicBuffer.encodeToBase64String(buffer); + //the method encodeToBase64String will add "77u/" as a prefix, so we should remove it + if(String(strBase64).substr(0,4) == "77u/") { + strBase64 = strBase64.substr(4); + } + var mediaType = storageFile.contentType; + var result = "data:" + mediaType + ";base64," + strBase64; + win(result); + } + ); + }, function () { + fail(FileError.NOT_FOUND_ERR); + } + ); + }, + + getDirectory: function (win, fail, args) { + var dirurl = args[0]; + var path = args[1]; + var options = args[2]; + + var fs = getFilesystemFromURL(dirurl); + var dirpath = pathFromURL(dirurl); + if (!fs || !validName(path)){ + fail(FileError.ENCODING_ERR); + return; + } + var fspath = sanitize(dirpath +'/'+ path); + var completePath = sanitize(fs.winpath + fspath); + + var name = completePath.substring(completePath.lastIndexOf('/')+1); + + var wpath = cordovaPathToNative(completePath.substring(0, completePath.lastIndexOf('/'))); + + var flag = ""; + if (options) { + flag = new Flags(options.create, options.exclusive); + } else { + flag = new Flags(false, false); + } + + getFolderFromPathAsync(wpath).done( + function (storageFolder) { + if (flag.create === true && flag.exclusive === true) { + storageFolder.createFolderAsync(name, Windows.Storage.CreationCollisionOption.failIfExists).done( + function (storageFolder) { + win(new DirectoryEntry(storageFolder.name, fspath, fs.name, fs.makeNativeURL(fspath))); + }, function (err) { + fail(FileError.PATH_EXISTS_ERR); + } + ); + } else if (flag.create === true && flag.exclusive === false) { + storageFolder.createFolderAsync(name, Windows.Storage.CreationCollisionOption.openIfExists).done( + function (storageFolder) { + win(new DirectoryEntry(storageFolder.name, fspath, fs.name, fs.makeNativeURL(fspath))); + }, function () { + fail(FileError.INVALID_MODIFICATION_ERR); + } + ); + } else if (flag.create === false) { + storageFolder.getFolderAsync(name).done( + function (storageFolder) { + win(new DirectoryEntry(storageFolder.name, fspath, fs.name, fs.makeNativeURL(fspath))); + }, + function () { + // check if path actually points to a file + storageFolder.getFileAsync(name).done( + function () { + fail(FileError.TYPE_MISMATCH_ERR); + }, function() { + fail(FileError.NOT_FOUND_ERR); + } + ); + } + ); + } + }, function () { + fail(FileError.NOT_FOUND_ERR); + } + ); + }, + + remove: function (win, fail, args) { + var fs = getFilesystemFromURL(args[0]); + var path = pathFromURL(args[0]); + if (!fs || !validName(path)){ + fail(FileError.ENCODING_ERR); + return; + } + + // FileSystem root can't be removed! + if (!path || path=='/'){ + fail(FileError.NO_MODIFICATION_ALLOWED_ERR); + return; + } + var fullPath = cordovaPathToNative(fs.winpath + path); + + getFileFromPathAsync(fullPath).then( + function (storageFile) { + storageFile.deleteAsync().done(win, function () { + fail(FileError.INVALID_MODIFICATION_ERR); + }); + }, + function () { + getFolderFromPathAsync(fullPath).done( + function (sFolder) { + sFolder.getFilesAsync() + // check for files + .then(function(fileList) { + if (fileList) { + if (fileList.length === 0) { + return sFolder.getFoldersAsync(); + } else { + fail(FileError.INVALID_MODIFICATION_ERR); + } + } + }) + // check for folders + .done(function (folderList) { + if (folderList) { + if (folderList.length === 0) { + sFolder.deleteAsync().done( + win, + function () { + fail(FileError.INVALID_MODIFICATION_ERR); + } + ); + } else { + fail(FileError.INVALID_MODIFICATION_ERR); + } + } + }); + }, + function () { + fail(FileError.NOT_FOUND_ERR); + } + ); + } + ); + }, + + removeRecursively: function (successCallback, fail, args) { + + var fs = getFilesystemFromURL(args[0]); + var path = pathFromURL(args[0]); + if (!fs || !validName(path)){ + fail(FileError.ENCODING_ERR); + return; + } + + // FileSystem root can't be removed! + if (!path || path=='/'){ + fail(FileError.NO_MODIFICATION_ALLOWED_ERR); + return; + } + var fullPath = cordovaPathToNative(fs.winpath + path); + + getFolderFromPathAsync(fullPath).done(function (storageFolder) { + storageFolder.deleteAsync().done(function (res) { + successCallback(res); + }, function (err) { + fail(err); + }); + + }, function () { + fail(FileError.FILE_NOT_FOUND_ERR); + }); + }, + + getFile: function (win, fail, args) { + + var dirurl = args[0]; + var path = args[1]; + var options = args[2]; + + var fs = getFilesystemFromURL(dirurl); + var dirpath = pathFromURL(dirurl); + if (!fs || !validName(path)){ + fail(FileError.ENCODING_ERR); + return; + } + var fspath = sanitize(dirpath +'/'+ path); + var completePath = sanitize(fs.winpath + fspath); + + var fileName = completePath.substring(completePath.lastIndexOf('/')+1); + + var wpath = cordovaPathToNative(completePath.substring(0, completePath.lastIndexOf('/'))); + + var flag = ""; + if (options !== null) { + flag = new Flags(options.create, options.exclusive); + } else { + flag = new Flags(false, false); + } + + getFolderFromPathAsync(wpath).done( + function (storageFolder) { + if (flag.create === true && flag.exclusive === true) { + storageFolder.createFileAsync(fileName, Windows.Storage.CreationCollisionOption.failIfExists).done( + function (storageFile) { + win(new FileEntry(storageFile.name, fspath, fs.name, fs.makeNativeURL(fspath))); + }, function () { + fail(FileError.PATH_EXISTS_ERR); + } + ); + } else if (flag.create === true && flag.exclusive === false) { + storageFolder.createFileAsync(fileName, Windows.Storage.CreationCollisionOption.openIfExists).done( + function (storageFile) { + win(new FileEntry(storageFile.name, fspath, fs.name, fs.makeNativeURL(fspath))); + }, function () { + fail(FileError.INVALID_MODIFICATION_ERR); + } + ); + } else if (flag.create === false) { + storageFolder.getFileAsync(fileName).done( + function (storageFile) { + win(new FileEntry(storageFile.name, fspath, fs.name, fs.makeNativeURL(fspath))); + }, function () { + // check if path actually points to a folder + storageFolder.getFolderAsync(fileName).done( + function () { + fail(FileError.TYPE_MISMATCH_ERR); + }, function () { + fail(FileError.NOT_FOUND_ERR); + }); + } + ); + } + }, function (err) { + fail( + err.number == WinError.accessDenied? + FileError.SECURITY_ERR: + FileError.NOT_FOUND_ERR + ); + } + ); + }, + + readEntries: function (win, fail, args) { // ["fullPath"] + var fs = getFilesystemFromURL(args[0]); + var path = pathFromURL(args[0]); + if (!fs || !validName(path)){ + fail(FileError.ENCODING_ERR); + return; + } + var fullPath = cordovaPathToNative(fs.winpath + path); + + var result = []; + + getFolderFromPathAsync(fullPath).done(function (storageFolder) { + var promiseArr = []; + var index = 0; + promiseArr[index++] = storageFolder.getFilesAsync().then(function (fileList) { + if (fileList !== null) { + for (var i = 0; i < fileList.length; i++) { + var fspath = getFsPathForWinPath(fs, fileList[i].path); + if (!fspath) { + fail(FileError.NOT_FOUND_ERR); + return; + } + result.push(new FileEntry(fileList[i].name, fspath, fs.name, fs.makeNativeURL(fspath))); + } + } + }); + promiseArr[index++] = storageFolder.getFoldersAsync().then(function (folderList) { + if (folderList !== null) { + for (var j = 0; j < folderList.length; j++) { + var fspath = getFsPathForWinPath(fs, folderList[j].path); + if (!fspath) { + fail(FileError.NOT_FOUND_ERR); + return; + } + result.push(new DirectoryEntry(folderList[j].name, fspath, fs.name, fs.makeNativeURL(fspath))); + } + } + }); + WinJS.Promise.join(promiseArr).then(function () { + win(result); + }); + + }, function () { fail(FileError.NOT_FOUND_ERR); }); + }, + + write: function (win, fail, args) { + + var url = args[0], + data = args[1], + position = args[2], + isBinary = args[3]; + + var fs = getFilesystemFromURL(url); + var path = pathFromURL(url); + if (!fs){ + fail(FileError.ENCODING_ERR); + return; + } + var completePath = sanitize(fs.winpath + path); + var fileName = completePath.substring(completePath.lastIndexOf('/')+1); + var dirpath = completePath.substring(0,completePath.lastIndexOf('/')); + var wpath = cordovaPathToNative(dirpath); + + function getWriteMethodForData(data, isBinary) { + + if (data instanceof Blob) { + return writeBlobAsync; + } + + if (data instanceof ArrayBuffer) { + return writeArrayBufferAsync; + } + + if (isBinary) { + return writeBytesAsync; + } + + if (typeof data === 'string') { + return writeTextAsync; + } + + throw new Error('Unsupported data type for write method'); + } + + var writePromise = getWriteMethodForData(data, isBinary); + + getFolderFromPathAsync(wpath).done( + function (storageFolder) { + storageFolder.createFileAsync(fileName, Windows.Storage.CreationCollisionOption.openIfExists).done( + function (storageFile) { + writePromise(storageFile, data, position).done( + function (bytesWritten) { + var written = bytesWritten || data.length; + win(written); + }, + function () { + fail(FileError.INVALID_MODIFICATION_ERR); + } + ); + }, + function () { + fail(FileError.INVALID_MODIFICATION_ERR); + } + ); + + }, + function () { + fail(FileError.NOT_FOUND_ERR); + } + ); + }, + + truncate: function (win, fail, args) { // ["fileName","size"] + var url = args[0]; + var size = args[1]; + + var fs = getFilesystemFromURL(url); + var path = pathFromURL(url); + if (!fs){ + fail(FileError.ENCODING_ERR); + return; + } + var completePath = sanitize(fs.winpath + path); + var wpath = cordovaPathToNative(completePath); + var dirwpath = cordovaPathToNative(completePath.substring(0,completePath.lastIndexOf('/'))); + + getFileFromPathAsync(wpath).done(function(storageFile){ + //the current length of the file. + var leng = 0; + + storageFile.getBasicPropertiesAsync().then(function (basicProperties) { + leng = basicProperties.size; + if (Number(size) >= leng) { + win(this.length); + return; + } + if (Number(size) >= 0) { + Windows.Storage.FileIO.readTextAsync(storageFile, Windows.Storage.Streams.UnicodeEncoding.utf8).then(function (fileContent) { + fileContent = fileContent.substr(0, size); + var name = storageFile.name; + storageFile.deleteAsync().then(function () { + return getFolderFromPathAsync(dirwpath); + }).done(function (storageFolder) { + storageFolder.createFileAsync(name).then(function (newStorageFile) { + Windows.Storage.FileIO.writeTextAsync(newStorageFile, fileContent).done(function () { + win(String(fileContent).length); + }, function () { + fail(FileError.NO_MODIFICATION_ALLOWED_ERR); + }); + }, function() { + fail(FileError.NO_MODIFICATION_ALLOWED_ERR); + }); + }); + }, function () { fail(FileError.NOT_FOUND_ERR); }); + } + }); + }, function () { fail(FileError.NOT_FOUND_ERR); }); + }, + + copyTo: function (success, fail, args) { // ["fullPath","parent", "newName"] + transport(success, fail, args, + { + fileOp:function(file,folder,name,coll) { + return file.copyAsync(folder,name,coll); + }, + folderOp:function(src,dst,name) { + return copyFolder(src,dst,name); + }} + ); + }, + + moveTo: function (success, fail, args) { + transport(success, fail, args, + { + fileOp:function(file,folder,name,coll) { + return file.moveAsync(folder,name,coll); + }, + folderOp:function(src,dst,name) { + return moveFolder(src,dst,name); + }} + ); + }, + tempFileSystem:null, + + persistentFileSystem:null, + + requestFileSystem: function (win, fail, args) { + + var type = args[0]; + var size = args[1]; + var MAX_SIZE = 10000000000; + if (size > MAX_SIZE) { + fail(FileError.QUOTA_EXCEEDED_ERR); + return; + } + + var fs; + switch (type) { + case LocalFileSystem.TEMPORARY: + fs = getFS('temporary'); + break; + case LocalFileSystem.PERSISTENT: + fs = getFS('persistent'); + break; + } + if (fs) + win(fs); + else + fail(FileError.NOT_FOUND_ERR); + }, + + resolveLocalFileSystemURI: function (success, fail, args) { + + var uri = args[0]; + + var path = pathFromURL(uri); + var fs = getFilesystemFromURL(uri); + if (!fs || !validName(path)) { + fail(FileError.ENCODING_ERR); + return; + } + if (path.indexOf(fs.winpath) === 0) + path=path.substr(fs.winpath.length); + var abspath = cordovaPathToNative(fs.winpath+path); + + getFileFromPathAsync(abspath).done( + function (storageFile) { + success(new FileEntry(storageFile.name, path, fs.name, fs.makeNativeURL(path))); + }, function () { + getFolderFromPathAsync(abspath).done( + function (storageFolder) { + success(new DirectoryEntry(storageFolder.name, path, fs.name,fs.makeNativeURL(path))); + }, function () { + fail(FileError.NOT_FOUND_ERR); + } + ); + } + ); + } + + +}; + +require("cordova/exec/proxy").add("File",module.exports); diff --git a/plugins/cordova-plugin-file/src/wp/File.cs b/plugins/cordova-plugin-file/src/wp/File.cs new file mode 100644 index 0000000..941c9c8 --- /dev/null +++ b/plugins/cordova-plugin-file/src/wp/File.cs @@ -0,0 +1,1800 @@ +/* + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.IO.IsolatedStorage; +using System.Runtime.Serialization; +using System.Security; +using System.Text; +using System.Windows; +using System.Windows.Resources; +using WPCordovaClassLib.Cordova.JSON; + +namespace WPCordovaClassLib.Cordova.Commands +{ + /// + /// Provides access to isolated storage + /// + public class File : BaseCommand + { + // Error codes + public const int NOT_FOUND_ERR = 1; + public const int SECURITY_ERR = 2; + public const int ABORT_ERR = 3; + public const int NOT_READABLE_ERR = 4; + public const int ENCODING_ERR = 5; + public const int NO_MODIFICATION_ALLOWED_ERR = 6; + public const int INVALID_STATE_ERR = 7; + public const int SYNTAX_ERR = 8; + public const int INVALID_MODIFICATION_ERR = 9; + public const int QUOTA_EXCEEDED_ERR = 10; + public const int TYPE_MISMATCH_ERR = 11; + public const int PATH_EXISTS_ERR = 12; + + // File system options + public const int TEMPORARY = 0; + public const int PERSISTENT = 1; + public const int RESOURCE = 2; + public const int APPLICATION = 3; + + /// + /// Temporary directory name + /// + private readonly string TMP_DIRECTORY_NAME = "tmp"; + + /// + /// Represents error code for callback + /// + [DataContract] + public class ErrorCode + { + /// + /// Error code + /// + [DataMember(IsRequired = true, Name = "code")] + public int Code { get; set; } + + /// + /// Creates ErrorCode object + /// + public ErrorCode(int code) + { + this.Code = code; + } + } + + /// + /// Represents File action options. + /// + [DataContract] + public class FileOptions + { + /// + /// File path + /// + /// + private string _fileName; + [DataMember(Name = "fileName")] + public string FilePath + { + get + { + return this._fileName; + } + + set + { + int index = value.IndexOfAny(new char[] { '#', '?' }); + this._fileName = index > -1 ? value.Substring(0, index) : value; + } + } + + /// + /// Full entryPath + /// + [DataMember(Name = "fullPath")] + public string FullPath { get; set; } + + /// + /// Directory name + /// + [DataMember(Name = "dirName")] + public string DirectoryName { get; set; } + + /// + /// Path to create file/directory + /// + [DataMember(Name = "path")] + public string Path { get; set; } + + /// + /// The encoding to use to encode the file's content. Default is UTF8. + /// + [DataMember(Name = "encoding")] + public string Encoding { get; set; } + + /// + /// Uri to get file + /// + /// + private string _uri; + [DataMember(Name = "uri")] + public string Uri + { + get + { + return this._uri; + } + + set + { + int index = value.IndexOfAny(new char[] { '#', '?' }); + this._uri = index > -1 ? value.Substring(0, index) : value; + } + } + + /// + /// Size to truncate file + /// + [DataMember(Name = "size")] + public long Size { get; set; } + + /// + /// Data to write in file + /// + [DataMember(Name = "data")] + public string Data { get; set; } + + /// + /// Position the writing starts with + /// + [DataMember(Name = "position")] + public int Position { get; set; } + + /// + /// Type of file system requested + /// + [DataMember(Name = "type")] + public int FileSystemType { get; set; } + + /// + /// New file/directory name + /// + [DataMember(Name = "newName")] + public string NewName { get; set; } + + /// + /// Destination directory to copy/move file/directory + /// + [DataMember(Name = "parent")] + public string Parent { get; set; } + + /// + /// Options for getFile/getDirectory methods + /// + [DataMember(Name = "options")] + public CreatingOptions CreatingOpt { get; set; } + + /// + /// Creates options object with default parameters + /// + public FileOptions() + { + this.SetDefaultValues(new StreamingContext()); + } + + /// + /// Initializes default values for class fields. + /// Implemented in separate method because default constructor is not invoked during deserialization. + /// + /// + [OnDeserializing()] + public void SetDefaultValues(StreamingContext context) + { + this.Encoding = "UTF-8"; + this.FilePath = ""; + this.FileSystemType = -1; + } + } + + /// + /// Stores image info + /// + [DataContract] + public class FileMetadata + { + [DataMember(Name = "fileName")] + public string FileName { get; set; } + + [DataMember(Name = "fullPath")] + public string FullPath { get; set; } + + [DataMember(Name = "type")] + public string Type { get; set; } + + [DataMember(Name = "lastModifiedDate")] + public string LastModifiedDate { get; set; } + + [DataMember(Name = "size")] + public long Size { get; set; } + + public FileMetadata(string filePath) + { + if (string.IsNullOrEmpty(filePath)) + { + throw new FileNotFoundException("File doesn't exist"); + } + + this.FullPath = filePath; + this.Size = 0; + this.FileName = string.Empty; + + using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) + { + bool IsFile = isoFile.FileExists(filePath); + bool IsDirectory = isoFile.DirectoryExists(filePath); + + if (!IsDirectory) + { + if (!IsFile) // special case, if isoFile cannot find it, it might still be part of the app-package + { + // attempt to get it from the resources + + Uri fileUri = new Uri(filePath, UriKind.Relative); + StreamResourceInfo streamInfo = Application.GetResourceStream(fileUri); + if (streamInfo != null) + { + this.Size = streamInfo.Stream.Length; + this.FileName = filePath.Substring(filePath.LastIndexOf("/") + 1); + } + else + { + throw new FileNotFoundException("File doesn't exist"); + } + } + else + { + using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(filePath, FileMode.Open, FileAccess.Read, isoFile)) + { + this.Size = stream.Length; + } + + this.FileName = System.IO.Path.GetFileName(filePath); + this.LastModifiedDate = isoFile.GetLastWriteTime(filePath).DateTime.ToString(); + } + } + + this.Type = MimeTypeMapper.GetMimeType(this.FileName); + } + } + } + + /// + /// Represents file or directory modification metadata + /// + [DataContract] + public class ModificationMetadata + { + /// + /// Modification time + /// + [DataMember] + public string modificationTime { get; set; } + } + + /// + /// Represents file or directory entry + /// + [DataContract] + public class FileEntry + { + + /// + /// File type + /// + [DataMember(Name = "isFile")] + public bool IsFile { get; set; } + + /// + /// Directory type + /// + [DataMember(Name = "isDirectory")] + public bool IsDirectory { get; set; } + + /// + /// File/directory name + /// + [DataMember(Name = "name")] + public string Name { get; set; } + + /// + /// Full path to file/directory + /// + [DataMember(Name = "fullPath")] + public string FullPath { get; set; } + + /// + /// URI encoded fullpath + /// + [DataMember(Name = "nativeURL")] + public string NativeURL + { + set { } + get + { + string escaped = Uri.EscapeUriString(this.FullPath); + escaped = escaped.Replace("//", "/"); + if (escaped.StartsWith("/")) + { + escaped = escaped.Insert(0, "/"); + } + return escaped; + } + } + + public bool IsResource { get; set; } + + public static FileEntry GetEntry(string filePath, bool bIsRes=false) + { + FileEntry entry = null; + try + { + entry = new FileEntry(filePath, bIsRes); + + } + catch (Exception ex) + { + Debug.WriteLine("Exception in GetEntry for filePath :: " + filePath + " " + ex.Message); + } + return entry; + } + + /// + /// Creates object and sets necessary properties + /// + /// + public FileEntry(string filePath, bool bIsRes = false) + { + if (string.IsNullOrEmpty(filePath)) + { + throw new ArgumentException(); + } + + if(filePath.Contains(" ")) + { + Debug.WriteLine("FilePath with spaces :: " + filePath); + } + + using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) + { + IsResource = bIsRes; + IsFile = isoFile.FileExists(filePath); + IsDirectory = isoFile.DirectoryExists(filePath); + if (IsFile) + { + this.Name = Path.GetFileName(filePath); + } + else if (IsDirectory) + { + this.Name = this.GetDirectoryName(filePath); + if (string.IsNullOrEmpty(Name)) + { + this.Name = "/"; + } + } + else + { + if (IsResource) + { + this.Name = Path.GetFileName(filePath); + } + else + { + throw new FileNotFoundException(); + } + } + + try + { + this.FullPath = filePath.Replace('\\', '/'); // new Uri(filePath).LocalPath; + } + catch (Exception) + { + this.FullPath = filePath; + } + } + } + + /// + /// Extracts directory name from path string + /// Path should refer to a directory, for example \foo\ or /foo. + /// + /// + /// + private string GetDirectoryName(string path) + { + if (String.IsNullOrEmpty(path)) + { + return path; + } + + string[] split = path.Split(new char[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries); + if (split.Length < 1) + { + return null; + } + else + { + return split[split.Length - 1]; + } + } + } + + + /// + /// Represents info about requested file system + /// + [DataContract] + public class FileSystemInfo + { + /// + /// file system type + /// + [DataMember(Name = "name", IsRequired = true)] + public string Name { get; set; } + + /// + /// Root directory entry + /// + [DataMember(Name = "root", EmitDefaultValue = false)] + public FileEntry Root { get; set; } + + /// + /// Creates class instance + /// + /// + /// Root directory + public FileSystemInfo(string name, FileEntry rootEntry = null) + { + Name = name; + Root = rootEntry; + } + } + + [DataContract] + public class CreatingOptions + { + /// + /// Create file/directory if is doesn't exist + /// + [DataMember(Name = "create")] + public bool Create { get; set; } + + /// + /// Generate an exception if create=true and file/directory already exists + /// + [DataMember(Name = "exclusive")] + public bool Exclusive { get; set; } + + + } + + // returns null value if it fails. + private string[] getOptionStrings(string options) + { + string[] optStings = null; + try + { + optStings = JSON.JsonHelper.Deserialize(options); + } + catch (Exception) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION), CurrentCommandCallbackId); + } + return optStings; + } + + /// + /// Gets amount of free space available for Isolated Storage + /// + /// No options is needed for this method + public void getFreeDiskSpace(string options) + { + string callbackId = getOptionStrings(options)[0]; + + try + { + using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.OK, isoFile.AvailableFreeSpace), callbackId); + } + } + catch (IsolatedStorageException) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId); + } + catch (Exception ex) + { + if (!this.HandleException(ex)) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId); + } + } + } + + /// + /// Check if file exists + /// + /// File path + public void testFileExists(string options) + { + IsDirectoryOrFileExist(options, false); + } + + /// + /// Check if directory exists + /// + /// directory name + public void testDirectoryExists(string options) + { + IsDirectoryOrFileExist(options, true); + } + + /// + /// Check if file or directory exist + /// + /// File path/Directory name + /// Flag to recognize what we should check + public void IsDirectoryOrFileExist(string options, bool isDirectory) + { + string[] args = getOptionStrings(options); + string callbackId = args[1]; + FileOptions fileOptions = JSON.JsonHelper.Deserialize(args[0]); + string filePath = args[0]; + + if (fileOptions == null) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION), callbackId); + } + + try + { + using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) + { + bool isExist; + if (isDirectory) + { + isExist = isoFile.DirectoryExists(fileOptions.DirectoryName); + } + else + { + isExist = isoFile.FileExists(fileOptions.FilePath); + } + DispatchCommandResult(new PluginResult(PluginResult.Status.OK, isExist), callbackId); + } + } + catch (IsolatedStorageException) // default handler throws INVALID_MODIFICATION_ERR + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId); + } + catch (Exception ex) + { + if (!this.HandleException(ex)) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); + } + } + + } + + public void readAsDataURL(string options) + { + string[] optStrings = getOptionStrings(options); + string filePath = optStrings[0]; + int startPos = int.Parse(optStrings[1]); + int endPos = int.Parse(optStrings[2]); + string callbackId = optStrings[3]; + + if (filePath != null) + { + try + { + string base64URL = null; + + using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) + { + if (!isoFile.FileExists(filePath)) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); + return; + } + string mimeType = MimeTypeMapper.GetMimeType(filePath); + + using (IsolatedStorageFileStream stream = isoFile.OpenFile(filePath, FileMode.Open, FileAccess.Read)) + { + string base64String = GetFileContent(stream); + base64URL = "data:" + mimeType + ";base64," + base64String; + } + } + + DispatchCommandResult(new PluginResult(PluginResult.Status.OK, base64URL), callbackId); + } + catch (Exception ex) + { + if (!this.HandleException(ex)) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId); + } + } + } + } + + private byte[] readFileBytes(string filePath,int startPos,int endPos, IsolatedStorageFile isoFile) + { + byte[] buffer; + using (IsolatedStorageFileStream reader = isoFile.OpenFile(filePath, FileMode.Open, FileAccess.Read)) + { + if (startPos < 0) + { + startPos = Math.Max((int)reader.Length + startPos, 0); + } + else if (startPos > 0) + { + startPos = Math.Min((int)reader.Length, startPos); + } + if (endPos > 0) + { + endPos = Math.Min((int)reader.Length, endPos); + } + else if (endPos < 0) + { + endPos = Math.Max(endPos + (int)reader.Length, 0); + } + + buffer = new byte[endPos - startPos]; + reader.Seek(startPos, SeekOrigin.Begin); + reader.Read(buffer, 0, buffer.Length); + } + + return buffer; + } + + public void readAsArrayBuffer(string options) + { + string[] optStrings = getOptionStrings(options); + string filePath = optStrings[0]; + int startPos = int.Parse(optStrings[1]); + int endPos = int.Parse(optStrings[2]); + string callbackId = optStrings[3]; + + try + { + byte[] buffer; + + using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) + { + if (!isoFile.FileExists(filePath)) + { + readResourceAsText(options); + return; + } + buffer = readFileBytes(filePath, startPos, endPos, isoFile); + } + + DispatchCommandResult(new PluginResult(PluginResult.Status.OK, buffer), callbackId); + } + catch (Exception ex) + { + if (!this.HandleException(ex, callbackId)) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId); + } + } + } + + public void readAsBinaryString(string options) + { + string[] optStrings = getOptionStrings(options); + string filePath = optStrings[0]; + int startPos = int.Parse(optStrings[1]); + int endPos = int.Parse(optStrings[2]); + string callbackId = optStrings[3]; + + try + { + string result; + + using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) + { + if (!isoFile.FileExists(filePath)) + { + readResourceAsText(options); + return; + } + + byte[] buffer = readFileBytes(filePath, startPos, endPos, isoFile); + result = System.Text.Encoding.GetEncoding("iso-8859-1").GetString(buffer, 0, buffer.Length); + + } + + DispatchCommandResult(new PluginResult(PluginResult.Status.OK, result), callbackId); + } + catch (Exception ex) + { + if (!this.HandleException(ex, callbackId)) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId); + } + } + } + + public void readAsText(string options) + { + string[] optStrings = getOptionStrings(options); + string filePath = optStrings[0]; + string encStr = optStrings[1]; + int startPos = int.Parse(optStrings[2]); + int endPos = int.Parse(optStrings[3]); + string callbackId = optStrings[4]; + + try + { + string text = ""; + + using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) + { + if (!isoFile.FileExists(filePath)) + { + readResourceAsText(options); + return; + } + Encoding encoding = Encoding.GetEncoding(encStr); + + byte[] buffer = this.readFileBytes(filePath, startPos, endPos, isoFile); + text = encoding.GetString(buffer, 0, buffer.Length); + } + + // JIRA: https://issues.apache.org/jira/browse/CB-8792 + // Need to perform additional serialization here because NativeExecution is always trying + // to do JSON.parse() on command result. This leads to issue when trying to read JSON files + var resultText = JsonHelper.Serialize(text); + DispatchCommandResult(new PluginResult(PluginResult.Status.OK, resultText), callbackId); + } + catch (Exception ex) + { + if (!this.HandleException(ex, callbackId)) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId); + } + } + } + + /// + /// Reads application resource as a text + /// + /// Path to a resource + public void readResourceAsText(string options) + { + string[] optStrings = getOptionStrings(options); + string pathToResource = optStrings[0]; + string encStr = optStrings[1]; + int start = int.Parse(optStrings[2]); + int endMarker = int.Parse(optStrings[3]); + string callbackId = optStrings[4]; + + try + { + if (pathToResource.StartsWith("/")) + { + pathToResource = pathToResource.Remove(0, 1); + } + + var resource = Application.GetResourceStream(new Uri(pathToResource, UriKind.Relative)); + + if (resource == null) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); + return; + } + + string text; + StreamReader streamReader = new StreamReader(resource.Stream); + text = streamReader.ReadToEnd(); + + DispatchCommandResult(new PluginResult(PluginResult.Status.OK, text), callbackId); + } + catch (Exception ex) + { + if (!this.HandleException(ex, callbackId)) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId); + } + } + } + + public void truncate(string options) + { + string[] optStrings = getOptionStrings(options); + + string filePath = optStrings[0]; + int size = int.Parse(optStrings[1]); + string callbackId = optStrings[2]; + + try + { + long streamLength = 0; + + using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) + { + if (!isoFile.FileExists(filePath)) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); + return; + } + + using (FileStream stream = new IsolatedStorageFileStream(filePath, FileMode.Open, FileAccess.ReadWrite, isoFile)) + { + if (0 <= size && size <= stream.Length) + { + stream.SetLength(size); + } + streamLength = stream.Length; + } + } + + DispatchCommandResult(new PluginResult(PluginResult.Status.OK, streamLength), callbackId); + } + catch (Exception ex) + { + if (!this.HandleException(ex, callbackId)) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId); + } + } + } + + //write:[filePath,data,position,isBinary,callbackId] + public void write(string options) + { + string[] optStrings = getOptionStrings(options); + + string filePath = optStrings[0]; + string data = optStrings[1]; + int position = int.Parse(optStrings[2]); + bool isBinary = bool.Parse(optStrings[3]); + string callbackId = optStrings[4]; + + try + { + if (string.IsNullOrEmpty(data)) + { + Debug.WriteLine("Expected some data to be send in the write command to {0}", filePath); + DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION), callbackId); + return; + } + + byte[] dataToWrite = isBinary ? JSON.JsonHelper.Deserialize(data) : + System.Text.Encoding.UTF8.GetBytes(data); + + using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) + { + // create the file if not exists + if (!isoFile.FileExists(filePath)) + { + var file = isoFile.CreateFile(filePath); + file.Close(); + } + + using (FileStream stream = new IsolatedStorageFileStream(filePath, FileMode.Open, FileAccess.ReadWrite, isoFile)) + { + if (0 <= position && position <= stream.Length) + { + stream.SetLength(position); + } + using (BinaryWriter writer = new BinaryWriter(stream)) + { + writer.Seek(0, SeekOrigin.End); + writer.Write(dataToWrite); + } + } + } + + DispatchCommandResult(new PluginResult(PluginResult.Status.OK, dataToWrite.Length), callbackId); + } + catch (Exception ex) + { + if (!this.HandleException(ex, callbackId)) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId); + } + } + } + + /// + /// Look up metadata about this entry. + /// + /// filePath to entry + public void getMetadata(string options) + { + string[] optStings = getOptionStrings(options); + string filePath = optStings[0]; + string callbackId = optStings[1]; + + if (filePath != null) + { + try + { + using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) + { + if (isoFile.FileExists(filePath)) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.OK, + new ModificationMetadata() { modificationTime = isoFile.GetLastWriteTime(filePath).DateTime.ToString() }), callbackId); + } + else if (isoFile.DirectoryExists(filePath)) + { + string modTime = isoFile.GetLastWriteTime(filePath).DateTime.ToString(); + DispatchCommandResult(new PluginResult(PluginResult.Status.OK, new ModificationMetadata() { modificationTime = modTime }), callbackId); + } + else + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); + } + + } + } + catch (IsolatedStorageException) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId); + } + catch (Exception ex) + { + if (!this.HandleException(ex)) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId); + } + } + } + + } + + + /// + /// Returns a File that represents the current state of the file that this FileEntry represents. + /// + /// filePath to entry + /// + public void getFileMetadata(string options) + { + string[] optStings = getOptionStrings(options); + string filePath = optStings[0]; + string callbackId = optStings[1]; + + if (!string.IsNullOrEmpty(filePath)) + { + try + { + FileMetadata metaData = new FileMetadata(filePath); + DispatchCommandResult(new PluginResult(PluginResult.Status.OK, metaData), callbackId); + } + catch (IsolatedStorageException) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId); + } + catch (Exception ex) + { + if (!this.HandleException(ex)) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId); + } + } + } + else + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); + } + } + + /// + /// Look up the parent DirectoryEntry containing this Entry. + /// If this Entry is the root of IsolatedStorage, its parent is itself. + /// + /// + public void getParent(string options) + { + string[] optStings = getOptionStrings(options); + string filePath = optStings[0]; + string callbackId = optStings[1]; + + if (filePath != null) + { + try + { + if (string.IsNullOrEmpty(filePath)) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION),callbackId); + return; + } + + using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) + { + FileEntry entry; + + if (isoFile.FileExists(filePath) || isoFile.DirectoryExists(filePath)) + { + + + string path = this.GetParentDirectory(filePath); + entry = FileEntry.GetEntry(path); + DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entry),callbackId); + } + else + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR),callbackId); + } + + } + } + catch (Exception ex) + { + if (!this.HandleException(ex)) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR),callbackId); + } + } + } + } + + public void remove(string options) + { + string[] args = getOptionStrings(options); + string filePath = args[0]; + string callbackId = args[1]; + + if (filePath != null) + { + try + { + if (filePath == "/" || filePath == "" || filePath == @"\") + { + throw new Exception("Cannot delete root file system") ; + } + using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) + { + if (isoFile.FileExists(filePath)) + { + isoFile.DeleteFile(filePath); + } + else + { + if (isoFile.DirectoryExists(filePath)) + { + isoFile.DeleteDirectory(filePath); + } + else + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR),callbackId); + return; + } + } + DispatchCommandResult(new PluginResult(PluginResult.Status.OK),callbackId); + } + } + catch (Exception ex) + { + if (!this.HandleException(ex)) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR),callbackId); + } + } + } + } + + public void removeRecursively(string options) + { + string[] args = getOptionStrings(options); + string filePath = args[0]; + string callbackId = args[1]; + + if (filePath != null) + { + if (string.IsNullOrEmpty(filePath)) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION),callbackId); + } + else + { + if (removeDirRecursively(filePath, callbackId)) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.OK), callbackId); + } + } + } + } + + public void readEntries(string options) + { + string[] args = getOptionStrings(options); + string filePath = args[0]; + string callbackId = args[1]; + + if (filePath != null) + { + try + { + if (string.IsNullOrEmpty(filePath)) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION),callbackId); + return; + } + + using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) + { + if (isoFile.DirectoryExists(filePath)) + { + string path = File.AddSlashToDirectory(filePath); + List entries = new List(); + string[] files = isoFile.GetFileNames(path + "*"); + string[] dirs = isoFile.GetDirectoryNames(path + "*"); + foreach (string file in files) + { + entries.Add(FileEntry.GetEntry(path + file)); + } + foreach (string dir in dirs) + { + entries.Add(FileEntry.GetEntry(path + dir + "/")); + } + DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entries),callbackId); + } + else + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR),callbackId); + } + } + } + catch (Exception ex) + { + if (!this.HandleException(ex)) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR),callbackId); + } + } + } + } + + public void requestFileSystem(string options) + { + // TODO: try/catch + string[] optVals = getOptionStrings(options); + //FileOptions fileOptions = new FileOptions(); + int fileSystemType = int.Parse(optVals[0]); + double size = double.Parse(optVals[1]); + string callbackId = optVals[2]; + + + IsolatedStorageFile.GetUserStoreForApplication(); + + if (size > (10 * 1024 * 1024)) // 10 MB, compier will clean this up! + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, QUOTA_EXCEEDED_ERR), callbackId); + return; + } + + try + { + if (size != 0) + { + using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) + { + long availableSize = isoFile.AvailableFreeSpace; + if (size > availableSize) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, QUOTA_EXCEEDED_ERR), callbackId); + return; + } + } + } + + if (fileSystemType == PERSISTENT) + { + // TODO: this should be in it's own folder to prevent overwriting of the app assets, which are also in ISO + DispatchCommandResult(new PluginResult(PluginResult.Status.OK, new FileSystemInfo("persistent", FileEntry.GetEntry("/"))), callbackId); + } + else if (fileSystemType == TEMPORARY) + { + using (IsolatedStorageFile isoStorage = IsolatedStorageFile.GetUserStoreForApplication()) + { + if (!isoStorage.FileExists(TMP_DIRECTORY_NAME)) + { + isoStorage.CreateDirectory(TMP_DIRECTORY_NAME); + } + } + + string tmpFolder = "/" + TMP_DIRECTORY_NAME + "/"; + + DispatchCommandResult(new PluginResult(PluginResult.Status.OK, new FileSystemInfo("temporary", FileEntry.GetEntry(tmpFolder))), callbackId); + } + else if (fileSystemType == RESOURCE) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.OK, new FileSystemInfo("resource")), callbackId); + } + else if (fileSystemType == APPLICATION) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.OK, new FileSystemInfo("application")), callbackId); + } + else + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR), callbackId); + } + + } + catch (Exception ex) + { + if (!this.HandleException(ex)) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR), callbackId); + } + } + } + + public void resolveLocalFileSystemURI(string options) + { + + string[] optVals = getOptionStrings(options); + string uri = optVals[0].Split('?')[0]; + string callbackId = optVals[1]; + + if (uri != null) + { + // a single '/' is valid, however, '/someDir' is not, but '/tmp//somedir' and '///someDir' are valid + if (uri.StartsWith("/") && uri.IndexOf("//") < 0 && uri != "/") + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ENCODING_ERR), callbackId); + return; + } + try + { + // fix encoded spaces + string path = Uri.UnescapeDataString(uri); + + FileEntry uriEntry = FileEntry.GetEntry(path); + if (uriEntry != null) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.OK, uriEntry), callbackId); + } + else + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); + } + } + catch (Exception ex) + { + if (!this.HandleException(ex, callbackId)) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR), callbackId); + } + } + } + } + + public void copyTo(string options) + { + TransferTo(options, false); + } + + public void moveTo(string options) + { + TransferTo(options, true); + } + + public void getFile(string options) + { + GetFileOrDirectory(options, false); + } + + public void getDirectory(string options) + { + GetFileOrDirectory(options, true); + } + + #region internal functionality + + /// + /// Retrieves the parent directory name of the specified path, + /// + /// Path + /// Parent directory name + private string GetParentDirectory(string path) + { + if (String.IsNullOrEmpty(path) || path == "/") + { + return "/"; + } + + if (path.EndsWith(@"/") || path.EndsWith(@"\")) + { + return this.GetParentDirectory(Path.GetDirectoryName(path)); + } + + string result = Path.GetDirectoryName(path); + if (result == null) + { + result = "/"; + } + + return result; + } + + private bool removeDirRecursively(string fullPath,string callbackId) + { + try + { + if (fullPath == "/") + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR),callbackId); + return false; + } + + using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) + { + if (isoFile.DirectoryExists(fullPath)) + { + string tempPath = File.AddSlashToDirectory(fullPath); + string[] files = isoFile.GetFileNames(tempPath + "*"); + if (files.Length > 0) + { + foreach (string file in files) + { + isoFile.DeleteFile(tempPath + file); + } + } + string[] dirs = isoFile.GetDirectoryNames(tempPath + "*"); + if (dirs.Length > 0) + { + foreach (string dir in dirs) + { + if (!removeDirRecursively(tempPath + dir, callbackId)) + { + return false; + } + } + } + isoFile.DeleteDirectory(fullPath); + } + else + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR),callbackId); + } + } + } + catch (Exception ex) + { + if (!this.HandleException(ex)) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR),callbackId); + return false; + } + } + return true; + } + + private bool CanonicalCompare(string pathA, string pathB) + { + string a = pathA.Replace("//", "/"); + string b = pathB.Replace("//", "/"); + + return a.Equals(b, StringComparison.OrdinalIgnoreCase); + } + + /* + * copyTo:["fullPath","parent", "newName"], + * moveTo:["fullPath","parent", "newName"], + */ + private void TransferTo(string options, bool move) + { + // TODO: try/catch + string[] optStrings = getOptionStrings(options); + string fullPath = optStrings[0]; + string parent = optStrings[1]; + string newFileName = optStrings[2]; + string callbackId = optStrings[3]; + + char[] invalids = Path.GetInvalidPathChars(); + + if (newFileName.IndexOfAny(invalids) > -1 || newFileName.IndexOf(":") > -1 ) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ENCODING_ERR), callbackId); + return; + } + + try + { + if ((parent == null) || (string.IsNullOrEmpty(parent)) || (string.IsNullOrEmpty(fullPath))) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); + return; + } + + string parentPath = File.AddSlashToDirectory(parent); + string currentPath = fullPath; + + using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) + { + bool isFileExist = isoFile.FileExists(currentPath); + bool isDirectoryExist = isoFile.DirectoryExists(currentPath); + bool isParentExist = isoFile.DirectoryExists(parentPath); + + if ( ( !isFileExist && !isDirectoryExist ) || !isParentExist ) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); + return; + } + string newName; + string newPath; + if (isFileExist) + { + newName = (string.IsNullOrEmpty(newFileName)) + ? Path.GetFileName(currentPath) + : newFileName; + + newPath = Path.Combine(parentPath, newName); + + // sanity check .. + // cannot copy file onto itself + if (CanonicalCompare(newPath,currentPath)) //(parent + newFileName)) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, INVALID_MODIFICATION_ERR), callbackId); + return; + } + else if (isoFile.DirectoryExists(newPath)) + { + // there is already a folder with the same name, operation is not allowed + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, INVALID_MODIFICATION_ERR), callbackId); + return; + } + else if (isoFile.FileExists(newPath)) + { // remove destination file if exists, in other case there will be exception + isoFile.DeleteFile(newPath); + } + + if (move) + { + isoFile.MoveFile(currentPath, newPath); + } + else + { + isoFile.CopyFile(currentPath, newPath, true); + } + } + else + { + newName = (string.IsNullOrEmpty(newFileName)) + ? currentPath + : newFileName; + + newPath = Path.Combine(parentPath, newName); + + if (move) + { + // remove destination directory if exists, in other case there will be exception + // target directory should be empty + if (!newPath.Equals(currentPath) && isoFile.DirectoryExists(newPath)) + { + isoFile.DeleteDirectory(newPath); + } + + isoFile.MoveDirectory(currentPath, newPath); + } + else + { + CopyDirectory(currentPath, newPath, isoFile); + } + } + FileEntry entry = FileEntry.GetEntry(newPath); + if (entry != null) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entry), callbackId); + } + else + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); + } + } + + } + catch (Exception ex) + { + if (!this.HandleException(ex, callbackId)) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR), callbackId); + } + } + } + + private bool HandleException(Exception ex, string cbId="") + { + bool handled = false; + string callbackId = String.IsNullOrEmpty(cbId) ? this.CurrentCommandCallbackId : cbId; + if (ex is SecurityException) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, SECURITY_ERR), callbackId); + handled = true; + } + else if (ex is FileNotFoundException) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); + handled = true; + } + else if (ex is ArgumentException) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ENCODING_ERR), callbackId); + handled = true; + } + else if (ex is IsolatedStorageException) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, INVALID_MODIFICATION_ERR), callbackId); + handled = true; + } + else if (ex is DirectoryNotFoundException) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); + handled = true; + } + return handled; + } + + private void CopyDirectory(string sourceDir, string destDir, IsolatedStorageFile isoFile) + { + string path = File.AddSlashToDirectory(sourceDir); + + bool bExists = isoFile.DirectoryExists(destDir); + + if (!bExists) + { + isoFile.CreateDirectory(destDir); + } + + destDir = File.AddSlashToDirectory(destDir); + + string[] files = isoFile.GetFileNames(path + "*"); + + if (files.Length > 0) + { + foreach (string file in files) + { + isoFile.CopyFile(path + file, destDir + file,true); + } + } + string[] dirs = isoFile.GetDirectoryNames(path + "*"); + if (dirs.Length > 0) + { + foreach (string dir in dirs) + { + CopyDirectory(path + dir, destDir + dir, isoFile); + } + } + } + + private string RemoveExtraSlash(string path) { + if (path.StartsWith("//")) { + path = path.Remove(0, 1); + path = RemoveExtraSlash(path); + } + return path; + } + + private string ResolvePath(string parentPath, string path) + { + string absolutePath = null; + + if (path.Contains("..")) + { + if (parentPath.Length > 1 && parentPath.StartsWith("/") && parentPath !="/") + { + parentPath = RemoveExtraSlash(parentPath); + } + + string fullPath = Path.GetFullPath(Path.Combine(parentPath, path)); + absolutePath = fullPath.Replace(Path.GetPathRoot(fullPath), @"//"); + } + else + { + absolutePath = Path.Combine(parentPath + "/", path); + } + return absolutePath; + } + + private void GetFileOrDirectory(string options, bool getDirectory) + { + FileOptions fOptions = new FileOptions(); + string[] args = getOptionStrings(options); + + fOptions.FullPath = args[0]; + fOptions.Path = args[1]; + + string callbackId = args[3]; + + try + { + fOptions.CreatingOpt = JSON.JsonHelper.Deserialize(args[2]); + } + catch (Exception) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION), callbackId); + return; + } + + try + { + if ((string.IsNullOrEmpty(fOptions.Path)) || (string.IsNullOrEmpty(fOptions.FullPath))) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); + return; + } + + string path; + + if (fOptions.Path.Split(':').Length > 2) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ENCODING_ERR), callbackId); + return; + } + + try + { + path = ResolvePath(fOptions.FullPath, fOptions.Path); + } + catch (Exception) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ENCODING_ERR), callbackId); + return; + } + + using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) + { + bool isFile = isoFile.FileExists(path); + bool isDirectory = isoFile.DirectoryExists(path); + bool create = (fOptions.CreatingOpt == null) ? false : fOptions.CreatingOpt.Create; + bool exclusive = (fOptions.CreatingOpt == null) ? false : fOptions.CreatingOpt.Exclusive; + if (create) + { + if (exclusive && (isoFile.FileExists(path) || isoFile.DirectoryExists(path))) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, PATH_EXISTS_ERR), callbackId); + return; + } + + // need to make sure the parent exists + // it is an error to create a directory whose immediate parent does not yet exist + // see issue: https://issues.apache.org/jira/browse/CB-339 + string[] pathParts = path.Split('/'); + string builtPath = pathParts[0]; + for (int n = 1; n < pathParts.Length - 1; n++) + { + builtPath += "/" + pathParts[n]; + if (!isoFile.DirectoryExists(builtPath)) + { + Debug.WriteLine(String.Format("Error :: Parent folder \"{0}\" does not exist, when attempting to create \"{1}\"",builtPath,path)); + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); + return; + } + } + + if ((getDirectory) && (!isDirectory)) + { + isoFile.CreateDirectory(path); + } + else + { + if ((!getDirectory) && (!isFile)) + { + + IsolatedStorageFileStream fileStream = isoFile.CreateFile(path); + fileStream.Close(); + } + } + } + else // (not create) + { + if ((!isFile) && (!isDirectory)) + { + if (path.IndexOf("//www") == 0) + { + Uri fileUri = new Uri(path.Remove(0,2), UriKind.Relative); + StreamResourceInfo streamInfo = Application.GetResourceStream(fileUri); + if (streamInfo != null) + { + FileEntry _entry = FileEntry.GetEntry(fileUri.OriginalString,true); + + DispatchCommandResult(new PluginResult(PluginResult.Status.OK, _entry), callbackId); + + //using (BinaryReader br = new BinaryReader(streamInfo.Stream)) + //{ + // byte[] data = br.ReadBytes((int)streamInfo.Stream.Length); + + //} + + } + else + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); + } + + + } + else + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); + } + return; + } + if (((getDirectory) && (!isDirectory)) || ((!getDirectory) && (!isFile))) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, TYPE_MISMATCH_ERR), callbackId); + return; + } + } + FileEntry entry = FileEntry.GetEntry(path); + if (entry != null) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entry), callbackId); + } + else + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); + } + } + } + catch (Exception ex) + { + if (!this.HandleException(ex)) + { + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR), callbackId); + } + } + } + + private static string AddSlashToDirectory(string dirPath) + { + if (dirPath.EndsWith("/")) + { + return dirPath; + } + else + { + return dirPath + "/"; + } + } + + /// + /// Returns file content in a form of base64 string + /// + /// File stream + /// Base64 representation of the file + private string GetFileContent(Stream stream) + { + int streamLength = (int)stream.Length; + byte[] fileData = new byte[streamLength + 1]; + stream.Read(fileData, 0, streamLength); + stream.Close(); + return Convert.ToBase64String(fileData); + } + + #endregion + + } +} diff --git a/plugins/cordova-plugin-file/tests/package.json b/plugins/cordova-plugin-file/tests/package.json new file mode 100644 index 0000000..c5a1dd7 --- /dev/null +++ b/plugins/cordova-plugin-file/tests/package.json @@ -0,0 +1,17 @@ +{ + "name": "cordova-plugin-file-tests", + "version": "4.3.3-dev", + "description": "", + "cordova": { + "id": "cordova-plugin-file-tests", + "platforms": [ + "android" + ] + }, + "keywords": [ + "ecosystem:cordova", + "cordova-android" + ], + "author": "", + "license": "Apache 2.0" +} diff --git a/plugins/cordova-plugin-file/tests/plugin.xml b/plugins/cordova-plugin-file/tests/plugin.xml new file mode 100644 index 0000000..90844bf --- /dev/null +++ b/plugins/cordova-plugin-file/tests/plugin.xml @@ -0,0 +1,44 @@ + + + + + + Cordova File Plugin Tests + Apache 2.0 + + + + + + + + + + + + + diff --git a/plugins/cordova-plugin-file/tests/src/android/TestContentProvider.java b/plugins/cordova-plugin-file/tests/src/android/TestContentProvider.java new file mode 100644 index 0000000..9eba0d0 --- /dev/null +++ b/plugins/cordova-plugin-file/tests/src/android/TestContentProvider.java @@ -0,0 +1,93 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. + */ +package org.apache.cordova.file.test; + +import android.content.ContentProvider; +import android.net.Uri; +import android.content.res.AssetFileDescriptor; +import android.content.res.AssetManager; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import android.content.ContentValues; +import android.database.Cursor; +import android.os.ParcelFileDescriptor; + +import org.apache.cordova.CordovaResourceApi; + +import java.io.IOException; +import java.util.HashMap; + +public class TestContentProvider extends ContentProvider { + + @Override + public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException { + String fileName = uri.getQueryParameter("realPath"); + if (fileName == null) { + fileName = uri.getPath(); + } + if (fileName == null || fileName.length() < 1) { + throw new FileNotFoundException(); + } + CordovaResourceApi resourceApi = new CordovaResourceApi(getContext(), null); + try { + File f = File.createTempFile("test-content-provider", ".tmp"); + resourceApi.copyResource(Uri.parse("file:///android_asset" + fileName), Uri.fromFile(f)); + return ParcelFileDescriptor.open(f, ParcelFileDescriptor.MODE_READ_ONLY); + } catch (FileNotFoundException e) { + throw e; + } catch (IOException e) { + e.printStackTrace(); + throw new FileNotFoundException("IO error: " + e.toString()); + } + } + + @Override + public boolean onCreate() { + return false; + } + + @Override + public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { + throw new UnsupportedOperationException(); + } + + @Override + public String getType(Uri uri) { + return "text/html"; + } + + @Override + public Uri insert(Uri uri, ContentValues values) { + throw new UnsupportedOperationException(); + } + + @Override + public int delete(Uri uri, String selection, String[] selectionArgs) { + throw new UnsupportedOperationException(); + } + + @Override + public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { + throw new UnsupportedOperationException(); + } + + +} diff --git a/plugins/cordova-plugin-file/tests/tests.js b/plugins/cordova-plugin-file/tests/tests.js new file mode 100644 index 0000000..acdcfa0 --- /dev/null +++ b/plugins/cordova-plugin-file/tests/tests.js @@ -0,0 +1,4012 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +/* jshint jasmine: true */ +/* global WebKitBlobBuilder */ + +exports.defineAutoTests = function () { + var isBrowser = (cordova.platformId === "browser"); + // Use feature detection to determine current browser instead of checking user-agent + var isChrome = isBrowser && window.webkitRequestFileSystem && window.webkitResolveLocalFileSystemURL; + var isIE = isBrowser && (window.msIndexedDB); + var isIndexedDBShim = isBrowser && !isChrome; // Firefox and IE for example + + var isWindows = (cordova.platformId === "windows" || cordova.platformId === "windows8"); + + var MEDIUM_TIMEOUT = 15000; + + describe('File API', function () { + // Adding a Jasmine helper matcher, to report errors when comparing to FileError better. + var fileErrorMap = { + 1 : 'NOT_FOUND_ERR', + 2 : 'SECURITY_ERR', + 3 : 'ABORT_ERR', + 4 : 'NOT_READABLE_ERR', + 5 : 'ENCODING_ERR', + 6 : 'NO_MODIFICATION_ALLOWED_ERR', + 7 : 'INVALID_STATE_ERR', + 8 : 'SYNTAX_ERR', + 9 : 'INVALID_MODIFICATION_ERR', + 10 : 'QUOTA_EXCEEDED_ERR', + 11 : 'TYPE_MISMATCH_ERR', + 12 : 'PATH_EXISTS_ERR' + }, + root, + temp_root, + persistent_root; + beforeEach(function (done) { + // Custom Matchers + jasmine.Expectation.addMatchers({ + toBeFileError : function () { + return { + compare : function (error, code) { + var pass = error.code === code; + return { + pass : pass, + message : 'Expected FileError with code ' + fileErrorMap[error.code] + ' (' + error.code + ') to be ' + fileErrorMap[code] + '(' + code + ')' + }; + } + }; + }, + toCanonicallyMatch : function () { + return { + compare : function (currentPath, path) { + var a = path.split("/").join("").split("\\").join(""), + b = currentPath.split("/").join("").split("\\").join(""), + pass = a === b; + return { + pass : pass, + message : 'Expected paths to match : ' + path + ' should be ' + currentPath + }; + } + }; + }, + toFailWithMessage : function () { + return { + compare : function (error, message) { + var pass = false; + return { + pass : pass, + message : message + }; + } + }; + }, + toBeDataUrl: function () { + return { + compare : function (url) { + var pass = false; + // "data:application/octet-stream;base64," + var header = url.substr(0, url.indexOf(',')); + var headerParts = header.split(/[:;]/); + if (headerParts.length === 3 && + headerParts[0] === 'data' && + headerParts[2] === 'base64') { + pass = true; + } + var message = 'Expected ' + url + ' to be a valid data url. ' + header + ' is not valid header for data uris'; + return { + pass : pass, + message : message + }; + } + }; + } + }); + //Define global variables + var onError = function (e) { + console.log('[ERROR] Problem setting up root filesystem for test running! Error to follow.'); + console.log(JSON.stringify(e)); + }; + window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) { + root = fileSystem.root; + // set in file.tests.js + persistent_root = root; + window.requestFileSystem(LocalFileSystem.TEMPORARY, 0, function (fileSystem) { + temp_root = fileSystem.root; + // set in file.tests.js + done(); + }, onError); + }, onError); + }); + // HELPER FUNCTIONS + // deletes specified file or directory + var deleteEntry = function (name, success, error) { + // deletes entry, if it exists + // entry.remove success callback is required: http://www.w3.org/TR/2011/WD-file-system-api-20110419/#the-entry-interface + success = success || function() {}; + error = error || failed.bind(null, success, 'deleteEntry failed.'); + + window.resolveLocalFileSystemURL(root.toURL() + '/' + name, function (entry) { + if (entry.isDirectory === true) { + entry.removeRecursively(success, error); + } else { + entry.remove(success, error); + } + }, success); + }; + // deletes file, if it exists, then invokes callback + var deleteFile = function (fileName, callback) { + // entry.remove success callback is required: http://www.w3.org/TR/2011/WD-file-system-api-20110419/#the-entry-interface + callback = callback || function() {}; + + root.getFile(fileName, null, // remove file system entry + function (entry) { + entry.remove(callback, function () { + console.log('[ERROR] deleteFile cleanup method invoked fail callback.'); + }); + }, // doesn't exist + callback); + }; + // deletes and re-creates the specified file + var createFile = function (fileName, success, error) { + deleteEntry(fileName, function () { + root.getFile(fileName, { + create : true + }, success, error); + }, error); + }; + // deletes and re-creates the specified directory + var createDirectory = function (dirName, success, error) { + deleteEntry(dirName, function () { + root.getDirectory(dirName, { + create : true + }, success, error); + }, error); + }; + function failed(done, msg, error) { + var info = typeof msg == 'undefined' ? 'Unexpected error callback' : msg; + var codeMsg = (error && error.code) ? (': ' + fileErrorMap[error.code]) : ''; + expect(true).toFailWithMessage(info + '\n' + JSON.stringify(error) + codeMsg); + done(); + } + var succeed = function (done, msg) { + var info = typeof msg == 'undefined' ? 'Unexpected success callback' : msg; + expect(true).toFailWithMessage(info); + done(); + }; + var joinURL = function (base, extension) { + if (base.charAt(base.length - 1) !== '/' && extension.charAt(0) !== '/') { + return base + '/' + extension; + } + if (base.charAt(base.length - 1) === '/' && extension.charAt(0) === '/') { + return base + extension.substring(1); + } + return base + extension; + }; + describe('FileError object', function () { + it("file.spec.1 should define FileError constants", function () { + expect(FileError.NOT_FOUND_ERR).toBe(1); + expect(FileError.SECURITY_ERR).toBe(2); + expect(FileError.ABORT_ERR).toBe(3); + expect(FileError.NOT_READABLE_ERR).toBe(4); + expect(FileError.ENCODING_ERR).toBe(5); + expect(FileError.NO_MODIFICATION_ALLOWED_ERR).toBe(6); + expect(FileError.INVALID_STATE_ERR).toBe(7); + expect(FileError.SYNTAX_ERR).toBe(8); + expect(FileError.INVALID_MODIFICATION_ERR).toBe(9); + expect(FileError.QUOTA_EXCEEDED_ERR).toBe(10); + expect(FileError.TYPE_MISMATCH_ERR).toBe(11); + expect(FileError.PATH_EXISTS_ERR).toBe(12); + }); + }); + describe('LocalFileSystem', function () { + it("file.spec.2 should define LocalFileSystem constants", function () { + expect(LocalFileSystem.TEMPORARY).toBe(0); + expect(LocalFileSystem.PERSISTENT).toBe(1); + }); + describe('window.requestFileSystem', function () { + it("file.spec.3 should be defined", function () { + expect(window.requestFileSystem).toBeDefined(); + }); + it("file.spec.4 should be able to retrieve a PERSISTENT file system", function (done) { + var win = function (fileSystem) { + expect(fileSystem).toBeDefined(); + expect(fileSystem.name).toBeDefined(); + if (isChrome) { + expect(fileSystem.name).toContain("Persistent"); + } else { + expect(fileSystem.name).toBe("persistent"); + } + expect(fileSystem.root).toBeDefined(); + expect(fileSystem.root.filesystem).toBeDefined(); + // Shouldn't use cdvfile by default. + expect(fileSystem.root.toURL()).not.toMatch(/^cdvfile:/); + // All DirectoryEntry URLs should always have a trailing slash. + expect(fileSystem.root.toURL()).toMatch(/\/$/); + done(); + }; + + // Request a little bit of space on the filesystem, unless we're running in a browser where that could cause a prompt. + var spaceRequired = isBrowser ? 0 : 1024; + + // retrieve PERSISTENT file system + window.requestFileSystem(LocalFileSystem.PERSISTENT, spaceRequired, win, failed.bind(null, done, 'window.requestFileSystem - Error retrieving PERSISTENT file system')); + }); + it("file.spec.5 should be able to retrieve a TEMPORARY file system", function (done) { + var win = function (fileSystem) { + expect(fileSystem).toBeDefined(); + if (isChrome) { + expect(fileSystem.name).toContain("Temporary"); + } else { + expect(fileSystem.name).toBe("temporary"); + } + expect(fileSystem.root).toBeDefined(); + expect(fileSystem.root.filesystem).toBeDefined(); + expect(fileSystem.root.filesystem).toBe(fileSystem); + done(); + }; + //retrieve TEMPORARY file system + window.requestFileSystem(LocalFileSystem.TEMPORARY, 0, win, failed.bind(null, done, 'window.requestFileSystem - Error retrieving TEMPORARY file system')); + }); + it("file.spec.6 should error if you request a file system that is too large", function (done) { + if (isBrowser) { + /*window.requestFileSystem TEMPORARY and PERSISTENT filesystem quota is not limited in Chrome. + Firefox filesystem size is not limited but every 50MB request user permission. + IE10 allows up to 10mb of combined AppCache and IndexedDB used in implementation + of filesystem without prompting, once you hit that level you will be asked if you + want to allow it to be increased up to a max of 250mb per site. + So `size` parameter for `requestFileSystem` function does not affect on filesystem in Firefox and IE.*/ + pending(); + } + + var fail = function (error) { + expect(error).toBeDefined(); + expect(error).toBeFileError(FileError.QUOTA_EXCEEDED_ERR); + done(); + }; + //win = createWin('window.requestFileSystem'); + // Request the file system + window.requestFileSystem(LocalFileSystem.TEMPORARY, 1000000000000000, failed.bind(null, done, 'window.requestFileSystem - Error retrieving TEMPORARY file system'), fail); + }); + it("file.spec.7 should error out if you request a file system that does not exist", function (done) { + + var fail = function (error) { + expect(error).toBeDefined(); + if (isChrome) { + /*INVALID_MODIFICATION_ERR (code: 9) is thrown instead of SYNTAX_ERR(code: 8) + on requesting of a non-existant filesystem.*/ + expect(error).toBeFileError(FileError.INVALID_MODIFICATION_ERR); + } else { + expect(error).toBeFileError(FileError.SYNTAX_ERR); + } + done(); + }; + // Request the file system + window.requestFileSystem(-1, 0, succeed.bind(null, done, 'window.requestFileSystem'), fail); + }); + }); + describe('window.resolveLocalFileSystemURL', function () { + it("file.spec.8 should be defined", function () { + expect(window.resolveLocalFileSystemURL).toBeDefined(); + }); + it("file.spec.9 should resolve a valid file name", function (done) { + var fileName = 'file.spec.9'; + var win = function (fileEntry) { + expect(fileEntry).toBeDefined(); + expect(fileEntry.isFile).toBe(true); + expect(fileEntry.isDirectory).toBe(false); + expect(fileEntry.name).toCanonicallyMatch(fileName); + expect(fileEntry.toURL()).not.toMatch(/^cdvfile:/, 'should not use cdvfile URL'); + expect(fileEntry.toURL()).not.toMatch(/\/$/, 'URL should not end with a slash'); + // Clean-up + deleteEntry(fileName, done); + }; + createFile(fileName, function (entry) { + window.resolveLocalFileSystemURL(entry.toURL(), win, failed.bind(null, done, 'window.resolveLocalFileSystemURL - Error resolving file URL: ' + entry.toURL())); + }, failed.bind(null, done, 'createFile - Error creating file: ' + fileName), failed.bind(null, done, 'createFile - Error creating file: ' + fileName)); + }); + it("file.spec.9.1 should resolve a file even with a terminating slash", function (done) { + var fileName = 'file.spec.9.1'; + var win = function (fileEntry) { + expect(fileEntry).toBeDefined(); + expect(fileEntry.isFile).toBe(true); + expect(fileEntry.isDirectory).toBe(false); + expect(fileEntry.name).toCanonicallyMatch(fileName); + expect(fileEntry.toURL()).not.toMatch(/^cdvfile:/, 'should not use cdvfile URL'); + expect(fileEntry.toURL()).not.toMatch(/\/$/, 'URL should not end with a slash'); + // Clean-up + deleteEntry(fileName, done); + }; + createFile(fileName, function (entry) { + var entryURL = entry.toURL() + '/'; + window.resolveLocalFileSystemURL(entryURL, win, failed.bind(null, done, 'window.resolveLocalFileSystemURL - Error resolving file URL: ' + entryURL)); + }, failed.bind(null, done, 'createFile - Error creating file: ' + fileName), failed.bind(null, done, 'createFile - Error creating file: ' + fileName)); + }); + it("file.spec.9.5 should resolve a directory", function (done) { + var fileName = 'file.spec.9.5'; + var win = function (fileEntry) { + expect(fileEntry).toBeDefined(); + expect(fileEntry.isFile).toBe(false); + expect(fileEntry.isDirectory).toBe(true); + expect(fileEntry.name).toCanonicallyMatch(fileName); + expect(fileEntry.toURL()).not.toMatch(/^cdvfile:/, 'should not use cdvfile URL'); + expect(fileEntry.toURL()).toMatch(/\/$/, 'URL end with a slash'); + // cleanup + deleteEntry(fileName, done); + }; + function gotDirectory(entry) { + // lookup file system entry + window.resolveLocalFileSystemURL(entry.toURL(), win, failed.bind(null, done, 'window.resolveLocalFileSystemURL - Error resolving directory URL: ' + entry.toURL())); + } + createDirectory(fileName, gotDirectory, failed.bind(null, done, 'createDirectory - Error creating directory: ' + fileName), failed.bind(null, done, 'createDirectory - Error creating directory: ' + fileName)); + }); + it("file.spec.9.6 should resolve a directory even without a terminating slash", function (done) { + var fileName = 'file.spec.9.6'; + var win = function (fileEntry) { + expect(fileEntry).toBeDefined(); + expect(fileEntry.isFile).toBe(false); + expect(fileEntry.isDirectory).toBe(true); + expect(fileEntry.name).toCanonicallyMatch(fileName); + expect(fileEntry.toURL()).not.toMatch(/^cdvfile:/, 'should not use cdvfile URL'); + expect(fileEntry.toURL()).toMatch(/\/$/, 'URL end with a slash'); + // cleanup + deleteEntry(fileName, done); + }; + function gotDirectory(entry) { + // lookup file system entry + var entryURL = entry.toURL(); + entryURL = entryURL.substring(0, entryURL.length - 1); + window.resolveLocalFileSystemURL(entryURL, win, failed.bind(null, done, 'window.resolveLocalFileSystemURL - Error resolving directory URL: ' + entryURL)); + } + createDirectory(fileName, gotDirectory, failed.bind(null, done, 'createDirectory - Error creating directory: ' + fileName), failed.bind(null, done, 'createDirectory - Error creating directory: ' + fileName)); + }); + + it("file.spec.9.7 should resolve a file with valid nativeURL", function (done) { + var fileName = "de.create.file", + win = function (entry) { + var path = entry.nativeURL.split('///')[1]; + expect(/\/{2,}/.test(path)).toBeFalsy(); + // cleanup + deleteEntry(entry.name, done); + }; + root.getFile(fileName, { + create: true + }, win, succeed.bind(null, done, 'root.getFile - Error unexpected callback, file should not exists: ' + fileName)); + }); + + it("file.spec.10 resolve valid file name with parameters", function (done) { + var fileName = "resolve.file.uri.params", + win = function (fileEntry) { + expect(fileEntry).toBeDefined(); + if (fileEntry.toURL().toLowerCase().substring(0, 10) === "cdvfile://") { + expect(fileEntry.fullPath).toBe("/" + fileName + "?1234567890"); + } + expect(fileEntry.name).toBe(fileName); + // cleanup + deleteEntry(fileName, done); + }; + // create a new file entry + createFile(fileName, function (entry) { + window.resolveLocalFileSystemURL(entry.toURL() + "?1234567890", win, failed.bind(null, done, 'window.resolveLocalFileSystemURL - Error resolving file URI: ' + entry.toURL())); + }, failed.bind(null, done, 'createFile - Error creating file: ' + fileName)); + }); + it("file.spec.11 should error (NOT_FOUND_ERR) when resolving (non-existent) invalid file name", function (done) { + var fileName = cordova.platformId === 'windowsphone' ? root.toURL() + "/" + "this.is.not.a.valid.file.txt" : joinURL(root.toURL(), "this.is.not.a.valid.file.txt"), + fail = function (error) { + expect(error).toBeDefined(); + expect(error).toBeFileError(FileError.NOT_FOUND_ERR); + done(); + }; + // lookup file system entry + window.resolveLocalFileSystemURL(fileName, succeed.bind(null, done, 'window.resolveLocalFileSystemURL - Error unexpected callback resolving file URI: ' + fileName), fail); + }); + it("file.spec.12 should error (ENCODING_ERR) when resolving invalid URI with leading /", function (done) { + var fileName = "/this.is.not.a.valid.url", + fail = function (error) { + expect(error).toBeDefined(); + expect(error).toBeFileError(FileError.ENCODING_ERR); + done(); + }; + // lookup file system entry + window.resolveLocalFileSystemURL(fileName, succeed.bind(null, done, 'window.resolveLocalFileSystemURL - Error unexpected callback resolving file URI: ' + fileName), fail); + }); + }); + }); + //LocalFileSystem + describe('Metadata interface', function () { + it("file.spec.13 should exist and have the right properties", function () { + var metadata = new Metadata(); + expect(metadata).toBeDefined(); + expect(metadata.modificationTime).toBeDefined(); + }); + }); + describe('Flags interface', function () { + it("file.spec.14 should exist and have the right properties", function () { + var flags = new Flags(false, true); + expect(flags).toBeDefined(); + expect(flags.create).toBeDefined(); + expect(flags.create).toBe(false); + expect(flags.exclusive).toBeDefined(); + expect(flags.exclusive).toBe(true); + }); + }); + describe('FileSystem interface', function () { + it("file.spec.15 should have a root that is a DirectoryEntry", function (done) { + var win = function (entry) { + expect(entry).toBeDefined(); + expect(entry.isFile).toBe(false); + expect(entry.isDirectory).toBe(true); + expect(entry.name).toBeDefined(); + expect(entry.fullPath).toBeDefined(); + expect(entry.getMetadata).toBeDefined(); + expect(entry.moveTo).toBeDefined(); + expect(entry.copyTo).toBeDefined(); + expect(entry.toURL).toBeDefined(); + expect(entry.remove).toBeDefined(); + expect(entry.getParent).toBeDefined(); + expect(entry.createReader).toBeDefined(); + expect(entry.getFile).toBeDefined(); + expect(entry.getDirectory).toBeDefined(); + expect(entry.removeRecursively).toBeDefined(); + done(); + }; + window.resolveLocalFileSystemURL(root.toURL(), win, failed.bind(null, done, 'window.resolveLocalFileSystemURL - Error resolving file URI: ' + root.toURL())); + }); + }); + describe('DirectoryEntry', function () { + it("file.spec.16 getFile: get Entry for file that does not exist", function (done) { + var fileName = "de.no.file", + fail = function (error) { + expect(error).toBeDefined(); + expect(error).toBeFileError(FileError.NOT_FOUND_ERR); + done(); + }; + // create:false, exclusive:false, file does not exist + root.getFile(fileName, { + create : false + }, succeed.bind(null, done, 'root.getFile - Error unexpected callback, file should not exists: ' + fileName), fail); + }); + it("file.spec.17 getFile: create new file", function (done) { + var fileName = "de.create.file", + filePath = joinURL(root.fullPath, fileName), + win = function (entry) { + expect(entry).toBeDefined(); + expect(entry.isFile).toBe(true); + expect(entry.isDirectory).toBe(false); + expect(entry.name).toCanonicallyMatch(fileName); + expect(entry.fullPath).toCanonicallyMatch(filePath); + // cleanup + deleteEntry(entry.name, done); + }; + // create:true, exclusive:false, file does not exist + root.getFile(fileName, { + create : true + }, win, succeed.bind(null, done, 'root.getFile - Error unexpected callback, file should not exists: ' + fileName)); + }); + it("file.spec.18 getFile: create new file (exclusive)", function (done) { + var fileName = "de.create.exclusive.file", + filePath = joinURL(root.fullPath, fileName), + win = function (entry) { + expect(entry).toBeDefined(); + expect(entry.isFile).toBe(true); + expect(entry.isDirectory).toBe(false); + expect(entry.name).toBe(fileName); + expect(entry.fullPath).toCanonicallyMatch(filePath); + // cleanup + deleteEntry(entry.name, done); + }; + // create:true, exclusive:true, file does not exist + root.getFile(fileName, { + create : true, + exclusive : true + }, win, failed.bind(null, done, 'root.getFile - Error creating file: ' + fileName)); + }); + it("file.spec.19 getFile: create file that already exists", function (done) { + var fileName = "de.create.existing.file", + filePath = joinURL(root.fullPath, fileName); + + function win(entry) { + expect(entry).toBeDefined(); + expect(entry.isFile).toBe(true); + expect(entry.isDirectory).toBe(false); + expect(entry.name).toCanonicallyMatch(fileName); + expect(entry.fullPath).toCanonicallyMatch(filePath); + // cleanup + deleteEntry(entry.name, done); + } + + function getFile(file) { + // create:true, exclusive:false, file exists + root.getFile(fileName, { + create : true + }, win, failed.bind(null, done, 'root.getFile - Error creating file: ' + fileName)); + } + + // create file to kick off it + root.getFile(fileName, { + create : true + }, getFile, failed.bind(null, done, 'root.getFile - Error on initial creating file: ' + fileName)); + }); + it("file.spec.20 getFile: create file that already exists (exclusive)", function (done) { + var fileName = "de.create.exclusive.existing.file", + existingFile; + + function fail(error) { + expect(error).toBeDefined(); + if (isChrome) { + /*INVALID_MODIFICATION_ERR (code: 9) is thrown instead of PATH_EXISTS_ERR(code: 12) + on trying to exclusively create a file, which already exists in Chrome.*/ + expect(error).toBeFileError(FileError.INVALID_MODIFICATION_ERR); + } else { + expect(error).toBeFileError(FileError.PATH_EXISTS_ERR); + } + // cleanup + deleteEntry(existingFile.name, done); + } + + function getFile(file) { + existingFile = file; + // create:true, exclusive:true, file exists + root.getFile(fileName, { + create : true, + exclusive : true + }, succeed.bind(null, done, 'root.getFile - getFile function - Error unexpected callback, file should exists: ' + fileName), fail); + } + + // create file to kick off it + root.getFile(fileName, { + create : true + }, getFile, failed.bind(null, done, 'root.getFile - Error creating file: ' + fileName)); + }); + it("file.spec.21 DirectoryEntry.getFile: get Entry for existing file", function (done) { + var fileName = "de.get.file", + filePath = joinURL(root.fullPath, fileName), + win = function (entry) { + expect(entry).toBeDefined(); + expect(entry.isFile).toBe(true); + expect(entry.isDirectory).toBe(false); + expect(entry.name).toCanonicallyMatch(fileName); + expect(entry.fullPath).toCanonicallyMatch(filePath); + expect(entry.filesystem).toBeDefined(); + expect(entry.filesystem).toBe(root.filesystem); + //clean up + deleteEntry(entry.name, done); + }, + getFile = function (file) { + // create:false, exclusive:false, file exists + root.getFile(fileName, { + create : false + }, win, failed.bind(null, done, 'root.getFile - Error getting file entry: ' + fileName)); + }; + // create file to kick off it + root.getFile(fileName, { + create : true + }, getFile, failed.bind(null, done, 'root.getFile - Error creating file: ' + fileName)); + }); + it("file.spec.22 DirectoryEntry.getFile: get FileEntry for invalid path", function (done) { + if (isBrowser) { + /*The plugin does not follow to ["8.3 Naming restrictions"] + (http://www.w3.org/TR/2011/WD-file-system-api-20110419/#naming-restrictions).*/ + pending(); + } + + var fileName = "de:invalid:path", + fail = function (error) { + expect(error).toBeDefined(); + expect(error).toBeFileError(FileError.ENCODING_ERR); + done(); + }; + // create:false, exclusive:false, invalid path + root.getFile(fileName, { + create : false + }, succeed.bind(null, done, 'root.getFile - Error unexpected callback, file should not exists: ' + fileName), fail); + }); + it("file.spec.23 DirectoryEntry.getDirectory: get Entry for directory that does not exist", function (done) { + var dirName = "de.no.dir", + fail = function (error) { + expect(error).toBeDefined(); + expect(error).toBeFileError(FileError.NOT_FOUND_ERR); + done(); + }; + // create:false, exclusive:false, directory does not exist + root.getDirectory(dirName, { + create : false + }, succeed.bind(null, done, 'root.getDirectory - Error unexpected callback, directory should not exists: ' + dirName), fail); + }); + it("file.spec.24 DirectoryEntry.getDirectory: create new dir with space then resolveLocalFileSystemURL", function (done) { + var dirName = "de create dir"; + + function win(directory) { + expect(directory).toBeDefined(); + expect(directory.isFile).toBe(false); + expect(directory.isDirectory).toBe(true); + expect(directory.name).toCanonicallyMatch(dirName); + expect(directory.fullPath).toCanonicallyMatch(joinURL(root.fullPath, dirName)); + // cleanup + deleteEntry(directory.name, done); + } + + function getDir(dirEntry) { + expect(dirEntry.filesystem).toBeDefined(); + expect(dirEntry.filesystem).toBe(root.filesystem); + var dirURI = dirEntry.toURL(); + // now encode URI and try to resolve + window.resolveLocalFileSystemURL(dirURI, win, failed.bind(null, done, 'window.resolveLocalFileSystemURL - getDir function - Error resolving directory: ' + dirURI)); + } + + // create:true, exclusive:false, directory does not exist + root.getDirectory(dirName, { + create : true + }, getDir, failed.bind(null, done, 'root.getDirectory - Error creating directory : ' + dirName)); + }); + // This test is excluded, and should probably be removed. Filesystem + // should always be properly encoded URLs, and *not* raw paths, and it + // doesn't make sense to double-encode the URLs and expect that to be + // handled by the implementation. + // If a particular platform uses paths internally rather than URLs, // then that platform should careful to pass them correctly to its + // backend. + xit("file.spec.25 DirectoryEntry.getDirectory: create new dir with space resolveLocalFileSystemURL with encoded URI", function (done) { + var dirName = "de create dir2", + dirPath = joinURL(root.fullPath, dirName); + + function win(directory) { + expect(directory).toBeDefined(); + expect(directory.isFile).toBe(false); + expect(directory.isDirectory).toBe(true); + expect(directory.name).toCanonicallyMatch(dirName); + expect(directory.fullPath).toCanonicallyMatch(dirPath); + // cleanup + deleteEntry(directory.name, done); + } + + function getDir(dirEntry) { + var dirURI = dirEntry.toURL(); + // now encode URI and try to resolve + window.resolveLocalFileSystemURL(encodeURI(dirURI), win, failed.bind(null, done, 'window.resolveLocalFileSystemURL - getDir function - Error resolving directory: ' + dirURI)); + } + + // create:true, exclusive:false, directory does not exist + root.getDirectory(dirName, { + create : true + }, getDir, failed.bind(null, done, 'root.getDirectory - Error creating directory : ' + dirName)); + }); + it("file.spec.26 DirectoryEntry.getDirectory: create new directory", function (done) { + var dirName = "de.create.dir", + dirPath = joinURL(root.fullPath, dirName), + win = function (directory) { + expect(directory).toBeDefined(); + expect(directory.isFile).toBe(false); + expect(directory.isDirectory).toBe(true); + expect(directory.name).toCanonicallyMatch(dirName); + expect(directory.fullPath).toCanonicallyMatch(dirPath); + expect(directory.filesystem).toBeDefined(); + expect(directory.filesystem).toBe(root.filesystem); + // cleanup + deleteEntry(directory.name, done); + }; + // create:true, exclusive:false, directory does not exist + root.getDirectory(dirName, { + create : true + }, win, failed.bind(null, done, 'root.getDirectory - Error creating directory : ' + dirName)); + }); + it("file.spec.27 DirectoryEntry.getDirectory: create new directory (exclusive)", function (done) { + var dirName = "de.create.exclusive.dir", + dirPath = joinURL(root.fullPath, dirName), + win = function (directory) { + expect(directory).toBeDefined(); + expect(directory.isFile).toBe(false); + expect(directory.isDirectory).toBe(true); + expect(directory.name).toCanonicallyMatch(dirName); + expect(directory.fullPath).toCanonicallyMatch(dirPath); + expect(directory.filesystem).toBeDefined(); + expect(directory.filesystem).toBe(root.filesystem); + // cleanup + deleteEntry(directory.name, done); + }; + // create:true, exclusive:true, directory does not exist + root.getDirectory(dirName, { + create : true, + exclusive : true + }, win, failed.bind(null, done, 'root.getDirectory - Error creating directory : ' + dirName)); + }); + it("file.spec.28 DirectoryEntry.getDirectory: create directory that already exists", function (done) { + var dirName = "de.create.existing.dir", + dirPath = joinURL(root.fullPath, dirName), + win = function (directory) { + expect(directory).toBeDefined(); + expect(directory.isFile).toBe(false); + expect(directory.isDirectory).toBe(true); + expect(directory.name).toCanonicallyMatch(dirName); + expect(directory.fullPath).toCanonicallyMatch(dirPath); + // cleanup + deleteEntry(directory.name, done); + }; + // create directory to kick off it + root.getDirectory(dirName, { + create : true + }, function () { + root.getDirectory(dirName, { + create : true + }, win, failed.bind(null, done, 'root.getDirectory - Error creating existent second directory : ' + dirName)); + }, failed.bind(null, done, 'root.getDirectory - Error creating directory : ' + dirName)); + }); + it("file.spec.29 DirectoryEntry.getDirectory: create directory that already exists (exclusive)", function (done) { + + var dirName = "de.create.exclusive.existing.dir", + existingDir, + fail = function (error) { + expect(error).toBeDefined(); + if (isChrome) { + /*INVALID_MODIFICATION_ERR (code: 9) is thrown instead of PATH_EXISTS_ERR(code: 12) + on trying to exclusively create a file or directory, which already exists (Chrome).*/ + expect(error).toBeFileError(FileError.INVALID_MODIFICATION_ERR); + } else { + expect(error).toBeFileError(FileError.PATH_EXISTS_ERR); + } + // cleanup + deleteEntry(existingDir.name, done); + }; + // create directory to kick off it + root.getDirectory(dirName, { + create : true + }, function (directory) { + existingDir = directory; + // create:true, exclusive:true, directory exists + root.getDirectory(dirName, { + create : true, + exclusive : true + }, failed.bind(null, done, 'root.getDirectory - Unexpected success callback, second directory should not be created : ' + dirName), fail); + }, failed.bind(null, done, 'root.getDirectory - Error creating directory : ' + dirName)); + }); + it("file.spec.30 DirectoryEntry.getDirectory: get Entry for existing directory", function (done) { + var dirName = "de.get.dir", + dirPath = joinURL(root.fullPath, dirName), + win = function (directory) { + expect(directory).toBeDefined(); + expect(directory.isFile).toBe(false); + expect(directory.isDirectory).toBe(true); + expect(directory.name).toCanonicallyMatch(dirName); + expect(directory.fullPath).toCanonicallyMatch(dirPath); + // cleanup + deleteEntry(directory.name, done); + }; + // create directory to kick it off + root.getDirectory(dirName, { + create : true + }, function () { + root.getDirectory(dirName, { + create : false + }, win, failed.bind(null, done, 'root.getDirectory - Error getting directory entry : ' + dirName)); + }, failed.bind(null, done, 'root.getDirectory - Error creating directory : ' + dirName)); + }); + it("file.spec.31 DirectoryEntry.getDirectory: get DirectoryEntry for invalid path", function (done) { + if (isBrowser) { + /*The plugin does not follow to ["8.3 Naming restrictions"] + (http://www.w3.org/TR/2011/WD-file-system-api-20110419/#naming-restrictions).*/ + pending(); + } + + var dirName = "de:invalid:path", + fail = function (error) { + expect(error).toBeDefined(); + expect(error).toBeFileError(FileError.ENCODING_ERR); + done(); + }; + // create:false, exclusive:false, invalid path + root.getDirectory(dirName, { + create : false + }, succeed.bind(null, done, 'root.getDirectory - Unexpected success callback, directory should not exists: ' + dirName), fail); + }); + it("file.spec.32 DirectoryEntry.getDirectory: get DirectoryEntry for existing file", function (done) { + var fileName = "de.existing.file", + existingFile, + fail = function (error) { + expect(error).toBeDefined(); + expect(error).toBeFileError(FileError.TYPE_MISMATCH_ERR); + // cleanup + deleteEntry(existingFile.name, done); + }; + // create file to kick off it + root.getFile(fileName, { + create : true + }, function (file) { + existingFile = file; + root.getDirectory(fileName, { + create : false + }, succeed.bind(null, done, 'root.getDirectory - Unexpected success callback, directory should not exists: ' + fileName), fail); + }, failed.bind(null, done, 'root.getFile - Error creating file : ' + fileName)); + }); + it("file.spec.33 DirectoryEntry.getFile: get FileEntry for existing directory", function (done) { + var dirName = "de.existing.dir", + existingDir, + fail = function (error) { + expect(error).toBeDefined(); + expect(error).toBeFileError(FileError.TYPE_MISMATCH_ERR); + // cleanup + deleteEntry(existingDir.name, done); + }; + // create directory to kick off it + root.getDirectory(dirName, { + create : true + }, function (directory) { + existingDir = directory; + root.getFile(dirName, { + create : false + }, succeed.bind(null, done, 'root.getFile - Unexpected success callback, file should not exists: ' + dirName), fail); + }, failed.bind(null, done, 'root.getDirectory - Error creating directory : ' + dirName)); + }); + it("file.spec.34 DirectoryEntry.removeRecursively on directory", function (done) { + var dirName = "de.removeRecursively", + subDirName = "dir", + dirExists = function (error) { + expect(error).toBeDefined(); + expect(error).toBeFileError(FileError.NOT_FOUND_ERR); + done(); + }; + // create a new directory entry to kick off it + root.getDirectory(dirName, { + create : true + }, function (entry) { + entry.getDirectory(subDirName, { + create : true + }, function (dir) { + entry.removeRecursively(function () { + root.getDirectory(dirName, { + create : false + }, succeed.bind(null, done, 'root.getDirectory - Unexpected success callback, directory should not exists: ' + dirName), dirExists); + }, failed.bind(null, done, 'entry.removeRecursively - Error removing directory recursively : ' + dirName)); + }, failed.bind(null, done, 'root.getDirectory - Error creating directory : ' + subDirName)); + }, failed.bind(null, done, 'root.getDirectory - Error creating directory : ' + dirName)); + }); + it("file.spec.35 createReader: create reader on existing directory", function () { + // create reader for root directory + var reader = root.createReader(); + expect(reader).toBeDefined(); + expect(typeof reader.readEntries).toBe('function'); + }); + it("file.spec.36 removeRecursively on root file system", function (done) { + + var remove = function (error) { + expect(error).toBeDefined(); + if (isChrome) { + /*INVALID_MODIFICATION_ERR (code: 9) is thrown instead of + NO_MODIFICATION_ALLOWED_ERR(code: 6) on trying to call removeRecursively + on the root file system (Chrome).*/ + expect(error).toBeFileError(FileError.INVALID_MODIFICATION_ERR); + } else { + expect(error).toBeFileError(FileError.NO_MODIFICATION_ALLOWED_ERR); + } + done(); + }; + // remove root file system + root.removeRecursively(succeed.bind(null, done, 'root.removeRecursively - Unexpected success callback, root cannot be removed'), remove); + }); + }); + describe('DirectoryReader interface', function () { + describe("readEntries", function () { + it("file.spec.37 should read contents of existing directory", function (done) { + var reader, + win = function (entries) { + expect(entries).toBeDefined(); + expect(entries instanceof Array).toBe(true); + done(); + }; + // create reader for root directory + reader = root.createReader(); + // read entries + reader.readEntries(win, failed.bind(null, done, 'reader.readEntries - Error reading entries')); + }); + it("file.spec.37.1 should read contents of existing directory", function (done) { + var dirName = 'readEntries.dir', + fileName = 'readeEntries.file'; + root.getDirectory(dirName, { + create : true + }, function (directory) { + directory.getFile(fileName, { + create : true + }, function (fileEntry) { + var reader = directory.createReader(); + reader.readEntries(function (entries) { + expect(entries).toBeDefined(); + expect(entries instanceof Array).toBe(true); + expect(entries.length).toBe(1); + expect(entries[0].fullPath).toCanonicallyMatch(fileEntry.fullPath); + expect(entries[0].filesystem).not.toBe(null); + if (isChrome) { + // Slicing '[object {type}]' -> '{type}' + expect(entries[0].filesystem.toString().slice(8, -1)).toEqual("DOMFileSystem"); + } + else { + expect(entries[0].filesystem instanceof FileSystem).toBe(true); + } + + // cleanup + deleteEntry(directory.name, done); + }, failed.bind(null, done, 'reader.readEntries - Error reading entries from directory: ' + dirName)); + }, failed.bind(null, done, 'directory.getFile - Error creating file : ' + fileName)); + }, failed.bind(null, done, 'root.getDirectory - Error creating directory : ' + dirName)); + }); + it("file.spec.109 should return an empty entry list on the second call", function (done) { + var reader, + fileName = 'test109.txt'; + // Add a file to ensure the root directory is non-empty and then read the contents of the directory. + root.getFile(fileName, { + create : true + }, function (entry) { + reader = root.createReader(); + //First read + reader.readEntries(function (entries) { + expect(entries).toBeDefined(); + expect(entries instanceof Array).toBe(true); + expect(entries.length).not.toBe(0); + //Second read + reader.readEntries(function (entries_) { + expect(entries_).toBeDefined(); + expect(entries_ instanceof Array).toBe(true); + expect(entries_.length).toBe(0); + //Clean up + deleteEntry(entry.name, done); + }, failed.bind(null, done, 'reader.readEntries - Error during SECOND reading of entries from [root] directory')); + }, failed.bind(null, done, 'reader.readEntries - Error during FIRST reading of entries from [root] directory')); + }, failed.bind(null, done, 'root.getFile - Error creating file : ' + fileName)); + }); + }); + it("file.spec.38 should read contents of directory that has been removed", function (done) { + var dirName = "de.createReader.notfound"; + // create a new directory entry to kick off it + root.getDirectory(dirName, { + create : true + }, function (directory) { + directory.removeRecursively(function () { + var reader = directory.createReader(); + reader.readEntries(succeed.bind(null, done, 'reader.readEntries - Unexpected success callback, it should not read entries from deleted dir: ' + dirName), function (error) { + expect(error).toBeDefined(); + expect(error).toBeFileError(FileError.NOT_FOUND_ERR); + root.getDirectory(dirName, { + create : false + }, succeed.bind(null, done, 'root.getDirectory - Unexpected success callback, it should not get deleted directory: ' + dirName), function (err) { + expect(err).toBeDefined(); + expect(err).toBeFileError(FileError.NOT_FOUND_ERR); + done(); + }); + }); + }, failed.bind(null, done, 'directory.removeRecursively - Error removing directory recursively : ' + dirName)); + }, failed.bind(null, done, 'root.getDirectory - Error creating directory : ' + dirName)); + }); + }); + //DirectoryReader interface + describe('File', function () { + it("file.spec.39 constructor should be defined", function () { + expect(File).toBeDefined(); + expect(typeof File).toBe('function'); + }); + it("file.spec.40 should be define File attributes", function () { + var file = new File(); + expect(file.name).toBeDefined(); + expect(file.type).toBeDefined(); + expect(file.lastModifiedDate).toBeDefined(); + expect(file.size).toBeDefined(); + }); + }); + //File + describe('FileEntry', function () { + + it("file.spec.41 should be define FileEntry methods", function (done) { + var fileName = "fe.methods", + testFileEntry = function (fileEntry) { + expect(fileEntry).toBeDefined(); + expect(typeof fileEntry.createWriter).toBe('function'); + expect(typeof fileEntry.file).toBe('function'); + // cleanup + deleteEntry(fileEntry.name, done); + }; + // create a new file entry to kick off it + root.getFile(fileName, { + create : true + }, testFileEntry, failed.bind(null, done, 'root.getFile - Error creating file : ' + fileName)); + }); + it("file.spec.42 createWriter should return a FileWriter object", function (done) { + var fileName = "fe.createWriter", + testFile, + testWriter = function (writer) { + expect(writer).toBeDefined(); + if (isChrome) { + // Slicing '[object {type}]' -> '{type}' + expect(writer.toString().slice(8, -1)).toEqual("FileWriter"); + } + else { + expect(writer instanceof FileWriter).toBe(true); + } + + // cleanup + deleteEntry(testFile.name, done); + }; + // create a new file entry to kick off it + root.getFile(fileName, { + create : true + }, function (fileEntry) { + testFile = fileEntry; + fileEntry.createWriter(testWriter, failed.bind(null, done, 'fileEntry.createWriter - Error creating Writer from entry')); + }, failed.bind(null, done, 'root.getFile - Error creating file : ' + fileName)); + }); + it("file.spec.43 file should return a File object", function (done) { + var fileName = "fe.file", + newFile, + testFile = function (file) { + expect(file).toBeDefined(); + if (isChrome) { + // Slicing '[object {type}]' -> '{type}' + expect(file.toString().slice(8, -1)).toEqual("File"); + } + else { + expect(file instanceof File).toBe(true); + } + + // cleanup + deleteEntry(newFile.name, done); + }; + // create a new file entry to kick off it + root.getFile(fileName, { + create : true + }, function (fileEntry) { + newFile = fileEntry; + fileEntry.file(testFile, failed.bind(null, done, 'fileEntry.file - Error reading file using fileEntry: ' + fileEntry.name)); + }, failed.bind(null, done, 'root.getFile - Error creating file : ' + fileName)); + }); + it("file.spec.44 file: on File that has been removed", function (done) { + var fileName = "fe.no.file"; + // create a new file entry to kick off it + root.getFile(fileName, { + create : true + }, function (fileEntry) { + fileEntry.remove(function () { + fileEntry.file(succeed.bind(null, done, 'fileEntry.file - Unexpected success callback, file it should not be created from removed entry'), function (error) { + expect(error).toBeDefined(); + expect(error).toBeFileError(FileError.NOT_FOUND_ERR); + done(); + }); + }, failed.bind(null, done, 'fileEntry.remove - Error removing entry : ' + fileName)); + }, failed.bind(null, done, 'root.getFile - Error creating file : ' + fileName)); + }); + }); + //FileEntry + describe('Entry', function () { + it("file.spec.45 Entry object", function (done) { + var fileName = "entry", + fullPath = joinURL(root.fullPath, fileName), + winEntry = function (entry) { + expect(entry).toBeDefined(); + expect(entry.isFile).toBe(true); + expect(entry.isDirectory).toBe(false); + expect(entry.name).toCanonicallyMatch(fileName); + expect(entry.fullPath).toCanonicallyMatch(fullPath); + expect(typeof entry.getMetadata).toBe('function'); + expect(typeof entry.setMetadata).toBe('function'); + expect(typeof entry.moveTo).toBe('function'); + expect(typeof entry.copyTo).toBe('function'); + expect(typeof entry.toURL).toBe('function'); + expect(typeof entry.remove).toBe('function'); + expect(typeof entry.getParent).toBe('function'); + expect(typeof entry.createWriter).toBe('function'); + expect(typeof entry.file).toBe('function'); + // Clean up + deleteEntry(fileName, done); + }; + // create a new file entry + createFile(fileName, winEntry, failed.bind(null, done, 'createFile - Error creating file : ' + fileName)); + }); + it("file.spec.46 Entry.getMetadata on file", function (done) { + var fileName = "entry.metadata.file"; + // create a new file entry + createFile(fileName, function (entry) { + entry.getMetadata(function (metadata) { + expect(metadata).toBeDefined(); + expect(metadata.modificationTime instanceof Date).toBe(true); + expect(typeof metadata.size).toBe("number"); + // cleanup + deleteEntry(fileName, done); + }, failed.bind(null, done, 'entry.getMetadata - Error getting metadata from entry : ' + fileName)); + }, failed.bind(null, done, 'createFile - Error creating file : ' + fileName)); + }); + it("file.spec.47 Entry.getMetadata on directory", function (done) { + if (isIndexedDBShim) { + /* Does not support metadata for directories (Firefox, IE) */ + pending(); + } + + var dirName = "entry.metadata.dir"; + // create a new directory entry + createDirectory(dirName, function (entry) { + entry.getMetadata(function (metadata) { + expect(metadata).toBeDefined(); + expect(metadata.modificationTime instanceof Date).toBe(true); + expect(typeof metadata.size).toBe("number"); + expect(metadata.size).toBe(0); + // cleanup + deleteEntry(dirName, done); + }, failed.bind(null, done, 'entry.getMetadata - Error getting metadata from entry : ' + dirName)); + }, failed.bind(null, done, 'createDirectory - Error creating directory : ' + dirName)); + }); + it("file.spec.48 Entry.getParent on file in root file system", function (done) { + var fileName = "entry.parent.file", + rootPath = root.fullPath; + // create a new file entry + createFile(fileName, function (entry) { + entry.getParent(function (parent) { + expect(parent).toBeDefined(); + expect(parent.fullPath).toCanonicallyMatch(rootPath); + // cleanup + deleteEntry(fileName, done); + }, failed.bind(null, done, 'entry.getParent - Error getting parent directory of file : ' + fileName)); + }, failed.bind(null, done, 'createFile - Error creating file : ' + fileName)); + }); + it("file.spec.49 Entry.getParent on directory in root file system", function (done) { + var dirName = "entry.parent.dir", + rootPath = root.fullPath; + // create a new directory entry + createDirectory(dirName, function (entry) { + entry.getParent(function (parent) { + expect(parent).toBeDefined(); + expect(parent.fullPath).toCanonicallyMatch(rootPath); + // cleanup + deleteEntry(dirName, done); + }, failed.bind(null, done, 'entry.getParent - Error getting parent directory of directory : ' + dirName)); + }, failed.bind(null, done, 'createDirectory - Error creating directory : ' + dirName)); + }); + it("file.spec.50 Entry.getParent on root file system", function (done) { + var rootPath = root.fullPath, + winParent = function (parent) { + expect(parent).toBeDefined(); + expect(parent.fullPath).toCanonicallyMatch(rootPath); + done(); + }; + // create a new directory entry + root.getParent(winParent, failed.bind(null, done, 'root.getParent - Error getting parent directory of root')); + }); + it("file.spec.51 Entry.toURL on file", function (done) { + var fileName = "entry.uri.file", + rootPath = root.fullPath, + winURI = function (entry) { + var uri = entry.toURL(); + expect(uri).toBeDefined(); + expect(uri.indexOf(rootPath)).not.toBe(-1); + // cleanup + deleteEntry(fileName, done); + }; + // create a new file entry + createFile(fileName, winURI, failed.bind(null, done, 'createFile - Error creating file : ' + fileName)); + }); + it("file.spec.52 Entry.toURL on directory", function (done) { + var dirName_1 = "num 1", + dirName_2 = "num 2", + rootPath = root.fullPath; + createDirectory(dirName_1, function (entry) { + entry.getDirectory(dirName_2, { + create : true + }, function (entryFile) { + var uri = entryFile.toURL(); + expect(uri).toBeDefined(); + expect(uri).toContain('/num%201/num%202/'); + expect(uri.indexOf(rootPath)).not.toBe(-1); + // cleanup + deleteEntry(dirName_1, done); + }, failed.bind(null, done, 'entry.getDirectory - Error creating directory : ' + dirName_2)); + }, failed.bind(null, done, 'createDirectory - Error creating directory : ' + dirName_1)); + }); + it("file.spec.53 Entry.remove on file", function (done) { + var fileName = "entr .rm.file"; + // create a new file entry + createFile(fileName, function (entry) { + expect(entry).toBeDefined(); + entry.remove(function () { + root.getFile(fileName, null, succeed.bind(null, done, 'root.getFile - Unexpected success callback, it should not get deleted file : ' + fileName), function (error) { + expect(error).toBeDefined(); + expect(error).toBeFileError(FileError.NOT_FOUND_ERR); + // cleanup + deleteEntry(fileName, done); + }); + }, failed.bind(null, done, 'entry.remove - Error removing entry : ' + fileName)); + }, failed.bind(null, done, 'createFile - Error creating file : ' + fileName)); + }); + it("file.spec.53.1 Entry.remove on filename with #s", function (done) { + var fileName = "entry.#rm#.file"; + // create a new file entry + createFile(fileName, function (entry) { + expect(entry).toBeDefined(); + entry.remove(function () { + root.getFile(fileName, null, succeed.bind(null, done, 'root.getFile - Unexpected success callback, it should not get deleted file : ' + fileName), function (error) { + expect(error).toBeDefined(); + expect(error).toBeFileError(FileError.NOT_FOUND_ERR); + // cleanup + deleteEntry(fileName, done); + }); + }, failed.bind(null, done, 'entry.remove - Error removing entry : ' + fileName)); + }, failed.bind(null, done, 'createFile - Error creating file : ' + fileName)); + }); + it("file.spec.54 remove on empty directory", function (done) { + var dirName = "entry.rm.dir"; + // create a new directory entry + createDirectory(dirName, function (entry) { + expect(entry).toBeDefined(); + entry.remove(function () { + root.getDirectory(dirName, null, succeed.bind(null, done, 'root.getDirectory - Unexpected success callback, it should not get deleted directory : ' + dirName), function (error) { + expect(error).toBeDefined(); + expect(error).toBeFileError(FileError.NOT_FOUND_ERR); + // cleanup + deleteEntry(dirName, done); + }); + }, failed.bind(null, done, 'entry.remove - Error removing entry : ' + dirName)); + }, failed.bind(null, done, 'createDirectory - Error creating directory : ' + dirName)); + }); + it("file.spec.55 remove on non-empty directory", function (done) { + if (isIndexedDBShim) { + /* Both Entry.remove and directoryEntry.removeRecursively don't fail when removing + non-empty directories - directories being removed are cleaned + along with contents instead (Firefox, IE)*/ + pending(); + } + + var dirName = "ent y.rm.dir.not.empty", + fileName = "re ove.txt", + fullPath = joinURL(root.fullPath, dirName); + // create a new directory entry + createDirectory(dirName, function (entry) { + entry.getFile(fileName, { + create : true + }, function (fileEntry) { + entry.remove(succeed.bind(null, done, 'entry.remove - Unexpected success callback, it should not remove a directory that contains files : ' + dirName), function (error) { + expect(error).toBeDefined(); + expect(error).toBeFileError(FileError.INVALID_MODIFICATION_ERR); + root.getDirectory(dirName, null, function (entry) { + expect(entry).toBeDefined(); + expect(entry.fullPath).toCanonicallyMatch(fullPath); + // cleanup + deleteEntry(dirName, done); + }, failed.bind(null, done, 'root.getDirectory - Error getting directory : ' + dirName)); + }); + }, failed.bind(null, done, 'entry.getFile - Error creating file : ' + fileName + ' inside of ' + dirName)); + }, failed.bind(null, done, 'createDirectory - Error creating directory : ' + dirName)); + }); + it("file.spec.56 remove on root file system", function (done) { + + // remove entry that doesn't exist + root.remove(succeed.bind(null, done, 'entry.remove - Unexpected success callback, it should not remove entry that it does not exists'), function (error) { + expect(error).toBeDefined(); + if (isChrome) { + /*INVALID_MODIFICATION_ERR (code: 9) is thrown instead of + NO_MODIFICATION_ALLOWED_ERR(code: 6) on trying to call removeRecursively + on the root file system.*/ + expect(error).toBeFileError(FileError.INVALID_MODIFICATION_ERR); + } else { + expect(error).toBeFileError(FileError.NO_MODIFICATION_ALLOWED_ERR); + } + done(); + }); + }); + it("file.spec.57 copyTo: file", function (done) { + var file1 = "entry copy.file1", + file2 = "entry copy.file2", + fullPath = joinURL(root.fullPath, file2); + // create a new file entry to kick off it + deleteEntry(file2, function () { + createFile(file1, function (fileEntry) { + // copy file1 to file2 + fileEntry.copyTo(root, file2, function (entry) { + expect(entry).toBeDefined(); + expect(entry.isFile).toBe(true); + expect(entry.isDirectory).toBe(false); + expect(entry.fullPath).toCanonicallyMatch(fullPath); + expect(entry.name).toCanonicallyMatch(file2); + root.getFile(file2, { + create : false + }, function (entry2) { + expect(entry2).toBeDefined(); + expect(entry2.isFile).toBe(true); + expect(entry2.isDirectory).toBe(false); + expect(entry2.fullPath).toCanonicallyMatch(fullPath); + expect(entry2.name).toCanonicallyMatch(file2); + // cleanup + deleteEntry(file1, function () { + deleteEntry(file2, done); + }); + }, failed.bind(null, done, 'root.getFile - Error getting copied file : ' + file2)); + }, failed.bind(null, done, 'fileEntry.copyTo - Error copying file : ' + file2)); + }, failed.bind(null, done, 'createFile - Error creating file : ' + file1)); + }, failed.bind(null, done, 'deleteEntry - Error removing file : ' + file2)); + }); + it("file.spec.58 copyTo: file onto itself", function (done) { + var file1 = "entry.copy.fos.file1"; + // create a new file entry to kick off it + createFile(file1, function (entry) { + // copy file1 onto itself + entry.copyTo(root, null, succeed.bind(null, done, 'entry.copyTo - Unexpected success callback, it should not copy a null file'), function (error) { + expect(error).toBeDefined(); + expect(error).toBeFileError(FileError.INVALID_MODIFICATION_ERR); + // cleanup + deleteEntry(file1, done); + }); + }, failed.bind(null, done, 'createFile - Error creating file : ' + file1)); + }); + it("file.spec.59 copyTo: directory", function (done) { + if (isIndexedDBShim) { + /* `copyTo` and `moveTo` functions do not support directories (Firefox, IE) */ + pending(); + } + + var file1 = "file1", + srcDir = "entry.copy.srcDir", + dstDir = "entry.copy.dstDir", + dstPath = joinURL(root.fullPath, dstDir), + filePath = joinURL(dstPath, file1); + // create a new directory entry to kick off it + deleteEntry(dstDir, function () { + createDirectory(srcDir, function (directory) { + // create a file within new directory + directory.getFile(file1, { + create : true + }, function () { + directory.copyTo(root, dstDir, function (directory) { + expect(directory).toBeDefined(); + expect(directory.isFile).toBe(false); + expect(directory.isDirectory).toBe(true); + expect(directory.fullPath).toCanonicallyMatch(dstPath); + expect(directory.name).toCanonicallyMatch(dstDir); + root.getDirectory(dstDir, { + create : false + }, function (dirEntry) { + expect(dirEntry).toBeDefined(); + expect(dirEntry.isFile).toBe(false); + expect(dirEntry.isDirectory).toBe(true); + expect(dirEntry.fullPath).toCanonicallyMatch(dstPath); + expect(dirEntry.name).toCanonicallyMatch(dstDir); + dirEntry.getFile(file1, { + create : false + }, function (fileEntry) { + expect(fileEntry).toBeDefined(); + expect(fileEntry.isFile).toBe(true); + expect(fileEntry.isDirectory).toBe(false); + expect(fileEntry.fullPath).toCanonicallyMatch(filePath); + expect(fileEntry.name).toCanonicallyMatch(file1); + // cleanup + deleteEntry(srcDir, function () { + deleteEntry(dstDir, done); + }); + }, failed.bind(null, done, 'dirEntry.getFile - Error getting file : ' + file1)); + }, failed.bind(null, done, 'root.getDirectory - Error getting copied directory : ' + dstDir)); + }, failed.bind(null, done, 'directory.copyTo - Error copying directory : ' + srcDir + ' to :' + dstDir)); + }, failed.bind(null, done, 'directory.getFile - Error creating file : ' + file1)); + }, failed.bind(null, done, 'createDirectory - Error creating directory : ' + srcDir)); + }, failed.bind(null, done, 'deleteEntry - Error removing directory : ' + dstDir)); + }); + it("file.spec.60 copyTo: directory to backup at same root directory", function (done) { + if (isIndexedDBShim) { + /* `copyTo` and `moveTo` functions do not support directories (Firefox, IE) */ + pending(); + } + + var file1 = "file1", + srcDir = "entry.copy srcDirSame", + dstDir = "entry.copy srcDirSame-backup", + dstPath = joinURL(root.fullPath, dstDir), + filePath = joinURL(dstPath, file1); + // create a new directory entry to kick off it + deleteEntry(dstDir, function () { + createDirectory(srcDir, function (directory) { + directory.getFile(file1, { + create : true + }, function () { + directory.copyTo(root, dstDir, function (directory) { + expect(directory).toBeDefined(); + expect(directory.isFile).toBe(false); + expect(directory.isDirectory).toBe(true); + expect(directory.fullPath).toCanonicallyMatch(dstPath); + expect(directory.name).toCanonicallyMatch(dstDir); + root.getDirectory(dstDir, { + create : false + }, function (dirEntry) { + expect(dirEntry).toBeDefined(); + expect(dirEntry.isFile).toBe(false); + expect(dirEntry.isDirectory).toBe(true); + expect(dirEntry.fullPath).toCanonicallyMatch(dstPath); + expect(dirEntry.name).toCanonicallyMatch(dstDir); + dirEntry.getFile(file1, { + create : false + }, function (fileEntry) { + expect(fileEntry).toBeDefined(); + expect(fileEntry.isFile).toBe(true); + expect(fileEntry.isDirectory).toBe(false); + expect(fileEntry.fullPath).toCanonicallyMatch(filePath); + expect(fileEntry.name).toCanonicallyMatch(file1); + // cleanup + deleteEntry(srcDir, function () { + deleteEntry(dstDir, done); + }); + }, failed.bind(null, done, 'dirEntry.getFile - Error getting file : ' + file1)); + }, failed.bind(null, done, 'root.getDirectory - Error getting copied directory : ' + dstDir)); + }, failed.bind(null, done, 'directory.copyTo - Error copying directory : ' + srcDir + ' to :' + dstDir)); + }, failed.bind(null, done, 'directory.getFile - Error creating file : ' + file1)); + }, failed.bind(null, done, 'createDirectory - Error creating directory : ' + srcDir)); + }, failed.bind(null, done, 'deleteEntry - Error removing directory : ' + dstDir)); + }); + it("file.spec.61 copyTo: directory onto itself", function (done) { + if (isIndexedDBShim) { + /* `copyTo` and `moveTo` functions do not support directories (Firefox, IE) */ + pending(); + } + + var file1 = "file1", + srcDir = "entry.copy.dos.srcDir", + srcPath = joinURL(root.fullPath, srcDir), + filePath = joinURL(srcPath, file1); + // create a new directory entry to kick off it + createDirectory(srcDir, function (directory) { + // create a file within new directory + directory.getFile(file1, { + create : true + }, function (fileEntry) { + // copy srcDir onto itself + directory.copyTo(root, null, succeed.bind(null, done, 'directory.copyTo - Unexpected success callback, it should not copy file: ' + srcDir + ' to a null destination'), function (error) { + expect(error).toBeDefined(); + expect(error).toBeFileError(FileError.INVALID_MODIFICATION_ERR); + root.getDirectory(srcDir, { + create : false + }, function (dirEntry) { + expect(dirEntry).toBeDefined(); + expect(dirEntry.fullPath).toCanonicallyMatch(srcPath); + dirEntry.getFile(file1, { + create : false + }, function (fileEntry) { + expect(fileEntry).toBeDefined(); + expect(fileEntry.fullPath).toCanonicallyMatch(filePath); + // cleanup + deleteEntry(srcDir, done); + }, failed.bind(null, done, 'dirEntry.getFile - Error getting file : ' + file1)); + }, failed.bind(null, done, 'root.getDirectory - Error getting directory : ' + srcDir)); + }); + }, failed.bind(null, done, 'directory.getFile - Error creating file : ' + file1)); + }, failed.bind(null, done, 'createDirectory - Error creating directory : ' + srcDir)); + }); + it("file.spec.62 copyTo: directory into itself", function (done) { + if (isIndexedDBShim) { + /* `copyTo` and `moveTo` functions do not support directories (Firefox, IE) */ + pending(); + } + + var srcDir = "entry.copy.dis.srcDir", + dstDir = "entry.copy.dis.dstDir", + srcPath = joinURL(root.fullPath, srcDir); + // create a new directory entry to kick off it + createDirectory(srcDir, function (directory) { + // copy source directory into itself + directory.copyTo(directory, dstDir, succeed.bind(null, done, 'directory.copyTo - Unexpected success callback, it should not copy a directory ' + srcDir + ' into itself'), function (error) { + expect(error).toBeDefined(); + expect(error).toBeFileError(FileError.INVALID_MODIFICATION_ERR); + root.getDirectory(srcDir, { + create : false + }, function (dirEntry) { + // returning confirms existence so just check fullPath entry + expect(dirEntry).toBeDefined(); + expect(dirEntry.fullPath).toCanonicallyMatch(srcPath); + // cleanup + deleteEntry(srcDir, done); + }, failed.bind(null, done, 'root.getDirectory - Error getting directory : ' + srcDir)); + }); + }, failed.bind(null, done, 'createDirectory - Error creating directory : ' + srcDir)); + }); + it("file.spec.63 copyTo: directory that does not exist", function (done) { + var file1 = "entry.copy.dnf.file1", + dirName = 'dir-foo'; + createFile(file1, function (fileEntry) { + createDirectory(dirName, function (dirEntry) { + dirEntry.remove(function () { + fileEntry.copyTo(dirEntry, null, succeed.bind(null, done, 'fileEntry.copyTo - Unexpected success callback, it should not copy a file ' + file1 + ' into a removed directory'), function (error) { + expect(error).toBeDefined(); + expect(error).toBeFileError(FileError.NOT_FOUND_ERR); + done(); + }); + }, failed.bind(null, done, 'dirEntry.remove - Error removing directory : ' + dirName)); + }, failed.bind(null, done, 'createDirectory - Error creating directory : ' + dirName)); + }, failed.bind(null, done, 'createFile - Error creating file : ' + file1)); + }); + it("file.spec.64 copyTo: invalid target name", function (done) { + if (isBrowser) { + /*The plugin does not follow ["8.3 Naming restrictions"] + (http://www.w3.org/TR/2011/WD-file-system-api-20110419/#naming-restrictions*/ + pending(); + } + + var file1 = "entry.copy.itn.file1", + file2 = "bad:file:name"; + // create a new file entry + createFile(file1, function (entry) { + // copy file1 to file2 + entry.copyTo(root, file2, succeed.bind(null, done, 'entry.copyTo - Unexpected success callback, it should not copy a file ' + file1 + ' to an invalid file name: ' + file2), function (error) { + expect(error).toBeDefined(); + expect(error).toBeFileError(FileError.ENCODING_ERR); + // cleanup + deleteEntry(file1, done); + }); + }, failed.bind(null, done, 'createFile - Error creating file : ' + file1)); + }); + it("file.spec.65 moveTo: file to same parent", function (done) { + var file1 = "entry.move.fsp.file1", + file2 = "entry.move.fsp.file2", + dstPath = joinURL(root.fullPath, file2); + // create a new file entry to kick off it + createFile(file1, function (entry) { + // move file1 to file2 + entry.moveTo(root, file2, function (entry) { + expect(entry).toBeDefined(); + expect(entry.isFile).toBe(true); + expect(entry.isDirectory).toBe(false); + expect(entry.fullPath).toCanonicallyMatch(dstPath); + expect(entry.name).toCanonicallyMatch(file2); + root.getFile(file2, { + create : false + }, function (fileEntry) { + expect(fileEntry).toBeDefined(); + expect(fileEntry.fullPath).toCanonicallyMatch(dstPath); + root.getFile(file1, { + create : false + }, succeed.bind(null, done, 'root.getFile - Unexpected success callback, it should not get invalid or moved file: ' + file1), function (error) { + //expect(navigator.fileMgr.testFileExists(srcPath) === false, "original file should not exist."); + expect(error).toBeDefined(); + expect(error).toBeFileError(FileError.NOT_FOUND_ERR); + // cleanup + deleteEntry(file1, function () { + deleteEntry(file2, done); + }); + }); + }, failed.bind(null, done, 'root.getFile - Error getting file : ' + file2)); + }, failed.bind(null, done, 'entry.moveTo - Error moving file : ' + file1 + ' to root as: ' + file2)); + }, failed.bind(null, done, 'createFile - Error creating file : ' + file1)); + }); + it("file.spec.66 moveTo: file to new parent", function (done) { + var file1 = "entry.move.fnp.file1", + dir = "entry.move.fnp.dir", + dstPath = joinURL(joinURL(root.fullPath, dir), file1); + // ensure destination directory is cleaned up first + deleteEntry(dir, function () { + // create a new file entry to kick off it + createFile(file1, function (entry) { + // create a parent directory to move file to + root.getDirectory(dir, { + create : true + }, function (directory) { + // move file1 to new directory + // move the file + entry.moveTo(directory, null, function (entry) { + expect(entry).toBeDefined(); + expect(entry.isFile).toBe(true); + expect(entry.isDirectory).toBe(false); + expect(entry.fullPath).toCanonicallyMatch(dstPath); + expect(entry.name).toCanonicallyMatch(file1); + // test the moved file exists + directory.getFile(file1, { + create : false + }, function (fileEntry) { + expect(fileEntry).toBeDefined(); + expect(fileEntry.fullPath).toCanonicallyMatch(dstPath); + root.getFile(file1, { + create : false + }, succeed.bind(null, done, 'root.getFile - Unexpected success callback, it should not get invalid or moved file: ' + file1), function (error) { + expect(error).toBeDefined(); + expect(error).toBeFileError(FileError.NOT_FOUND_ERR); + // cleanup + deleteEntry(file1, function () { + deleteEntry(dir, done); + }); + }); + }, failed.bind(null, done, 'directory.getFile - Error getting file : ' + file1 + ' from: ' + dir)); + }, failed.bind(null, done, 'entry.moveTo - Error moving file : ' + file1 + ' to: ' + dir + ' with the same name')); + }, failed.bind(null, done, 'root.getDirectory - Error creating directory : ' + dir)); + }, failed.bind(null, done, 'createFile - Error creating file : ' + file1)); + }, failed.bind(null, done, 'deleteEntry - Error removing directory : ' + dir)); + }); + it("file.spec.67 moveTo: directory to same parent", function (done) { + if (isIndexedDBShim) { + /* `copyTo` and `moveTo` functions do not support directories (Firefox, IE) */ + pending(); + } + + var file1 = "file1", + srcDir = "entry.move.dsp.srcDir", + dstDir = "entry.move.dsp.dstDir", + dstPath = joinURL(root.fullPath, dstDir), + filePath = joinURL(dstPath, file1); + // ensure destination directory is cleaned up before it + deleteEntry(dstDir, function () { + // create a new directory entry to kick off it + createDirectory(srcDir, function (directory) { + // create a file within directory + directory.getFile(file1, { + create : true + }, function () { + // move srcDir to dstDir + directory.moveTo(root, dstDir, function (directory) { + expect(directory).toBeDefined(); + expect(directory.isFile).toBe(false); + expect(directory.isDirectory).toBe(true); + expect(directory.fullPath).toCanonicallyMatch(dstPath); + expect(directory.name).toCanonicallyMatch(dstDir); + // test that moved file exists in destination dir + directory.getFile(file1, { + create : false + }, function (fileEntry) { + expect(fileEntry).toBeDefined(); + expect(fileEntry.fullPath).toCanonicallyMatch(filePath); + // check that the moved file no longer exists in original dir + root.getFile(file1, { + create : false + }, succeed.bind(null, done, 'directory.getFile - Unexpected success callback, it should not get invalid or moved file: ' + file1), function (error) { + expect(error).toBeDefined(); + expect(error).toBeFileError(FileError.NOT_FOUND_ERR); + // cleanup + deleteEntry(srcDir, function() { + deleteEntry(dstDir, done); + }); + }); + }, failed.bind(null, done, 'directory.getFile - Error getting file : ' + file1 + ' from: ' + srcDir)); + }, failed.bind(null, done, 'entry.moveTo - Error moving directory : ' + srcDir + ' to root as: ' + dstDir)); + }, failed.bind(null, done, 'directory.getFile - Error creating file : ' + file1)); + }, failed.bind(null, done, 'createDirectory - Error creating directory : ' + srcDir)); + }, failed.bind(null, done, 'deleteEntry - Error removing directory : ' + dstDir)); + }); + it("file.spec.68 moveTo: directory to same parent with same name", function (done) { + if (isIndexedDBShim) { + /* `copyTo` and `moveTo` functions do not support directories (Firefox, IE) */ + pending(); + } + + var file1 = "file1", + srcDir = "entry.move.dsp.srcDir", + dstDir = "entry.move.dsp.srcDir-backup", + dstPath = joinURL(root.fullPath, dstDir), + filePath = joinURL(dstPath, file1); + // ensure destination directory is cleaned up before it + deleteEntry(dstDir, function () { + // create a new directory entry to kick off it + createDirectory(srcDir, function (directory) { + // create a file within directory + directory.getFile(file1, { + create : true + }, function () { + // move srcDir to dstDir + directory.moveTo(root, dstDir, function (directory) { + expect(directory).toBeDefined(); + expect(directory.isFile).toBe(false); + expect(directory.isDirectory).toBe(true); + expect(directory.fullPath).toCanonicallyMatch(dstPath); + expect(directory.name).toCanonicallyMatch(dstDir); + // check that moved file exists in destination dir + directory.getFile(file1, { + create : false + }, function (fileEntry) { + expect(fileEntry).toBeDefined(); + expect(fileEntry.fullPath).toCanonicallyMatch(filePath); + // check that the moved file no longer exists in original dir + root.getFile(file1, { + create : false + }, succeed.bind(null, done, 'directory.getFile - Unexpected success callback, it should not get invalid or moved file: ' + file1), function (error) { + expect(error).toBeDefined(); + expect(error).toBeFileError(FileError.NOT_FOUND_ERR); + // cleanup + deleteEntry(srcDir, function() { + deleteEntry(dstDir, done); + }); + }); + }, failed.bind(null, done, 'directory.getFile - Error getting file : ' + file1 + ' from: ' + srcDir)); + }, failed.bind(null, done, 'entry.moveTo - Error moving directory : ' + srcDir + ' to root as: ' + dstDir)); + }, failed.bind(null, done, 'directory.getFile - Error creating file : ' + file1)); + }, failed.bind(null, done, 'createDirectory - Error creating directory : ' + srcDir)); + }, failed.bind(null, done, 'deleteEntry - Error removing directory : ' + dstDir)); + }); + it("file.spec.69 moveTo: directory to new parent", function (done) { + if (isIndexedDBShim) { + /* `copyTo` and `moveTo` functions do not support directories (Firefox, IE) */ + pending(); + } + + var file1 = "file1", + srcDir = "entry.move.dnp.srcDir", + dstDir = "entry.move.dnp.dstDir", + dstPath = joinURL(root.fullPath, dstDir), + filePath = joinURL(dstPath, file1); + // ensure destination directory is cleaned up before it + deleteEntry(dstDir, function () { + // create a new directory entry to kick off it + createDirectory(srcDir, function (directory) { + // create a file within directory + directory.getFile(file1, { + create : true + }, function () { + // move srcDir to dstDir + directory.moveTo(root, dstDir, function (dirEntry) { + expect(dirEntry).toBeDefined(); + expect(dirEntry.isFile).toBe(false); + expect(dirEntry.isDirectory).toBe(true); + expect(dirEntry.fullPath).toCanonicallyMatch(dstPath); + expect(dirEntry.name).toCanonicallyMatch(dstDir); + // test that moved file exists in destination dir + dirEntry.getFile(file1, { + create : false + }, function (fileEntry) { + expect(fileEntry).toBeDefined(); + expect(fileEntry.fullPath).toCanonicallyMatch(filePath); + // test that the moved file no longer exists in original dir + root.getFile(file1, { + create : false + }, succeed.bind(null, done, 'root.getFile - Unexpected success callback, it should not get invalid or moved file: ' + file1), function (error) { + expect(error).toBeDefined(); + expect(error).toBeFileError(FileError.NOT_FOUND_ERR); + // cleanup + deleteEntry(srcDir, function() { + deleteEntry(dstDir, done); + }); + }); + }, failed.bind(null, done, 'directory.getFile - Error getting file : ' + file1 + ' from: ' + dstDir)); + }, failed.bind(null, done, 'directory.moveTo - Error moving directory : ' + srcDir + ' to root as: ' + dstDir)); + }, failed.bind(null, done, 'directory.getFile - Error creating file : ' + file1)); + }, failed.bind(null, done, 'createDirectory - Error creating directory : ' + srcDir)); + }, failed.bind(null, done, 'deleteEntry - Error removing directory : ' + dstDir)); + }); + + it("file.spec.131 moveTo: directories tree to new parent", function (done) { + if (isIndexedDBShim) { + /* `copyTo` and `moveTo` functions do not support directories (Firefox, IE) */ + pending(); + } + + var srcDir = "entry.move.dnp.srcDir"; + var srcDirNestedFirst = "entry.move.dnp.srcDir.Nested1"; + var srcDirNestedSecond = "entry.move.dnp.srcDir.Nested2"; + var dstDir = "entry.move.dnp.dstDir"; + + createDirectory(dstDir, function (dstDirectory) { + createDirectory(srcDir, function (srcDirectory) { + srcDirectory.getDirectory(srcDirNestedFirst, { create: true }, function () { + srcDirectory.getDirectory(srcDirNestedSecond, { create: true }, function () { + srcDirectory.moveTo(dstDirectory, srcDir, function successMove(transferredDirectory) { + var directoryReader = transferredDirectory.createReader(); + directoryReader.readEntries(function successRead(entries) { + expect(entries.length).toBe(2); + expect(entries[0].name).toBe(srcDirNestedFirst); + expect(entries[1].name).toBe(srcDirNestedSecond); + deleteEntry(dstDir, done); + }, failed.bind(null, done, 'Error getting entries from: ' + transferredDirectory)); + }, failed.bind(null, done, 'directory.moveTo - Error moving directory : ' + srcDir + ' to root as: ' + dstDir)); + }, failed.bind(null, done, 'directory.getDirectory - Error creating directory : ' + srcDirNestedSecond)); + }, failed.bind(null, done, 'directory.getDirectory - Error creating directory : ' + srcDirNestedFirst)); + }, failed.bind(null, done, 'createDirectory - Error creating source directory : ' + srcDir)); + }, failed.bind(null, done, 'createDirectory - Error creating dest directory : ' + dstDir)); + }); + + it("file.spec.70 moveTo: directory onto itself", function (done) { + if (isIndexedDBShim) { + /* `copyTo` and `moveTo` functions do not support directories (Firefox, IE) */ + pending(); + } + + var file1 = "file1", + srcDir = "entry.move.dos.srcDir", + srcPath = joinURL(root.fullPath, srcDir), + filePath = joinURL(srcPath, file1); + // create a new directory entry to kick off it + createDirectory(srcDir, function (directory) { + // create a file within new directory + directory.getFile(file1, { + create : true + }, function () { + // move srcDir onto itself + directory.moveTo(root, null, succeed.bind(null, done, 'directory.moveTo - Unexpected success callback, it should not move directory to invalid path'), function (error) { + expect(error).toBeDefined(); + expect(error).toBeFileError(FileError.INVALID_MODIFICATION_ERR); + // test that original dir still exists + root.getDirectory(srcDir, { + create : false + }, function (dirEntry) { + // returning confirms existence so just check fullPath entry + expect(dirEntry).toBeDefined(); + expect(dirEntry.fullPath).toCanonicallyMatch(srcPath); + dirEntry.getFile(file1, { + create : false + }, function (fileEntry) { + expect(fileEntry).toBeDefined(); + expect(fileEntry.fullPath).toCanonicallyMatch(filePath); + // cleanup + deleteEntry(srcDir, done); + }, failed.bind(null, done, 'dirEntry.getFile - Error getting file : ' + file1 + ' from: ' + srcDir)); + }, failed.bind(null, done, 'root.getDirectory - Error getting directory : ' + srcDir)); + }); + }, failed.bind(null, done, 'directory.getFile - Error creating file : ' + file1)); + }, failed.bind(null, done, 'createDirectory - Error creating directory : ' + srcDir)); + }); + it("file.spec.71 moveTo: directory into itself", function (done) { + if (isIndexedDBShim) { + /* `copyTo` and `moveTo` functions do not support directories (Firefox, IE) */ + pending(); + } + + var srcDir = "entry.move.dis.srcDir", + dstDir = "entry.move.dis.dstDir", + srcPath = joinURL(root.fullPath, srcDir); + // create a new directory entry to kick off it + createDirectory(srcDir, function (directory) { + // move source directory into itself + directory.moveTo(directory, dstDir, succeed.bind(null, done, 'directory.moveTo - Unexpected success callback, it should not move a directory into itself: ' + srcDir), function (error) { + expect(error).toBeDefined(); + expect(error).toBeFileError(FileError.INVALID_MODIFICATION_ERR); + // make sure original directory still exists + root.getDirectory(srcDir, { + create : false + }, function (entry) { + expect(entry).toBeDefined(); + expect(entry.fullPath).toCanonicallyMatch(srcPath); + // cleanup + deleteEntry(srcDir, done); + }, failed.bind(null, done, 'root.getDirectory - Error getting directory, making sure that original directory still exists: ' + srcDir)); + }); + }, failed.bind(null, done, 'createDirectory - Error creating directory : ' + srcDir)); + }); + it("file.spec.130 moveTo: directory into similar directory", function (done) { + if (isIndexedDBShim) { + /* `copyTo` and `moveTo` functions do not support directories (Firefox, IE) */ + pending(); + } + + var srcDir = "entry.move.dis.srcDir", + dstDir = "entry.move.dis.srcDir-backup"; + // create a new directory entry to kick off it + createDirectory(srcDir, function (srcDirEntry) { + deleteEntry(dstDir, function () { + createDirectory(dstDir, function (dstDirEntry) { + // move source directory into itself + srcDirEntry.moveTo(dstDirEntry, 'file', function (newDirEntry) { + expect(newDirEntry).toBeDefined(); + deleteEntry(dstDir, done); + }, failed.bind(null, done, 'directory.moveTo - Error moving a directory into a similarly-named directory: ' + srcDir)); + }, failed.bind(null, done, 'createDirectory - Error creating directory : ' + dstDir)); + }, failed.bind(null, done, 'deleteEntry - Error deleting directory : ' + dstDir)); + }, failed.bind(null, done, 'createDirectory - Error creating directory : ' + srcDir)); + }); + it("file.spec.72 moveTo: file onto itself", function (done) { + var file1 = "entry.move.fos.file1", + filePath = joinURL(root.fullPath, file1); + // create a new file entry to kick off it + createFile(file1, function (entry) { + // move file1 onto itself + entry.moveTo(root, null, succeed.bind(null, done, 'entry.moveTo - Unexpected success callback, it should not move a file: ' + file1 + ' into the same parent'), function (error) { + expect(error).toBeDefined(); + expect(error).toBeFileError(FileError.INVALID_MODIFICATION_ERR); + //test that original file still exists + root.getFile(file1, { + create : false + }, function (fileEntry) { + expect(fileEntry).toBeDefined(); + expect(fileEntry.fullPath).toCanonicallyMatch(filePath); + // cleanup + deleteEntry(file1, done); + }, failed.bind(null, done, 'root.getFile - Error getting file, making sure that original file still exists: ' + file1)); + }); + }, failed.bind(null, done, 'createFile - Error creating file : ' + file1)); + }); + it("file.spec.73 moveTo: file onto existing directory", function (done) { + var file1 = "entry.move.fod.file1", + dstDir = "entry.move.fod.dstDir", + subDir = "subDir", + dirPath = joinURL(joinURL(root.fullPath, dstDir), subDir), + filePath = joinURL(root.fullPath, file1); + // ensure destination directory is cleaned up before it + deleteEntry(dstDir, function () { + // create a new file entry to kick off it + createFile(file1, function (entry) { + // create top level directory + root.getDirectory(dstDir, { + create : true + }, function (directory) { + // create sub-directory + directory.getDirectory(subDir, { + create : true + }, function (subDirectory) { + // move file1 onto sub-directory + entry.moveTo(directory, subDir, succeed.bind(null, done, 'entry.moveTo - Unexpected success callback, it should not move a file: ' + file1 + ' into directory: ' + dstDir + '\n' + subDir + ' directory already exists'), function (error) { + expect(error).toBeDefined(); + expect(error).toBeFileError(FileError.INVALID_MODIFICATION_ERR); + // check that original dir still exists + directory.getDirectory(subDir, { + create : false + }, function (dirEntry) { + expect(dirEntry).toBeDefined(); + expect(dirEntry.fullPath).toCanonicallyMatch(dirPath); + // check that original file still exists + root.getFile(file1, { + create : false + }, function (fileEntry) { + expect(fileEntry).toBeDefined(); + expect(fileEntry.fullPath).toCanonicallyMatch(filePath); + // cleanup + deleteEntry(file1, function () { + deleteEntry(dstDir, done); + }); + }, failed.bind(null, done, 'root.getFile - Error getting file, making sure that original file still exists: ' + file1)); + }, failed.bind(null, done, 'directory.getDirectory - Error getting directory, making sure that original directory still exists: ' + subDir)); + }); + }, failed.bind(null, done, 'directory.getDirectory - Error creating directory : ' + subDir)); + }, failed.bind(null, done, 'root.getDirectory - Error creating directory : ' + dstDir)); + }, failed.bind(null, done, 'createFile - Error creating file : ' + file1)); + }, failed.bind(null, done, 'deleteEntry - Error removing directory : ' + dstDir)); + }); + it("file.spec.74 moveTo: directory onto existing file", function (done) { + if (isIndexedDBShim) { + /* `copyTo` and `moveTo` functions do not support directories (Firefox, IE) */ + pending(); + } + + var file1 = "entry.move.dof.file1", + srcDir = "entry.move.dof.srcDir", + dirPath = joinURL(root.fullPath, srcDir), + filePath = joinURL(root.fullPath, file1); + // create a new directory entry to kick off it + createDirectory(srcDir, function (entry) { + // create file + root.getFile(file1, { + create : true + }, function (fileEntry) { + // move directory onto file + entry.moveTo(root, file1, succeed.bind(null, done, 'entry.moveTo - Unexpected success callback, it should not move : \n' + srcDir + ' into root directory renamed as ' + file1 + '\n' + file1 + ' file already exists'), function (error) { + expect(error).toBeDefined(); + expect(error).toBeFileError(FileError.INVALID_MODIFICATION_ERR); + // test that original directory exists + root.getDirectory(srcDir, { + create : false + }, function (dirEntry) { + // returning confirms existence so just check fullPath entry + expect(dirEntry).toBeDefined(); + expect(dirEntry.fullPath).toCanonicallyMatch(dirPath); + // test that original file exists + root.getFile(file1, { + create : false + }, function (fileEntry) { + expect(fileEntry).toBeDefined(); + expect(fileEntry.fullPath).toCanonicallyMatch(filePath); + // cleanup + deleteEntry(file1, function () { + deleteEntry(srcDir, done); + }); + }, failed.bind(null, done, 'root.getFile - Error getting file, making sure that original file still exists: ' + file1)); + }, failed.bind(null, done, 'directory.getDirectory - Error getting directory, making sure that original directory still exists: ' + srcDir)); + }); + }, failed.bind(null, done, 'root.getFile - Error creating file : ' + file1)); + }, failed.bind(null, done, 'createDirectory - Error creating directory : ' + srcDir)); + }); + it("file.spec.75 copyTo: directory onto existing file", function (done) { + if (isIndexedDBShim) { + /* `copyTo` and `moveTo` functions do not support directories (Firefox, IE) */ + pending(); + } + + var file1 = "entry.copy.dof.file1", + srcDir = "entry.copy.dof.srcDir", + dirPath = joinURL(root.fullPath, srcDir), + filePath = joinURL(root.fullPath, file1); + // create a new directory entry to kick off it + createDirectory(srcDir, function (entry) { + // create file + root.getFile(file1, { + create : true + }, function () { + // copy directory onto file + entry.copyTo(root, file1, succeed.bind(null, done, 'entry.copyTo - Unexpected success callback, it should not copy : \n' + srcDir + ' into root directory renamed as ' + file1 + '\n' + file1 + ' file already exists'), function (error) { + expect(error).toBeDefined(); + expect(error).toBeFileError(FileError.INVALID_MODIFICATION_ERR); + //check that original dir still exists + root.getDirectory(srcDir, { + create : false + }, function (dirEntry) { + // returning confirms existence so just check fullPath entry + expect(dirEntry).toBeDefined(); + expect(dirEntry.fullPath).toCanonicallyMatch(dirPath); + // test that original file still exists + root.getFile(file1, { + create : false + }, function (fileEntry) { + expect(fileEntry).toBeDefined(); + expect(fileEntry.fullPath).toCanonicallyMatch(filePath); + // cleanup + deleteEntry(file1, function () { + deleteEntry(srcDir, done); + }); + }, failed.bind(null, done, 'root.getFile - Error getting file, making sure that original file still exists: ' + file1)); + }, failed.bind(null, done, 'root.getDirectory - Error getting directory, making sure that original directory still exists: ' + srcDir)); + }); + }, failed.bind(null, done, 'root.getFile - Error creating file : ' + file1)); + }, failed.bind(null, done, 'createDirectory - Error creating directory : ' + srcDir)); + }); + it("file.spec.76 moveTo: directory onto directory that is not empty", function (done) { + if (isIndexedDBShim) { + /* `copyTo` and `moveTo` functions do not support directories (Firefox, IE) */ + pending(); + } + + var srcDir = "entry.move.dod.srcDir", + dstDir = "entry.move.dod.dstDir", + subDir = "subDir", + srcPath = joinURL(root.fullPath, srcDir), + dstPath = joinURL(joinURL(root.fullPath, dstDir), subDir); + // ensure destination directory is cleaned up before it + deleteEntry(dstDir, function () { + // create a new file entry to kick off it + createDirectory(srcDir, function (entry) { + // create top level directory + root.getDirectory(dstDir, { + create : true + }, function (directory) { + // create sub-directory + directory.getDirectory(subDir, { + create : true + }, function () { + // move srcDir onto dstDir (not empty) + entry.moveTo(root, dstDir, succeed.bind(null, done, 'entry.moveTo - Unexpected success callback, it should not copy : \n' + srcDir + ' into root directory renamed as ' + dstDir + '\n' + dstDir + ' directory already exists'), function (error) { + expect(error).toBeDefined(); + expect(error).toBeFileError(FileError.INVALID_MODIFICATION_ERR); + // making sure destination directory still exists + directory.getDirectory(subDir, { + create : false + }, function (dirEntry) { + // returning confirms existence so just check fullPath entry + expect(dirEntry).toBeDefined(); + expect(dirEntry.fullPath).toCanonicallyMatch(dstPath); + // making sure source directory exists + root.getDirectory(srcDir, { + create : false + }, function (srcEntry) { + expect(srcEntry).toBeDefined(); + expect(srcEntry.fullPath).toCanonicallyMatch(srcPath); + // cleanup + deleteEntry(srcDir, function () { + deleteEntry(dstDir, done); + }); + }, failed.bind(null, done, 'root.getDirectory - Error getting directory, making sure that original directory still exists: ' + srcDir)); + }, failed.bind(null, done, 'directory.getDirectory - Error getting directory, making sure that original directory still exists: ' + subDir)); + }); + }, failed.bind(null, done, 'directory.getDirectory - Error creating directory : ' + subDir)); + }, failed.bind(null, done, 'directory.getDirectory - Error creating directory : ' + subDir)); + }, failed.bind(null, done, 'createDirectory - Error creating directory : ' + srcDir)); + }, failed.bind(null, done, 'deleteEntry - Error removing directory : ' + dstDir)); + }); + it("file.spec.77 moveTo: file replace existing file", function (done) { + var file1 = "entry.move.frf.file1", + file2 = "entry.move.frf.file2", + file2Path = joinURL(root.fullPath, file2); + // create a new directory entry to kick off it + createFile(file1, function (entry) { + // create file + root.getFile(file2, { + create : true + }, function () { + // replace file2 with file1 + entry.moveTo(root, file2, function (entry2) { + expect(entry2).toBeDefined(); + expect(entry2.isFile).toBe(true); + expect(entry2.isDirectory).toBe(false); + expect(entry2.fullPath).toCanonicallyMatch(file2Path); + expect(entry2.name).toCanonicallyMatch(file2); + // old file should not exists + root.getFile(file1, { + create : false + }, succeed.bind(null, done, 'root.getFile - Unexpected success callback, file: ' + file1 + ' should not exists'), function (error) { + expect(error).toBeDefined(); + expect(error).toBeFileError(FileError.NOT_FOUND_ERR); + // test that new file exists + root.getFile(file2, { + create : false + }, function (fileEntry) { + expect(fileEntry).toBeDefined(); + expect(fileEntry.fullPath).toCanonicallyMatch(file2Path); + // cleanup + deleteEntry(file1, function () { + deleteEntry(file2, done); + }); + }, failed.bind(null, done, 'root.getFile - Error getting moved file: ' + file2)); + }); + }, failed.bind(null, done, 'entry.moveTo - Error moving file : ' + file1 + ' to root as: ' + file2)); + }, failed.bind(null, done, 'root.getFile - Error creating file: ' + file2)); + }, failed.bind(null, done, 'createFile - Error creating file: ' + file1)); + }); + it("file.spec.78 moveTo: directory replace empty directory", function (done) { + if (isIndexedDBShim) { + /* `copyTo` and `moveTo` functions do not support directories (Firefox, IE) */ + pending(); + } + + var file1 = "file1", + srcDir = "entry.move.drd.srcDir", + dstDir = "entry.move.drd.dstDir", + dstPath = joinURL(root.fullPath, dstDir), + filePath = dstPath + '/' + file1; + // ensure destination directory is cleaned up before it + deleteEntry(dstDir, function () { + // create a new directory entry to kick off it + createDirectory(srcDir, function (directory) { + // create a file within source directory + directory.getFile(file1, { + create : true + }, function () { + // create destination directory + root.getDirectory(dstDir, { + create : true + }, function () { + // move srcDir to dstDir + directory.moveTo(root, dstDir, function (dirEntry) { + expect(dirEntry).toBeDefined(); + expect(dirEntry.isFile).toBe(false); + expect(dirEntry.isDirectory).toBe(true); + expect(dirEntry.fullPath).toCanonicallyMatch(dstPath); + expect(dirEntry.name).toCanonicallyMatch(dstDir); + // check that old directory contents have been moved + dirEntry.getFile(file1, { + create : false + }, function (fileEntry) { + expect(fileEntry).toBeDefined(); + expect(fileEntry.fullPath).toCanonicallyMatch(filePath); + // check that old directory no longer exists + root.getDirectory(srcDir, { + create : false + }, succeed.bind(null, done, 'root.getDirectory - Unexpected success callback, directory: ' + srcDir + ' should not exists'), function (error) { + expect(error).toBeDefined(); + expect(error).toBeFileError(FileError.NOT_FOUND_ERR); + // cleanup + deleteEntry(srcDir, function () { + deleteEntry(dstDir, done); + }); + }); + }, failed.bind(null, done, 'dirEntry.getFile - Error getting moved file: ' + file1)); + }, failed.bind(null, done, 'entry.moveTo - Error moving directory : ' + srcDir + ' to root as: ' + dstDir)); + }, failed.bind(null, done, 'root.getDirectory - Error creating directory: ' + dstDir)); + }, failed.bind(null, done, 'root.getFile - Error creating file: ' + file1)); + }, failed.bind(null, done, 'createDirectory - Error creating directory: ' + srcDir)); + }, failed.bind(null, done, 'deleteEntry - Error removing directory : ' + dstDir)); + }); + it("file.spec.79 moveTo: directory that does not exist", function (done) { + + var file1 = "entry.move.dnf.file1", + dstDir = "entry.move.dnf.dstDir", + dstPath = joinURL(root.fullPath, dstDir); + // create a new file entry to kick off it + createFile(file1, function (entry) { + // move file to directory that does not exist + var directory = new DirectoryEntry(); + directory.filesystem = root.filesystem; + directory.fullPath = dstPath; + entry.moveTo(directory, null, succeed.bind(null, done, 'entry.moveTo - Unexpected success callback, parent directory: ' + dstPath + ' should not exists'), function (error) { + expect(error).toBeDefined(); + if (isChrome) { + /*INVALID_MODIFICATION_ERR (code: 9) is thrown instead of NOT_FOUND_ERR(code: 1) + on trying to moveTo directory that does not exist.*/ + expect(error).toBeFileError(FileError.INVALID_MODIFICATION_ERR); + } else { + expect(error).toBeFileError(FileError.NOT_FOUND_ERR); + } + // cleanup + deleteEntry(file1, done); + }); + }, failed.bind(null, done, 'createFile - Error creating file: ' + file1)); + }); + it("file.spec.80 moveTo: invalid target name", function (done) { + if (isBrowser) { + /*The plugin does not follow ["8.3 Naming restrictions"] + (http://www.w3.org/TR/2011/WD-file-system-api-20110419/#naming-restrictions*/ + pending(); + } + + var file1 = "entry.move.itn.file1", + file2 = "bad:file:name"; + // create a new file entry to kick off it + createFile(file1, function (entry) { + // move file1 to file2 + entry.moveTo(root, file2, succeed.bind(null, done, 'entry.moveTo - Unexpected success callback, : ' + file1 + ' to root as: ' + file2), function (error) { + expect(error).toBeDefined(); + expect(error).toBeFileError(FileError.ENCODING_ERR); + // cleanup + deleteEntry(file1, done); + }); + }, failed.bind(null, done, 'createFile - Error creating file: ' + file1)); + }); + }); + //Entry + describe('FileReader', function () { + it("file.spec.81 should have correct methods", function () { + var reader = new FileReader(); + expect(reader).toBeDefined(); + expect(typeof reader.readAsBinaryString).toBe('function'); + expect(typeof reader.readAsDataURL).toBe('function'); + expect(typeof reader.readAsText).toBe('function'); + expect(typeof reader.readAsArrayBuffer).toBe('function'); + expect(typeof reader.abort).toBe('function'); + expect(reader.result).toBe(null); + }); + }); + //FileReader + describe('Read method', function () { + it("file.spec.82 should error out on non-existent file", function (done) { + var fileName = cordova.platformId === 'windowsphone' ? root.toURL() + "/" + "somefile.txt" : "somefile.txt", + verifier = function (evt) { + expect(evt).toBeDefined(); + expect(evt.target.error).toBeFileError(FileError.NOT_FOUND_ERR); + done(); + }; + root.getFile(fileName, { + create : true + }, function (entry) { + entry.file(function (file) { + deleteEntry(fileName, function () { + //Create FileReader + var reader = new FileReader(); + reader.onerror = verifier; + reader.onload = succeed.bind(null, done, 'reader.onload - Unexpected success callback, file: ' + fileName + ' it should not exists'); + reader.readAsText(file); + }, failed.bind(null, done, 'deleteEntry - Error removing file: ' + fileName)); + }, failed.bind(null, done, 'entry.file - Error reading file: ' + fileName)); + }, failed.bind(null, done, 'root.getFile - Error creating file: ' + fileName)); + }); + it("file.spec.83 should be able to read native blob objects", function (done) { + // Skip test if blobs are not supported (e.g.: Android 2.3). + if (typeof window.Blob == 'undefined' || typeof window.Uint8Array == 'undefined') { + expect(true).toFailWithMessage('Platform does not supported this feature'); + done(); + } + var contents = 'asdf'; + var uint8Array = new Uint8Array(contents.length); + for (var i = 0; i < contents.length; ++i) { + uint8Array[i] = contents.charCodeAt(i); + } + var Builder = window.BlobBuilder || window.WebKitBlobBuilder; + var blob; + if (Builder) { + var builder = new Builder(); + builder.append(uint8Array.buffer); + builder.append(contents); + blob = builder.getBlob("text/plain"); + } else { + try { + // iOS 6 does not support Views, so pass in the buffer. + blob = new Blob([uint8Array.buffer, contents]); + } catch (e) { + // Skip the test if we can't create a blob (e.g.: iOS 5). + if (e instanceof TypeError) { + expect(true).toFailWithMessage('Platform does not supported this feature'); + done(); + } + throw e; + } + } + var verifier = function (evt) { + expect(evt).toBeDefined(); + expect(evt.target.result).toBe('asdfasdf'); + done(); + }; + var reader = new FileReader(); + reader.onloadend = verifier; + reader.readAsText(blob); + }); + function writeDummyFile(writeBinary, callback, done, fileContents) { + var fileName = "dummy.txt", + fileEntry = null, + // use default string if file data is not provided + fileData = fileContents !== undefined ? fileContents : + '\u20AC\xEB - There is an exception to every rule. Except this one.', + fileDataAsBinaryString = fileContents !== undefined ? fileContents : + '\xe2\x82\xac\xc3\xab - There is an exception to every rule. Except this one.'; + + function createWriter(fe) { + fileEntry = fe; + fileEntry.createWriter(writeFile, failed.bind(null, done, 'fileEntry.createWriter - Error reading file: ' + fileName)); + } + + // writes file and reads it back in + function writeFile(writer) { + writer.onwriteend = function () { + fileEntry.file(function (f) { + callback(fileEntry, f, fileData, fileDataAsBinaryString); + }, failed.bind(null, done, 'writer.onwriteend - Error writing data on file: ' + fileName)); + }; + writer.write(fileData); + } + + fileData += writeBinary ? 'bin:\x01\x00' : ''; + fileDataAsBinaryString += writeBinary ? 'bin:\x01\x00' : ''; + // create a file, write to it, and read it in again + createFile(fileName, createWriter, failed.bind(null, done, 'createFile - Error creating file: ' + fileName)); + } + function runReaderTest(funcName, writeBinary, done, progressFunc, verifierFunc, sliceStart, sliceEnd, fileContents) { + writeDummyFile(writeBinary, function (fileEntry, file, fileData, fileDataAsBinaryString) { + var verifier = function (evt) { + expect(evt).toBeDefined(); + verifierFunc(evt, fileData, fileDataAsBinaryString); + }; + var reader = new FileReader(); + reader.onprogress = progressFunc; + reader.onload = verifier; + reader.onerror = failed.bind(null, done, 'reader.onerror - Error reading file: ' + file + ' using function: ' + funcName); + if (sliceEnd !== undefined) { + // 'type' is specified so that is will be preserved in the resulting file: + // http://www.w3.org/TR/FileAPI/#slice-method-algo -> "6.4.1. The slice method" -> 4. A), 6. c) + file = file.slice(sliceStart, sliceEnd, file.type); + } else if (sliceStart !== undefined) { + file = file.slice(sliceStart, file.size, file.type); + } + reader[funcName](file); + }, done, fileContents); + } + function arrayBufferEqualsString(ab, str) { + var buf = new Uint8Array(ab); + var match = buf.length == str.length; + for (var i = 0; match && i < buf.length; i++) { + match = buf[i] == str.charCodeAt(i); + } + return match; + } + it("file.spec.84 should read file properly, readAsText", function (done) { + runReaderTest('readAsText', false, done, null, function (evt, fileData, fileDataAsBinaryString) { + expect(evt.target.result).toBe(fileData); + done(); + }); + }); + it("file.spec.84.1 should read JSON file properly, readAsText", function (done) { + var testObject = {key1: "value1", key2: 2}; + runReaderTest('readAsText', false, done, null, function (evt, fileData, fileDataAsBinaryString) { + expect(evt.target.result).toEqual(JSON.stringify(testObject)); + done(); + }, undefined, undefined, JSON.stringify(testObject)); + }); + it("file.spec.85 should read file properly, Data URI", function (done) { + runReaderTest('readAsDataURL', true, done, null, function (evt, fileData, fileDataAsBinaryString) { + /* `readAsDataURL` function is supported, but the mediatype in Chrome depends on entry name extension, + mediatype in IE is always empty (which is the same as `text-plain` according the specification), + the mediatype in Firefox is always `application/octet-stream`. + For example, if the content is `abcdefg` then Firefox returns `data:application/octet-stream;base64,YWJjZGVmZw==`, + IE returns `data:;base64,YWJjZGVmZw==`, Chrome returns `data:;base64,YWJjZGVmZw==`. */ + expect(evt.target.result).toBeDataUrl(); + + //The atob function it is completely ignored during mobilespec execution, besides the returned object: evt + //it is encoded and the atob function is aimed to decode a string. Even with btoa (encode) the function it gets stucked + //because of the Unicode characters that contains the fileData object. + //Issue reported at JIRA with all the details: CB-7095 + + //expect(evt.target.result.slice(23)).toBe(atob(fileData)); + + done(); + }); + }); + it("file.spec.86 should read file properly, readAsBinaryString", function (done) { + if (isIE) { + /*`readAsBinaryString` function is not supported by IE and has not the stub.*/ + pending(); + } + + runReaderTest('readAsBinaryString', true, done, null, function (evt, fileData, fileDataAsBinaryString) { + expect(evt.target.result).toBe(fileDataAsBinaryString); + done(); + }); + }); + it("file.spec.87 should read file properly, readAsArrayBuffer", function (done) { + // Skip test if ArrayBuffers are not supported (e.g.: Android 2.3). + if (typeof window.ArrayBuffer == 'undefined') { + expect(true).toFailWithMessage('Platform does not supported this feature'); + done(); + } + runReaderTest('readAsArrayBuffer', true, done, null, function (evt, fileData, fileDataAsBinaryString) { + expect(arrayBufferEqualsString(evt.target.result, fileDataAsBinaryString)).toBe(true); + done(); + }); + }); + it("file.spec.88 should read sliced file: readAsText", function (done) { + runReaderTest('readAsText', false, done, null, function (evt, fileData, fileDataAsBinaryString) { + expect(evt.target.result).toBe(fileDataAsBinaryString.slice(10, 40)); + done(); + }, 10, 40); + }); + it("file.spec.89 should read sliced file: slice past eof", function (done) { + runReaderTest('readAsText', false, done, null, function (evt, fileData, fileDataAsBinaryString) { + expect(evt.target.result).toBe(fileData.slice(-5, 9999)); + done(); + }, -5, 9999); + }); + it("file.spec.90 should read sliced file: slice to eof", function (done) { + runReaderTest('readAsText', false, done, null, function (evt, fileData, fileDataAsBinaryString) { + expect(evt.target.result).toBe(fileData.slice(-5)); + done(); + }, -5); + }); + it("file.spec.91 should read empty slice", function (done) { + runReaderTest('readAsText', false, done, null, function (evt, fileData, fileDataAsBinaryString) { + expect(evt.target.result).toBe(''); + done(); + }, 0, 0); + }); + it("file.spec.92 should read sliced file properly, readAsDataURL", function (done) { + runReaderTest('readAsDataURL', true, done, null, function (evt, fileData, fileDataAsBinaryString) { + /* `readAsDataURL` function is supported, but the mediatype in Chrome depends on entry name extension, + mediatype in IE is always empty (which is the same as `text-plain` according the specification), + the mediatype in Firefox is always `application/octet-stream`. + For example, if the content is `abcdefg` then Firefox returns `data:application/octet-stream;base64,YWJjZGVmZw==`, + IE returns `data:;base64,YWJjZGVmZw==`, Chrome returns `data:;base64,YWJjZGVmZw==`. */ + expect(evt.target.result).toBeDataUrl(); + + //The atob function it is completely ignored during mobilespec execution, besides the returned object: evt + //it is encoded and the atob function is aimed to decode a string. Even with btoa (encode) the function it gets stucked + //because of the Unicode characters that contains the fileData object. + //Issue reported at JIRA with all the details: CB-7095 + + //expect(evt.target.result.slice(23)).toBe(atob(fileDataAsBinaryString.slice(10, -3))); + + done(); + }, 10, -3); + }); + it("file.spec.93 should read sliced file properly, readAsBinaryString", function (done) { + if (isIE) { + /*`readAsBinaryString` function is not supported by IE and has not the stub.*/ + pending(); + } + + runReaderTest('readAsBinaryString', true, done, null, function (evt, fileData, fileDataAsBinaryString) { + expect(evt.target.result).toBe(fileDataAsBinaryString.slice(-10, -5)); + done(); + }, -10, -5); + }); + it("file.spec.94 should read sliced file properly, readAsArrayBuffer", function (done) { + // Skip test if ArrayBuffers are not supported (e.g.: Android 2.3). + if (typeof window.ArrayBuffer == 'undefined') { + expect(true).toFailWithMessage('Platform does not supported this feature'); + done(); + } + runReaderTest('readAsArrayBuffer', true, done, null, function (evt, fileData, fileDataAsBinaryString) { + expect(arrayBufferEqualsString(evt.target.result, fileDataAsBinaryString.slice(0, -1))).toBe(true); + done(); + }, 0, -1); + }); + it("file.spec.94.5 should read large file in multiple chunks, readAsArrayBuffer", function (done) { + // Skip test if ArrayBuffers are not supported (e.g.: Android 2.3). + if (typeof window.ArrayBuffer == 'undefined') { + expect(true).toFailWithMessage('Platform does not supported this feature'); + done(); + } + + var largeText = ""; + for (var i = 0; i < 1000; i++) { + largeText += "Test " + i + "\n"; + } + + // Set the chunk size so that the read will take 5 chunks + FileReader.READ_CHUNK_SIZE = Math.floor(largeText.length / 4) + 1; + + var chunkCount = 0; + var lastProgressValue = -1; + var progressFunc = function (evt) { + expect(evt.loaded).toBeDefined(); + expect(evt.total).toBeDefined(); + + expect(evt.total >= largeText.length).toBe(true); + expect(evt.total <= largeText.length + 5).toBe(true); + expect(evt.loaded > lastProgressValue).toBe(true); + expect(evt.loaded <= evt.total).toBe(true); + + lastProgressValue = evt.loaded; + chunkCount++; + }; + + runReaderTest( + 'readAsArrayBuffer', true, done, progressFunc, + function (evt, fileData, fileDataAsBinaryString) { + expect(arrayBufferEqualsString(evt.target.result, fileDataAsBinaryString.slice(0, -1))).toBe(true); + expect(lastProgressValue >= largeText.length).toBe(true); + expect(lastProgressValue <= largeText.length + 5).toBe(true); + expect(chunkCount).toBe(5); + done(); + }, + 0, -1, largeText); + }); + it("file.spec.94.6 should read large file in multiple chunks, readAsDataURL", function (done) { + var largeText = ""; + for (var i = 0; i < 10; i++) { + largeText += "Test " + i + "\n"; + } + + // Set the chunk size so that the read will take 5 chunks + FileReader.READ_CHUNK_SIZE = Math.floor(largeText.length / 4) + 1; + + var lastProgressValue = 0; + var progressFunc = function (evt) { + expect(evt.total).toBeDefined(); + expect(evt.total).toEqual(largeText.length); + + expect(evt.loaded).toBeDefined(); + expect(evt.loaded).toBeGreaterThan(lastProgressValue); + expect(evt.loaded).toBeLessThan(evt.total + 1); + + lastProgressValue = evt.loaded; + }; + + runReaderTest('readAsDataURL', false, done, progressFunc, + function (evt, fileData, fileDataAsBinaryString) { + expect(function () { + // Cut off data uri prefix + var base64Data = evt.target.result.substring(evt.target.result.indexOf(',') + 1); + expect(window.atob(base64Data)).toEqual(fileData); + }).not.toThrow(); + + expect(lastProgressValue).toEqual(largeText.length); + done(); + }, + undefined, undefined, largeText); + }); + }); + //Read method + describe('FileWriter', function () { + it("file.spec.95 should have correct methods", function (done) { + // retrieve a FileWriter object + var fileName = "writer.methods"; + // FileWriter + root.getFile(fileName, { + create : true + }, function (fileEntry) { + fileEntry.createWriter(function (writer) { + expect(writer).toBeDefined(); + expect(typeof writer.write).toBe('function'); + expect(typeof writer.seek).toBe('function'); + expect(typeof writer.truncate).toBe('function'); + expect(typeof writer.abort).toBe('function'); + // cleanup + deleteFile(fileName, done); + }, failed.bind(null, done, 'fileEntry.createWriter - Error creating writer using fileEntry: ' + fileEntry.name)); + }, failed.bind(null, done, 'root.getFile - Error creating file: ' + fileName)); + }); + it("file.spec.96 should be able to write and append to file, createWriter", function (done) { + var fileName = "writer.append.createWriter", // file content + content = "There is an exception to every rule.", // for checkin file length + exception = " Except this one.", + length = content.length; + // create file, then write and append to it + createFile(fileName, function (fileEntry) { + // writes initial file content + fileEntry.createWriter(function (writer) { + //Verifiers declaration + function verifier(evt) { + expect(writer.length).toBe(length); + expect(writer.position).toBe(length); + // Append some more data + writer.onwriteend = secondVerifier; + length += exception.length; + writer.seek(writer.length); + writer.write(exception); + } + function secondVerifier(evt) { + expect(writer.length).toBe(length); + expect(writer.position).toBe(length); + var reader = new FileReader(); + reader.onloadend = thirdVerifier; + reader.onerror = failed.bind(null, done, 'reader.onerror - Error reading file: ' + fileName); + fileEntry.file(function(f){reader.readAsText(f);}); + } + function thirdVerifier(evt) { + expect(evt.target.result).toBe(content+exception); + // cleanup + deleteFile(fileName, done); + } + + //Write process + writer.onwriteend = verifier; + writer.write(content); + }, failed.bind(null, done, 'fileEntry.createWriter - Error creating writer using fileEntry: ' + fileEntry.name)); + }, failed.bind(null, done, 'createFile - Error creating file: ' + fileName)); + }); + it("file.spec.97 should be able to write and append to file, File object", function (done) { + var fileName = "writer.append.File", // file content + content = "There is an exception to every rule.", // for checkin file length + exception = " Except this one.", + length = content.length; + root.getFile(fileName, { + create : true + }, function (fileEntry) { + fileEntry.createWriter(function (writer) { + //Verifiers declaration + function verifier() { + expect(writer.length).toBe(length); + expect(writer.position).toBe(length); + // Append some more data + writer.onwriteend = secondVerifier; + length += exception.length; + writer.seek(writer.length); + writer.write(exception); + } + function secondVerifier() { + expect(writer.length).toBe(length); + expect(writer.position).toBe(length); + var reader = new FileReader(); + reader.onloadend = thirdVerifier; + reader.onerror = failed.bind(null, done, 'reader.onerror - Error reading file: ' + fileName); + fileEntry.file(function(f){reader.readAsText(f);}); + } + function thirdVerifier(evt) { + expect(evt.target.result).toBe(content+exception); + // cleanup + deleteFile(fileName, done); + } + + //Write process + writer.onwriteend = verifier; + writer.write(content); + }, failed.bind(null, done, 'fileEntry.createWriter - Error creating writer using fileEntry: ' + fileEntry.name)); + }, failed.bind(null, done, 'root.getFile - Error creating file: ' + fileName)); + }); + it("file.spec.98 should be able to seek to the middle of the file and write more data than file.length", function (done) { + var fileName = "writer.seek.write", // file content + content = "This is our sentence.", // for checking file length + exception = "newer sentence.", + length = content.length; + // create file, then write and append to it + createFile(fileName, function (fileEntry) { + fileEntry.createWriter(function (writer) { + //Verifiers declaration + function verifier(evt) { + expect(writer.length).toBe(length); + expect(writer.position).toBe(length); + // Append some more data + writer.onwriteend = secondVerifier; + length = 12 + exception.length; + writer.seek(12); + writer.write(exception); + } + function secondVerifier(evt) { + expect(writer.length).toBe(length); + expect(writer.position).toBe(length); + var reader = new FileReader(); + reader.onloadend = thirdVerifier; + reader.onerror = failed.bind(null, done, 'reader.onerror - Error reading file: ' + fileName); + fileEntry.file(function(f){reader.readAsText(f);}); + } + function thirdVerifier(evt) { + expect(evt.target.result).toBe(content.substr(0,12)+exception); + // cleanup + deleteFile(fileName, done); + } + + //Write process + writer.onwriteend = verifier; + writer.write(content); + }, failed.bind(null, done, 'fileEntry.createWriter - Error creating writer using fileEntry: ' + fileEntry.name)); + }, failed.bind(null, done, 'createFile - Error creating file: ' + fileName)); + }); + it("file.spec.99 should be able to seek to the middle of the file and write less data than file.length", function (done) { + if (isChrome) { + /* Chrome (re)writes as follows: "This is our sentence." -> "This is new.sentence.", + i.e. the length is not being changed from content.length and writer length will be equal 21 */ + pending(); + } + + var fileName = "writer.seek.write2", // file content + content = "This is our sentence.", // for checking file length + exception = "new.", + length = content.length; + // create file, then write and append to it + createFile(fileName, function (fileEntry) { + fileEntry.createWriter(function (writer) { + // Verifiers declaration + function verifier(evt) { + expect(writer.length).toBe(length); + expect(writer.position).toBe(length); + // Append some more data + writer.onwriteend = secondVerifier; + length = 8 + exception.length; + writer.seek(8); + writer.write(exception); + } + function secondVerifier(evt) { + expect(writer.length).toBe(length); + expect(writer.position).toBe(length); + var reader = new FileReader(); + reader.onloadend = thirdVerifier; + reader.onerror = failed.bind(null, done, 'reader.onerror - Error reading file: ' + fileName); + fileEntry.file(function(f){reader.readAsText(f);}); + } + function thirdVerifier(evt) { + expect(evt.target.result).toBe(content.substr(0,8)+exception); + // cleanup + deleteFile(fileName, done); + } + + //Write process + writer.onwriteend = verifier; + writer.write(content); + }, failed.bind(null, done, 'fileEntry.createWriter - Error creating writer using fileEntry: ' + fileEntry.name)); + }, failed.bind(null, done, 'createFile - Error creating file: ' + fileName)); + }); + it("file.spec.100 should be able to write XML data", function (done) { + var fileName = "writer.xml", // file content + content = '\n\nData\n\n', // for testing file length + length = content.length; + // creates file, then write XML data + createFile(fileName, function (fileEntry) { + fileEntry.createWriter(function (writer) { + //Verifier content + var verifier = function (evt) { + expect(writer.length).toBe(length); + expect(writer.position).toBe(length); + // cleanup + deleteFile(fileName, done); + }; + //Write process + writer.onwriteend = verifier; + writer.write(content); + }, failed.bind(null, done, 'fileEntry.createWriter - Error creating writer using fileEntry: ' + fileEntry.name)); + }, failed.bind(null, done, 'createFile - Error creating file: ' + fileName)); + }); + it("file.spec.101 should be able to write JSON data", function (done) { + var fileName = "writer.json", // file content + content = '{ "name": "Guy Incognito", "email": "here@there.com" }', // for testing file length + length = content.length; + // creates file, then write JSON content + createFile(fileName, function (fileEntry) { + fileEntry.createWriter(function (writer) { + //Verifier declaration + var verifier = function (evt) { + expect(writer.length).toBe(length); + expect(writer.position).toBe(length); + // cleanup + deleteFile(fileName, done); + }; + //Write process + writer.onwriteend = verifier; + writer.write(content); + }, failed.bind(null, done, 'fileEntry.createWriter - Error creating writer using fileEntry: ' + fileEntry.name)); + }, failed.bind(null, done, 'createFile - Error creating file: ' + fileName)); + }); + it("file.spec.102 should be able to seek", function (done) { + var fileName = "writer.seek", // file content + content = "There is an exception to every rule. Except this one.", // for testing file length + length = content.length; + // creates file, then write JSON content + createFile(fileName, function (fileEntry) { + // writes file content and tests writer.seek + fileEntry.createWriter(function (writer) { + //Verifier declaration + var verifier = function () { + expect(writer.position).toBe(length); + writer.seek(-5); + expect(writer.position).toBe(length - 5); + writer.seek(length + 100); + expect(writer.position).toBe(length); + writer.seek(10); + expect(writer.position).toBe(10); + // cleanup + deleteFile(fileName, done); + }; + //Write process + writer.onwriteend = verifier; + writer.seek(-100); + expect(writer.position).toBe(0); + writer.write(content); + }, failed.bind(null, done, 'fileEntry.createWriter - Error creating writer using fileEntry: ' + fileEntry.name)); + }, failed.bind(null, done, 'createFile - Error creating file: ' + fileName)); + }); + it("file.spec.103 should be able to truncate", function (done) { + if (isIndexedDBShim) { + /* `abort` and `truncate` functions are not supported (Firefox, IE) */ + pending(); + } + + var fileName = "writer.truncate", + content = "There is an exception to every rule. Except this one."; + // creates file, writes to it, then truncates it + createFile(fileName, function (fileEntry) { + fileEntry.createWriter(function (writer) { + // Verifier declaration + var verifier = function () { + expect(writer.length).toBe(36); + expect(writer.position).toBe(36); + // cleanup + deleteFile(fileName, done); + }; + //Write process + writer.onwriteend = function () { + //Truncate process after write + writer.onwriteend = verifier; + writer.truncate(36); + }; + writer.write(content); + }, failed.bind(null, done, 'fileEntry.createWriter - Error creating writer using fileEntry: ' + fileEntry.name)); + }, failed.bind(null, done, 'createFile - Error creating file: ' + fileName)); + }); + it("file.spec.104 should be able to write binary data from an ArrayBuffer", function (done) { + // Skip test if ArrayBuffers are not supported (e.g.: Android 2.3). + if (typeof window.ArrayBuffer == 'undefined') { + expect(true).toFailWithMessage('Platform does not supported this feature'); + done(); + return; + } + var fileName = "bufferwriter.bin", // file content + data = new ArrayBuffer(32), + dataView = new Int8Array(data), // for verifying file length + length = 32; + for (var i = 0; i < dataView.length; i++) { + dataView[i] = i; + } + // creates file, then write content + createFile(fileName, function (fileEntry) { + // writes file content + fileEntry.createWriter(function (writer) { + //Verifier declaration + var verifier = function () { + expect(writer.length).toBe(length); + expect(writer.position).toBe(length); + // cleanup + deleteFile(fileName, done); + }; + //Write process + writer.onwriteend = verifier; + writer.write(data); + }, failed.bind(null, done, 'fileEntry.createWriter - Error creating writer using fileEntry: ' + fileEntry.name)); + }, failed.bind(null, done, 'createFile - Error creating file: ' + fileName)); + }); + it("file.spec.105 should be able to write binary data from a Blob", function (done) { + // Skip test if Blobs are not supported (e.g.: Android 2.3). + if ((typeof window.Blob == 'undefined' && typeof window.WebKitBlobBuilder == 'undefined') || typeof window.ArrayBuffer == 'undefined') { + expect(true).toFailWithMessage('Platform does not supported this feature'); + done(); + return; + } + var fileName = "blobwriter.bin", // file content + data = new ArrayBuffer(32), + dataView = new Int8Array(data), + blob, // for verifying file length + length = 32; + for (var i = 0; i < dataView.length; i++) { + dataView[i] = i; + } + try { + // Mobile Safari: Use Blob constructor + blob = new Blob([data], { + "type" : "application/octet-stream" + }); + } catch (e) { + if (window.WebKitBlobBuilder) { + // Android Browser: Use deprecated BlobBuilder + var builder = new WebKitBlobBuilder(); + builder.append(data); + blob = builder.getBlob('application/octet-stream'); + } else { + // We have no way defined to create a Blob, so fail + fail(); + } + } + if (typeof blob !== 'undefined') { + // creates file, then write content + createFile(fileName, function (fileEntry) { + fileEntry.createWriter(function (writer) { + //Verifier declaration + var verifier = function () { + expect(writer.length).toBe(length); + expect(writer.position).toBe(length); + // cleanup + deleteFile(fileName, done); + }; + //Write process + writer.onwriteend = verifier; + writer.write(blob); + }, failed.bind(null, done, 'fileEntry.createWriter - Error creating writer using fileEntry: ' + fileEntry.name)); + }, failed.bind(null, done, 'createFile - Error creating file: ' + fileName)); + } + }); + it("file.spec.106 should be able to write a File to a FileWriter", function (done) { + var dummyFileName = 'dummy.txt', + outputFileName = 'verify.txt', + dummyFileText = 'This text should be written to two files', + verifier = function (outputFileWriter) { + expect(outputFileWriter.length).toBe(dummyFileText.length); + expect(outputFileWriter.position).toBe(dummyFileText.length); + deleteFile(outputFileName, done); + }, + writeFile = function (fileName, fileData, win) { + var theWriter, + write_file = function (fileEntry) { + // writes file content to new file + fileEntry.createWriter(function (writer) { + theWriter = writer; + writer.onwriteend = function (ev) { + if (typeof fileData.length !== "undefined") { + expect(theWriter.length).toBe(fileData.length); + expect(theWriter.position).toBe(fileData.length); + } + win(theWriter); + }; + writer.onerror = failed.bind(null, done, 'writer.onerror - Error writing content on file: ' + fileName); + writer.write(fileData); + }, failed.bind(null, done, 'fileEntry.createWriter - Error creating writer using fileEntry: ' + fileEntry.name)); + }; + createFile(fileName, write_file, failed.bind(null, done, 'createFile - Error creating file: ' + fileName)); + }, + openFile = function (fileName, callback) { + root.getFile(fileName, { + create : false + }, function (fileEntry) { + fileEntry.file(callback, failed.bind(null, done, 'fileEntry.file - Error reading file using fileEntry: ' + fileEntry.name)); + }, failed.bind(null, done, 'root.getFile - Error getting file: ' + fileName)); + }; + writeFile(dummyFileName, dummyFileText, function (dummyFileWriter) { + openFile(dummyFileName, function (file) { + writeFile(outputFileName, file, verifier); + }); + }); + }); + it("file.spec.107 should be able to write a sliced File to a FileWriter", function (done) { + var dummyFileName = 'dummy2.txt', + outputFileName = 'verify2.txt', + dummyFileText = 'This text should be written to two files', + verifier = function (outputFileWriter) { + expect(outputFileWriter.length).toBe(10); + expect(outputFileWriter.position).toBe(10); + deleteFile(outputFileName, done); + }, + writeFile = function (fileName, fileData, win) { + var theWriter, + write_file = function (fileEntry) { + // writes file content to new file + fileEntry.createWriter(function (writer) { + theWriter = writer; + writer.onwriteend = function (ev) { + if (typeof fileData.length !== "undefined") { + expect(theWriter.length).toBe(fileData.length); + expect(theWriter.position).toBe(fileData.length); + } + win(theWriter); + }; + writer.onerror = failed.bind(null, done, 'writer.onerror - Error writing content on file: ' + fileName); + writer.write(fileData); + }, failed.bind(null, done, 'fileEntry.createWriter - Error creating writer using fileEntry: ' + fileEntry.name)); + }; + createFile(fileName, write_file, failed.bind(null, done, 'createFile - Error creating file: ' + fileName)); + }, + openFile = function (fileName, callback) { + root.getFile(fileName, { + create : false + }, function (fileEntry) { + fileEntry.file(callback, failed.bind(null, done, 'fileEntry.file - Error reading file using fileEntry: ' + fileEntry.name)); + }, failed.bind(null, done, 'root.getFile - Error getting file: ' + fileName)); + }; + writeFile(dummyFileName, dummyFileText, function (dummyFileWriter) { + openFile(dummyFileName, function (file) { + writeFile(outputFileName, file.slice(10, 20), verifier); + }); + }); + }); + it("file.spec.108 should be able to write binary data from a File", function (done) { + // Skip test if Blobs are not supported (e.g.: Android 2.3). + if (typeof window.Blob == 'undefined' && typeof window.WebKitBlobBuilder == 'undefined') { + expect(true).toFailWithMessage('Platform does not supported this feature'); + done(); + } + var dummyFileName = "blobwriter.bin", + outputFileName = 'verify.bin', // file content + data = new ArrayBuffer(32), + dataView = new Int8Array(data), + blob, // for verifying file length + length = 32, + verifier = function (outputFileWriter) { + expect(outputFileWriter.length).toBe(length); + expect(outputFileWriter.position).toBe(length); + // cleanup + deleteFile(outputFileName); + done(); + }, + writeFile = function (fileName, fileData, win) { + var theWriter, + write_file = function (fileEntry) { + // writes file content to new file + fileEntry.createWriter(function (writer) { + theWriter = writer; + writer.onwriteend = function (ev) { + if (typeof fileData.length !== "undefined") { + expect(theWriter.length).toBe(fileData.length); + expect(theWriter.position).toBe(fileData.length); + } + win(theWriter); + }; + writer.onerror = failed.bind(null, done, 'writer.onerror - Error writing content on file: ' + fileName); + writer.write(fileData); + }, failed.bind(null, done, 'fileEntry.createWriter - Error creating writer using fileEntry: ' + fileEntry.name)); + }; + createFile(fileName, write_file, failed.bind(null, done, 'createFile - Error creating file: ' + fileName)); + }, + openFile = function (fileName, callback) { + root.getFile(fileName, { + create : false + }, function (fileEntry) { + fileEntry.file(callback, failed.bind(null, done, 'fileEntry.file - Error reading file using fileEntry: ' + fileEntry.name)); + }, failed.bind(null, done, 'root.getFile - Error getting file: ' + fileName)); + }; + for (var i = 0; i < dataView.length; i++) { + dataView[i] = i; + } + try { + // Mobile Safari: Use Blob constructor + blob = new Blob([data], { + "type" : "application/octet-stream" + }); + } catch (e) { + if (window.WebKitBlobBuilder) { + // Android Browser: Use deprecated BlobBuilder + var builder = new WebKitBlobBuilder(); + builder.append(data); + blob = builder.getBlob('application/octet-stream'); + } else { + // We have no way defined to create a Blob, so fail + fail(); + } + } + if (typeof blob !== 'undefined') { + // creates file, then write content + writeFile(dummyFileName, blob, function (dummyFileWriter) { + openFile(dummyFileName, function (file) { + writeFile(outputFileName, file, verifier); + }); + }); + } + }); + }); + //FileWritter + describe('Backwards compatibility', function () { + /* These specs exist to test that the File plugin can still recognize file:/// + * URLs, and can resolve them to FileEntry and DirectoryEntry objects. + * They rely on an undocumented interface to File which provides absolute file + * paths, which are not used internally anymore. + * If that interface is not present, then these tests will silently succeed. + */ + it("file.spec.109 should be able to resolve a file:/// URL", function (done) { + var localFilename = 'file.txt'; + var originalEntry; + root.getFile(localFilename, { + create : true + }, function (entry) { + originalEntry = entry; + /* This is an undocumented interface to File which exists only for testing + * backwards compatibilty. By obtaining the raw filesystem path of the download + * location, we can pass that to ft.download() to make sure that previously-stored + * paths are still valid. + */ + cordova.exec(function (localPath) { + window.resolveLocalFileSystemURL("file://" + encodeURI(localPath), function (fileEntry) { + expect(fileEntry.toURL()).toEqual(originalEntry.toURL()); + // cleanup + deleteFile(localFilename); + done(); + }, failed.bind(null, done, 'window.resolveLocalFileSystemURL - Error resolving URI: file://' + encodeURI(localPath))); + }, done, 'File', '_getLocalFilesystemPath', [entry.toURL()]); + }, failed.bind(null, done, 'root.getFile - Error creating file: ' + localFilename)); + }); + }); + //Backwards Compatibility + describe('Parent References', function () { + /* These specs verify that paths with parent references i("..") in them + * work correctly, and do not cause the application to crash. + */ + it("file.spec.110 should not throw exception resolving parent refefences", function (done) { + /* This is a direct copy of file.spec.9, with the filename changed, * as reported in CB-5721. + */ + var fileName = "resolve.file.uri"; + var dirName = "resolve.dir.uri"; + // create a new file entry + createDirectory(dirName, function () { + createFile(dirName+"/../" + fileName, function (entry) { + // lookup file system entry + window.resolveLocalFileSystemURL(entry.toURL(), function (fileEntry) { + expect(fileEntry).toBeDefined(); + expect(fileEntry.name).toCanonicallyMatch(fileName); + // cleanup + deleteEntry(fileName, done); + }, failed.bind(null, done, 'window.resolveLocalFileSystemURL - Error resolving URI: ' + entry.toURL())); + }, failed.bind(null, done, 'createFile - Error creating file: ../' + fileName)); + }, failed.bind(null, done, 'createDirectory - Error creating directory: ' + dirName)); + }); + it("file.spec.111 should not traverse above above the root directory", function (done) { + var fileName = "traverse.file.uri"; + // create a new file entry + createFile(fileName, function (entry) { + // lookup file system entry + root.getFile('../' + fileName, { + create : false + }, function (fileEntry) { + // Note: we expect this to still resolve, as the correct behaviour is to ignore the ../, not to fail out. + expect(fileEntry).toBeDefined(); + expect(fileEntry.name).toBe(fileName); + expect(fileEntry.fullPath).toCanonicallyMatch(root.fullPath +'/' + fileName); + // cleanup + deleteEntry(fileName, done); + }, failed.bind(null, done, 'root.getFile - Error getting file: ../' + fileName)); + }, failed.bind(null, done, 'createFile - Error creating file: ../' + fileName)); + }); + it("file.spec.112 should traverse above above the current directory", function (done) { + var fileName = "traverse2.file.uri", + dirName = "traverse2.subdir"; + // create a new directory and a file entry + createFile(fileName, function () { + createDirectory(dirName, function (entry) { + // lookup file system entry + entry.getFile('../' + fileName, { + create : false + }, function (fileEntry) { + expect(fileEntry).toBeDefined(); + expect(fileEntry.name).toBe(fileName); + expect(fileEntry.fullPath).toCanonicallyMatch('/' + fileName); + // cleanup + deleteEntry(fileName, function () { + deleteEntry(dirName, done); + }); + }, failed.bind(null, done, 'entry.getFile - Error getting file: ' + fileName + ' recently created above: ' + dirName)); + }, failed.bind(null, done, 'createDirectory - Error creating directory: ' + dirName)); + }, failed.bind(null, done, 'createFile - Error creating file: ' + fileName)); + }); + it("file.spec.113 getFile: get Entry should error for missing file above root directory", function (done) { + var fileName = "../missing.file"; + // create:false, exclusive:false, file does not exist + root.getFile(fileName, { + create : false + }, succeed.bind(null, done, 'root.getFile - Unexpected success callback, it should not locate nonexistent file: ' + fileName), function (error) { + expect(error).toBeDefined(); + expect(error).toBeFileError(FileError.NOT_FOUND_ERR); + done(); + }); + }); + }); + //Parent References + describe('toNativeURL interface', function () { + /* These specs verify that FileEntries have a toNativeURL method + * which appears to be sane. + */ + var pathExpect = cordova.platformId === 'windowsphone' ? "//nativ" : "file://"; + if (isChrome) { + pathExpect = 'filesystem:file://'; + } + it("file.spec.114 fileEntry should have a toNativeURL method", function (done) { + var fileName = "native.file.uri"; + if (isWindows) { + var rootPath = root.fullPath; + pathExpect = rootPath.substr(0, rootPath.indexOf(":")); + } + // create a new file entry + createFile(fileName, function (entry) { + expect(entry.toNativeURL).toBeDefined(); + expect(entry.name).toCanonicallyMatch(fileName); + expect(typeof entry.toNativeURL).toBe('function'); + var nativeURL = entry.toNativeURL(); + expect(typeof nativeURL).toBe("string"); + expect(nativeURL.substring(0, pathExpect.length)).toEqual(pathExpect); + expect(nativeURL.substring(nativeURL.length - fileName.length)).toEqual(fileName); + // cleanup + deleteEntry(fileName, done); + }, failed.bind(null, done, 'createFile - Error creating file: ' + fileName)); + }); + it("file.spec.115 DirectoryReader should return entries with toNativeURL method", function (done) { + var dirName = 'nativeEntries.dir', + fileName = 'nativeEntries.file', + directory, + checkEntries = function (entries) { + expect(entries).toBeDefined(); + expect(entries instanceof Array).toBe(true); + expect(entries.length).toBe(1); + expect(entries[0].toNativeURL).toBeDefined(); + expect(typeof entries[0].toNativeURL).toBe('function'); + var nativeURL = entries[0].toNativeURL(); + expect(typeof nativeURL).toBe("string"); + expect(nativeURL.substring(0, pathExpect.length)).toEqual(pathExpect); + expect(nativeURL.substring(nativeURL.length - fileName.length)).toEqual(fileName); + // cleanup + directory.removeRecursively(null, null); + done(); + }; + // create a new file entry + root.getDirectory(dirName, { + create : true + }, function (dir) { + directory = dir; + directory.getFile(fileName, { + create : true + }, function (fileEntry) { + var reader = directory.createReader(); + reader.readEntries(checkEntries, failed.bind(null, done, 'reader.readEntries - Error reading entries from directory: ' + dirName)); + }, failed.bind(null, done, 'directory.getFile - Error creating file: ' + fileName)); + }, failed.bind(null, done, 'root.getDirectory - Error creating directory: ' + dirName)); + }); + it("file.spec.116 resolveLocalFileSystemURL should return entries with toNativeURL method", function (done) { + var fileName = "native.resolve.uri"; + // create a new file entry + createFile(fileName, function (entry) { + resolveLocalFileSystemURL(entry.toURL(), function (entry) { + expect(entry.toNativeURL).toBeDefined(); + expect(entry.name).toCanonicallyMatch(fileName); + expect(typeof entry.toNativeURL).toBe('function'); + var nativeURL = entry.toNativeURL(); + expect(typeof nativeURL).toBe("string"); + expect(nativeURL.substring(0, pathExpect.length)).toEqual(pathExpect); + expect(nativeURL.substring(nativeURL.length - fileName.length)).toEqual(fileName); + // cleanup + deleteEntry(fileName, done); + }, failed.bind(null, done, 'resolveLocalFileSystemURL - Error resolving file URL: ' + entry.toURL())); + }, failed.bind(null, done, 'createFile - Error creating file: ' + fileName)); + }); + }); + //toNativeURL interface + describe('resolveLocalFileSystemURL on file://', function () { + /* These specs verify that window.resolveLocalFileSystemURL works correctly on file:// URLs + */ + it("file.spec.117 should not resolve native URLs outside of FS roots", function (done) { + // lookup file system entry + window.resolveLocalFileSystemURL("file:///this.is.an.invalid.url", succeed.bind(null, done, 'window.resolveLocalFileSystemURL - Unexpected success callback, it should not resolve invalid URL: file:///this.is.an.invalid.url'), function (error) { + expect(error).toBeDefined(); + done(); + }); + }); + it("file.spec.118 should not resolve native URLs outside of FS roots", function (done) { + // lookup file system entry + window.resolveLocalFileSystemURL("file://localhost/this.is.an.invalid.url", succeed.bind(null, done, 'window.resolveLocalFileSystemURL - Unexpected success callback, it should not resolve invalid URL: file://localhost/this.is.an.invalid.url'), function (error) { + expect(error).toBeDefined(); + done(); + }); + }); + it("file.spec.119 should not resolve invalid native URLs", function (done) { + // lookup file system entry + window.resolveLocalFileSystemURL("file://localhost", succeed.bind(null, done, 'window.resolveLocalFileSystemURL - Unexpected success callback, it should not resolve invalid URL: file://localhost'), function (error) { + expect(error).toBeDefined(); + done(); + }); + }); + it("file.spec.120 should not resolve invalid native URLs with query strings", function (done) { + // lookup file system entry + window.resolveLocalFileSystemURL("file://localhost?test/test", succeed.bind(null, done, 'window.resolveLocalFileSystemURL - Unexpected success callback, it should not resolve invalid URL: file://localhost?test/test'), function (error) { + expect(error).toBeDefined(); + done(); + }); + }); + it("file.spec.121 should resolve native URLs returned by API", function (done) { + var fileName = "native.resolve.uri1"; + // create a new file entry + createFile(fileName, function (entry) { + resolveLocalFileSystemURL(entry.toNativeURL(), function (fileEntry) { + expect(fileEntry.fullPath).toCanonicallyMatch(root.fullPath + "/" + fileName); + // cleanup + deleteEntry(fileName, done); + }, failed.bind(null, done, 'resolveLocalFileSystemURL - Error resolving file URL: ' + entry.toNativeURL())); + }, failed.bind(null, done, 'createFile - Error creating file: ' + fileName)); + }); + it("file.spec.122 should resolve native URLs returned by API with localhost", function (done) { + var fileName = "native.resolve.uri2"; + // create a new file entry + createFile(fileName, function (entry) { + var url = entry.toNativeURL(); + url = url.replace("///", "//localhost/"); + resolveLocalFileSystemURL(url, function (fileEntry) { + expect(fileEntry.fullPath).toCanonicallyMatch(root.fullPath + "/" + fileName); + // cleanup + deleteEntry(fileName, done); + }, failed.bind(null, done, 'resolveLocalFileSystemURL - Error resolving file URL: ' + url)); + }, failed.bind(null, done, 'createFile - Error creating file: ' + fileName)); + }); + it("file.spec.123 should resolve native URLs returned by API with query string", function (done) { + var fileName = "native.resolve.uri3"; + // create a new file entry + createFile(fileName, function (entry) { + var url = entry.toNativeURL(); + url = url + "?test/test"; + resolveLocalFileSystemURL(url, function (fileEntry) { + expect(fileEntry.fullPath).toCanonicallyMatch(root.fullPath + "/" + fileName); + // cleanup + deleteEntry(fileName, done); + }, failed.bind(null, done, 'resolveLocalFileSystemURL - Error resolving file URL: ' + url)); + }, failed.bind(null, done, 'createFile - Error creating file: ' + fileName)); + }); + it("file.spec.124 should resolve native URLs returned by API with localhost and query string", function (done) { + var fileName = "native.resolve.uri4"; + // create a new file entry + createFile(fileName, function (entry) { + var url = entry.toNativeURL(); + url = url.replace("///", "//localhost/") + "?test/test"; + resolveLocalFileSystemURL(url, function (fileEntry) { + expect(fileEntry.fullPath).toCanonicallyMatch(root.fullPath + "/" + fileName); + // cleanup + deleteEntry(fileName, done); + }, failed.bind(null, done, 'resolveLocalFileSystemURL - Error resolving file URL: ' + url)); + }, failed.bind(null, done, 'createFile - Error creating file: ' + fileName)); + }); + }); + //resolveLocalFileSystemURL on file:// + describe('cross-file-system copy and move', function () { + /* These specs verify that Entry.copyTo and Entry.moveTo work correctly + * when crossing filesystem boundaries. + */ + it("file.spec.125 copyTo: temporary -> persistent", function (done) { + var file1 = "entry.copy.file1a", + file2 = "entry.copy.file2a", + sourceEntry, + fullPath = joinURL(root.fullPath, file2), + validateFile = function (entry) { + // a bit redundant since copy returned this entry already + expect(entry).toBeDefined(); + expect(entry.isFile).toBe(true); + expect(entry.isDirectory).toBe(false); + expect(entry.name).toCanonicallyMatch(file2); + expect(entry.fullPath).toCanonicallyMatch(fullPath); + expect(entry.filesystem).toBeDefined(); + if (isChrome) { + expect(entry.filesystem.name).toContain("Persistent"); + } else { + expect(entry.filesystem.name).toEqual("persistent"); + } + // cleanup + deleteEntry(entry.name); + deleteEntry(sourceEntry.name, done); + }, + createSourceAndTransfer = function () { + temp_root.getFile(file1, { + create : true + }, function (entry) { + expect(entry.filesystem).toBeDefined(); + if (isChrome) { + expect(entry.filesystem.name).toContain("Temporary"); + } else { + expect(entry.filesystem.name).toEqual("temporary"); + } + sourceEntry = entry; + // Save for later cleanup + entry.copyTo(persistent_root, file2, validateFile, failed.bind(null, done, 'entry.copyTo - Error copying file: ' + file1 + ' to PERSISTENT root as: ' + file2)); + }, failed.bind(null, done, 'temp_root.getFile - Error creating file: ' + file1 + 'at TEMPORAL root')); + }; + // Delete any existing file to start things off + persistent_root.getFile(file2, {}, function (entry) { + entry.remove(createSourceAndTransfer, failed.bind(null, done, 'entry.remove - Error removing file: ' + file2)); + }, createSourceAndTransfer); + }); + it("file.spec.126 copyTo: persistent -> temporary", function (done) { + var file1 = "entry.copy.file1b", + file2 = "entry.copy.file2b", + sourceEntry, + fullPath = joinURL(temp_root.fullPath, file2), + validateFile = function (entry) { + expect(entry).toBeDefined(); + expect(entry.isFile).toBe(true); + expect(entry.isDirectory).toBe(false); + expect(entry.name).toCanonicallyMatch(file2); + expect(entry.fullPath).toCanonicallyMatch(fullPath); + if (isChrome) { + expect(entry.filesystem.name).toContain("Temporary"); + } else { + expect(entry.filesystem.name).toEqual("temporary"); + } + // cleanup + deleteEntry(entry.name); + deleteEntry(sourceEntry.name, done); + }, + createSourceAndTransfer = function () { + persistent_root.getFile(file1, { + create : true + }, function (entry) { + expect(entry).toBeDefined(); + expect(entry.filesystem).toBeDefined(); + if (isChrome) { + expect(entry.filesystem.name).toContain("Persistent"); + } else { + expect(entry.filesystem.name).toEqual("persistent"); + } + sourceEntry = entry; + // Save for later cleanup + entry.copyTo(temp_root, file2, validateFile, failed.bind(null, done, 'entry.copyTo - Error copying file: ' + file1 + ' to TEMPORAL root as: ' + file2)); + }, failed.bind(null, done, 'persistent_root.getFile - Error creating file: ' + file1 + 'at PERSISTENT root')); + }; + // Delete any existing file to start things off + temp_root.getFile(file2, {}, function (entry) { + entry.remove(createSourceAndTransfer, failed.bind(null, done, 'entry.remove - Error removing file: ' + file2)); + }, createSourceAndTransfer); + }); + it("file.spec.127 moveTo: temporary -> persistent", function (done) { + var file1 = "entry.copy.file1a", + file2 = "entry.copy.file2a", + sourceEntry, + fullPath = joinURL(root.fullPath, file2), + validateFile = function (entry) { + // a bit redundant since copy returned this entry already + expect(entry).toBeDefined(); + expect(entry.isFile).toBe(true); + expect(entry.isDirectory).toBe(false); + expect(entry.name).toCanonicallyMatch(file2); + expect(entry.fullPath).toCanonicallyMatch(fullPath); + expect(entry.filesystem).toBeDefined(); + if (isChrome) { + expect(entry.filesystem.name).toContain("Persistent"); + } else { + expect(entry.filesystem.name).toEqual("persistent"); + } + // cleanup + deleteEntry(entry.name); + deleteEntry(sourceEntry.name, done); + }, + createSourceAndTransfer = function () { + temp_root.getFile(file1, { + create : true + }, function (entry) { + expect(entry.filesystem).toBeDefined(); + if (isChrome) { + expect(entry.filesystem.name).toContain("Temporary"); + } else { + expect(entry.filesystem.name).toEqual("temporary"); + } + sourceEntry = entry; + // Save for later cleanup + entry.moveTo(persistent_root, file2, validateFile, failed.bind(null, done, 'entry.moveTo - Error moving file: ' + file1 + ' to PERSISTENT root as: ' + file2)); + }, failed.bind(null, done, 'temp_root.getFile - Error creating file: ' + file1 + 'at TEMPORAL root')); + }; + // Delete any existing file to start things off + persistent_root.getFile(file2, {}, function (entry) { + entry.remove(createSourceAndTransfer, failed.bind(null, done, 'entry.remove - Error removing file: ' + file2)); + }, createSourceAndTransfer); + }); + it("file.spec.128 moveTo: persistent -> temporary", function (done) { + var file1 = "entry.copy.file1b", + file2 = "entry.copy.file2b", + sourceEntry, + fullPath = joinURL(temp_root.fullPath, file2), + validateFile = function (entry) { + expect(entry).toBeDefined(); + expect(entry.isFile).toBe(true); + expect(entry.isDirectory).toBe(false); + expect(entry.name).toCanonicallyMatch(file2); + expect(entry.fullPath).toCanonicallyMatch(fullPath); + if(isChrome) { + expect(entry.filesystem.name).toContain("Temporary"); + } else { + expect(entry.filesystem.name).toEqual("temporary"); + } + // cleanup + deleteEntry(entry.name); + deleteEntry(sourceEntry.name, done); + }, + createSourceAndTransfer = function () { + persistent_root.getFile(file1, { + create : true + }, function (entry) { + expect(entry).toBeDefined(); + expect(entry.filesystem).toBeDefined(); + if (isChrome) { + expect(entry.filesystem.name).toContain("Persistent"); + } else { + expect(entry.filesystem.name).toEqual("persistent"); + } + sourceEntry = entry; + // Save for later cleanup + entry.moveTo(temp_root, file2, validateFile, failed.bind(null, done, 'entry.moveTo - Error moving file: ' + file1 + ' to TEMPORAL root as: ' + file2)); + }, failed.bind(null, done, 'persistent_root.getFile - Error creating file: ' + file1 + 'at PERSISTENT root')); + }; + // Delete any existing file to start things off + temp_root.getFile(file2, {}, function (entry) { + entry.remove(createSourceAndTransfer, failed.bind(null, done, 'entry.remove - Error removing file: ' + file2)); + }, createSourceAndTransfer); + }); + it("file.spec.129 cordova.file.*Directory are set", function () { + var expectedPaths = ['applicationDirectory', 'applicationStorageDirectory', 'dataDirectory', 'cacheDirectory']; + if (cordova.platformId == 'android' || cordova.platformId == 'amazon-fireos') { + if (cordova.file.externalApplicationStorageDirectory !== null) { + // https://issues.apache.org/jira/browse/CB-10411 + // If external storage can't be mounted, the cordova.file.external* properties are null. + expectedPaths.push('externalApplicationStorageDirectory', 'externalRootDirectory', 'externalCacheDirectory', 'externalDataDirectory'); + } + } else if (cordova.platformId == 'blackberry10') { + expectedPaths.push('externalRootDirectory', 'sharedDirectory'); + } else if (cordova.platformId == 'ios') { + expectedPaths.push('syncedDataDirectory', 'documentsDirectory', 'tempDirectory'); + } else if (cordova.platformId == 'osx') { + expectedPaths.push('documentsDirectory', 'tempDirectory', 'rootDirectory'); + } else { + console.log('Skipping test due on unsupported platform.'); + return; + } + for (var i = 0; i < expectedPaths.length; ++i) { + expect(typeof cordova.file[expectedPaths[i]]).toBe('string'); + expect(cordova.file[expectedPaths[i]]).toMatch(/\/$/, 'Path should end with a slash'); + } + }); + }); + describe('resolveLocalFileSystemURL on cdvfile://', function () { + it("file.spec.147 should be able to resolve cdvfile applicationDirectory fs root", function(done) { + var cdvfileApplicationDirectoryFsRootName; + if (cordova.platformId === 'android') { + cdvfileApplicationDirectoryFsRootName = 'assets'; + } else if (cordova.platformId === 'ios') { + cdvfileApplicationDirectoryFsRootName = 'bundle'; + } else { + pending(); + } + + resolveLocalFileSystemURL('cdvfile://localhost/' + cdvfileApplicationDirectoryFsRootName + '/', function(applicationDirectoryRoot) { + expect(applicationDirectoryRoot.isFile).toBe(false); + expect(applicationDirectoryRoot.isDirectory).toBe(true); + expect(applicationDirectoryRoot.name).toCanonicallyMatch(''); + expect(applicationDirectoryRoot.fullPath).toCanonicallyMatch('/'); + expect(applicationDirectoryRoot.filesystem.name).toEqual(cdvfileApplicationDirectoryFsRootName); + + // Requires HelloCordova www assets, in config.xml or + // cdvfile: in CSP and in config.xml + resolveLocalFileSystemURL('cdvfile://localhost/' + cdvfileApplicationDirectoryFsRootName + '/www/img/logo.png', function(entry) { + expect(entry.isFile).toBe(true); + expect(entry.isDirectory).toBe(false); + expect(entry.name).toCanonicallyMatch('logo.png'); + expect(entry.fullPath).toCanonicallyMatch('/www/img/logo.png'); + expect(entry.filesystem.name).toEqual(cdvfileApplicationDirectoryFsRootName); + + var img = new Image(); + img.onerror = function(err) { + expect(err).not.toBeDefined(); + done(); + }; + img.onload = function() { + done(); + }; + img.src = entry.toInternalURL(); + }, failed.bind(null, done, 'resolveLocalFileSystemURL failed for cdvfile applicationDirectory')); + }, failed.bind(null, done, 'resolveLocalFileSystemURL failed for cdvfile applicationDirectory')); + }); + }); + //cross-file-system copy and move + describe('IndexedDB-based impl', function () { + it("file.spec.131 Nested file or nested directory should be removed when removing a parent directory", function (done) { + var parentDirName = 'deletedDir131', + nestedDirName = 'nestedDir131', + nestedFileName = 'nestedFile131.txt'; + + createDirectory(parentDirName, function (parent) { + parent.getDirectory(nestedDirName, { create: true}, function () { + parent.getFile(nestedFileName, { create: true}, function () { + parent.removeRecursively(function() { + root.getDirectory(parentDirName,{ create: false}, failed.bind(this, done, 'root.getDirectory - unexpected success callback : ' + parentDirName), function(){ + parent.getFile(nestedFileName,{ create: false}, failed.bind(this, done, 'getFile - unexpected success callback : ' + nestedFileName), function(){ + parent.getDirectory(nestedDirName, { create: false}, failed.bind(this, done, 'getDirectory - unexpected success callback : ' + nestedDirName), done); + }); + }); + }, failed.bind(this, done, 'removeRecursively - Error removing directory : ' + parentDirName)); + }, failed.bind(this, done, 'getFile - Error creating file : ' + nestedFileName)); + },failed.bind(this, done, 'getDirectory - Error creating directory : ' + nestedDirName)); + }, failed.bind(this, done, 'root.getDirectory - Error creating directory : ' + parentDirName)); + }); + it("file.spec.132 Entry should be created succesfully when using relative paths if its parent directory exists", function (done) { + /* Directory entries have to be created successively. + For example, the call `fs.root.getDirectory('dir1/dir2', {create:true}, successCallback, errorCallback)` + will fail if dir1 did not exist. */ + var parentName = 'parentName132'; + var nestedName = 'nestedName132'; + var path = parentName + '/' + nestedName; + + var win = function(directory){ + expect(directory).toBeDefined(); + expect(directory.isFile).toBe(false); + expect(directory.isDirectory).toBe(true); + expect(directory.name).toCanonicallyMatch(nestedName); + expect(directory.fullPath).toCanonicallyMatch('/' + path + '/'); + deleteEntry(directory.name); + deleteEntry(parentName, done); + }; + + createDirectory(parentName, function() { + root.getDirectory(parentName + '/' + nestedName, {create:true}, win, + failed.bind(this, done, 'root.getDirectory - Error getting directory : ' + path)); + }, failed.bind(this, done, 'root.getDirectory - Error getting directory : ' + parentName)); + }); + it("file.spec.133 A file being removed should not affect another file with name being a prefix of the removed file name.", function (done) { + + // Names include special symbols so that we check the IndexedDB range used + var deletedFileName = 'deletedFile.0', + secondFileName = 'deletedFile.0.1'; + + var win = function(fileEntry){ + expect(fileEntry).toBeDefined(); + expect(fileEntry.isFile).toBe(true); + expect(fileEntry.isDirectory).toBe(false); + expect(fileEntry.name).toCanonicallyMatch(secondFileName); + deleteEntry(fileEntry.name, done); + }; + + createFile(deletedFileName, function (deletedFile) { + createFile(secondFileName, function () { + deletedFile.remove(function() { + root.getFile(deletedFileName, {create: false}, failed.bind(this, done, 'getFile - unexpected success callback getting deleted file : ' + deletedFileName), function(){ + root.getFile(secondFileName, {create: false}, win, failed.bind(this, done, 'getFile - Error getting file after deleting deletedFile : ' + secondFileName)); + }); + }, failed.bind(this, done, 'remove - Error removing file : ' + deletedFileName)); + }, failed.bind(this, done, 'getFile - Error creating file : ' + secondFileName)); + }, failed.bind(this, done, 'getFile - Error creating file : ' + deletedFileName)); + }); + it("file.spec.134 A directory being removed should not affect another directory with name being a prefix of the removed directory name.", function (done) { + + // Names include special symbols so that we check the IndexedDB range used + var deletedDirName = 'deletedDir.0', + secondDirName = 'deletedDir.0.1'; + + var win = function(directory){ + expect(directory).toBeDefined(); + expect(directory.isFile).toBe(false); + expect(directory.isDirectory).toBe(true); + expect(directory.name).toCanonicallyMatch(secondDirName); + deleteEntry(directory.name, done); + }; + + createDirectory(deletedDirName, function (deletedDir) { + createDirectory(secondDirName, function () { + deletedDir.remove(function() { + root.getDirectory(deletedDirName, {create: false}, failed.bind(this, done, 'getDirectory - unexpected success callback getting deleted directory : ' + deletedDirName), function() { + root.getDirectory(secondDirName, {create: false}, win, failed.bind(this, done, 'getDirectory - Error getting directory after deleting deletedDirectory : ' + secondDirName)); + }); + }, failed.bind(this, done, 'remove - Error removing directory : ' + deletedDirName)); + }, failed.bind(this, done, 'root.getDirectory - Error creating directory : ' + secondDirName)); + }, failed.bind(this, done, 'root.getDirectory - Error creating directory : ' + deletedDirName)); + }); + it("file.spec.135 Deletion of a child directory should not affect the parent directory.", function (done) { + + var parentName = 'parentName135'; + var childName = 'childName135'; + + var win = function(directory){ + expect(directory).toBeDefined(); + expect(directory.isFile).toBe(false); + expect(directory.isDirectory).toBe(true); + expect(directory.name).toCanonicallyMatch(parentName); + deleteEntry(directory.name, done); + }; + + createDirectory(parentName, function(parent){ + parent.getDirectory(childName, {create: true}, function(child){ + child.removeRecursively(function(){ + root.getDirectory(parentName, {create: false}, win, failed.bind(this, done, 'root.getDirectory - Error getting parent directory : ' + parentName)); + }, + failed.bind(this, done, 'getDirectory - Error removing directory : ' + childName)); + }, failed.bind(this, done, 'getDirectory - Error creating directory : ' + childName)); + }, failed.bind(this, done, 'root.getDirectory - Error creating directory : ' + parentName)); + }); + it("file.spec.136 Paths should support Unicode symbols.", function (done) { + + var dirName = '文件插件'; + + var win = function(directory){ + expect(directory).toBeDefined(); + expect(directory.isFile).toBe(false); + expect(directory.isDirectory).toBe(true); + expect(directory.name).toCanonicallyMatch(dirName); + deleteEntry(directory.name, done); + }; + + createDirectory(dirName, function(){ + root.getDirectory(dirName, {create: false}, win, + failed.bind(this, done, 'root.getDirectory - Error getting directory : ' + dirName)); + }, failed.bind(this, done, 'root.getDirectory - Error creating directory : ' + dirName)); + }); + }); + // Content and Asset URLs + if (cordova.platformId == 'android') { + describe('content: URLs', function() { + // Warning: Default HelloWorld www directory structure is required for these tests (www/index.html at least) + function testContentCopy(src, done) { + var file2 = "entry.copy.file2b", + fullPath = joinURL(temp_root.fullPath, file2), + validateFile = function (entry) { + expect(entry.isFile).toBe(true); + expect(entry.isDirectory).toBe(false); + expect(entry.name).toCanonicallyMatch(file2); + expect(entry.fullPath).toCanonicallyMatch(fullPath); + expect(entry.filesystem.name).toEqual("temporary"); + // cleanup + deleteEntry(entry.name, done); + }, + transfer = function () { + resolveLocalFileSystemURL(src, function(entry) { + expect(entry).toBeDefined(); + expect(entry.filesystem.name).toEqual("content"); + entry.copyTo(temp_root, file2, validateFile, failed.bind(null, done, 'entry.copyTo - Error copying file: ' + entry.toURL() + ' to TEMPORAL root as: ' + file2)); + }, failed.bind(null, done, 'resolveLocalFileSystemURL failed for content provider')); + }; + // Delete any existing file to start things off + temp_root.getFile(file2, {}, function (entry) { + entry.remove(transfer, failed.bind(null, done, 'entry.remove - Error removing file: ' + file2)); + }, transfer); + } + it("file.spec.138 copyTo: content", function(done) { + testContentCopy('content://org.apache.cordova.file.testprovider/www/index.html', done); + }); + it("file.spec.139 copyTo: content /w space and query", function(done) { + testContentCopy('content://org.apache.cordova.file.testprovider/?name=foo%20bar&realPath=%2Fwww%2Findex.html', done); + }); + it("file.spec.140 delete: content should fail", function(done) { + resolveLocalFileSystemURL('content://org.apache.cordova.file.testprovider/www/index.html', function(entry) { + entry.remove(failed.bind(null, done, 'expected delete to fail'), done); + }, failed.bind(null, done, 'resolveLocalFileSystemURL failed for content provider')); + }); + }); + + // these tests ensure that you can read and copy from android_asset folder + // for details see https://issues.apache.org/jira/browse/CB-6428 + // and https://mail-archives.apache.org/mod_mbox/cordova-dev/201508.mbox/%3C782154441.8406572.1440182722528.JavaMail.yahoo%40mail.yahoo.com%3E + describe('asset: URLs', function() { + it("file.spec.141 filePaths.applicationStorage", function() { + expect(cordova.file.applicationDirectory).toEqual('file:///android_asset/'); + }, MEDIUM_TIMEOUT); + it("file.spec.142 assets should be enumerable", function(done) { + resolveLocalFileSystemURL('file:///android_asset/www/fixtures/asset-test', function(entry) { + var reader = entry.createReader(); + reader.readEntries(function (entries) { + expect(entries.length).not.toBe(0); + done(); + }, failed.bind(null, done, 'reader.readEntries - Error during reading of entries from assets directory')); + }, failed.bind(null, done, 'resolveLocalFileSystemURL failed for assets')); + }, MEDIUM_TIMEOUT); + it("file.spec.145 asset subdirectories should be obtainable", function(done) { + resolveLocalFileSystemURL('file:///android_asset/www/fixtures', function(entry) { + entry.getDirectory('asset-test', { create: false }, function (subDir) { + expect(subDir).toBeDefined(); + expect(subDir.isFile).toBe(false); + expect(subDir.isDirectory).toBe(true); + expect(subDir.name).toCanonicallyMatch('asset-test'); + done(); + }, failed.bind(null, done, 'entry.getDirectory - Error getting asset subdirectory')); + }, failed.bind(null, done, 'resolveLocalFileSystemURL failed for assets')); + }, MEDIUM_TIMEOUT); + it("file.spec.146 asset files should be readable", function(done) { + resolveLocalFileSystemURL('file:///android_asset/www/fixtures/asset-test/asset-test.txt', function(entry) { + expect(entry.isFile).toBe(true); + entry.file(function (file) { + expect(file).toBeDefined(); + var reader = new FileReader(); + reader.onerror = failed.bind(null, done, 'reader.readAsText - Error reading asset text file'); + reader.onloadend = function () { + expect(this.result).toBeDefined(); + expect(this.result.length).not.toBe(0); + done(); + }; + reader.readAsText(file); + }, failed.bind(null, done, 'entry.file - Error reading asset file')); + }, failed.bind(null, done, 'resolveLocalFileSystemURL failed for assets')); + }, MEDIUM_TIMEOUT); + it("file.spec.143 copyTo: asset -> temporary", function(done) { + var file2 = "entry.copy.file2b", + fullPath = joinURL(temp_root.fullPath, file2), + validateFile = function (entry) { + expect(entry.isFile).toBe(true); + expect(entry.isDirectory).toBe(false); + expect(entry.name).toCanonicallyMatch(file2); + expect(entry.fullPath).toCanonicallyMatch(fullPath); + expect(entry.filesystem.name).toEqual("temporary"); + // cleanup + deleteEntry(entry.name, done); + }, + transfer = function () { + resolveLocalFileSystemURL('file:///android_asset/www/index.html', function(entry) { + expect(entry.filesystem.name).toEqual('assets'); + entry.copyTo(temp_root, file2, validateFile, failed.bind(null, done, 'entry.copyTo - Error copying file: ' + entry.toURL() + ' to TEMPORAL root as: ' + file2)); + }, failed.bind(null, done, 'resolveLocalFileSystemURL failed for assets')); + }; + // Delete any existing file to start things off + temp_root.getFile(file2, {}, function (entry) { + entry.remove(transfer, failed.bind(null, done, 'entry.remove - Error removing file: ' + file2)); + }, transfer); + }, MEDIUM_TIMEOUT); + }); + it("file.spec.144 copyTo: asset directory", function (done) { + var srcUrl = 'file:///android_asset/www/fixtures/asset-test'; + var dstDir = "entry.copy.dstDir"; + var dstPath = joinURL(root.fullPath, dstDir); + // create a new directory entry to kick off it + deleteEntry(dstDir, function () { + resolveLocalFileSystemURL(srcUrl, function(directory) { + directory.copyTo(root, dstDir, function (directory) { + expect(directory).toBeDefined(); + expect(directory.isFile).toBe(false); + expect(directory.isDirectory).toBe(true); + expect(directory.fullPath).toCanonicallyMatch(dstPath); + expect(directory.name).toCanonicallyMatch(dstDir); + root.getDirectory(dstDir, { + create : false + }, function (dirEntry) { + expect(dirEntry).toBeDefined(); + expect(dirEntry.isFile).toBe(false); + expect(dirEntry.isDirectory).toBe(true); + expect(dirEntry.fullPath).toCanonicallyMatch(dstPath); + expect(dirEntry.name).toCanonicallyMatch(dstDir); + dirEntry.getFile('asset-test.txt', { + create : false + }, function (fileEntry) { + expect(fileEntry).toBeDefined(); + expect(fileEntry.isFile).toBe(true); + // cleanup + deleteEntry(dstDir, done); + }, failed.bind(null, done, 'dirEntry.getFile - Error getting subfile')); + }, failed.bind(null, done, 'root.getDirectory - Error getting copied directory')); + }, failed.bind(null, done, 'directory.copyTo - Error copying directory')); + }, failed.bind(null, done, 'resolving src dir')); + }, failed.bind(null, done, 'deleteEntry - Error removing directory : ' + dstDir)); + }, MEDIUM_TIMEOUT); + } + }); + +}; +//****************************************************************************************** +//***************************************Manual Tests*************************************** +//****************************************************************************************** + +exports.defineManualTests = function (contentEl, createActionButton) { + + function resolveFs(fsname) { + var fsURL = "cdvfile://localhost/" + fsname + "/"; + logMessage("Resolving URL: " + fsURL); + resolveLocalFileSystemURL(fsURL, function (entry) { + logMessage("Success", 'green'); + logMessage(entry.toURL(), 'blue'); + logMessage(entry.toInternalURL(), 'blue'); + logMessage("Resolving URL: " + entry.toURL()); + resolveLocalFileSystemURL(entry.toURL(), function (entry2) { + logMessage("Success", 'green'); + logMessage(entry2.toURL(), 'blue'); + logMessage(entry2.toInternalURL(), 'blue'); + }, logError("resolveLocalFileSystemURL")); + }, logError("resolveLocalFileSystemURL")); + } + + function testPrivateURL() { + requestFileSystem(LocalFileSystem.TEMPORARY, 0, function (fileSystem) { + logMessage("Temporary root is at " + fileSystem.root.toNativeURL()); + fileSystem.root.getFile("testfile", { + create : true + }, function (entry) { + logMessage("Temporary file is at " + entry.toNativeURL()); + if (entry.toNativeURL().substring(0, 12) == "file:///var/") { + logMessage("File starts with /var/, trying /private/var"); + var newURL = "file://localhost/private/var/" + entry.toNativeURL().substring(12) + "?and=another_thing"; + //var newURL = entry.toNativeURL(); + logMessage(newURL, 'blue'); + resolveLocalFileSystemURL(newURL, function (newEntry) { + logMessage("Successfully resolved.", 'green'); + logMessage(newEntry.toURL(), 'blue'); + logMessage(newEntry.toNativeURL(), 'blue'); + }, logError("resolveLocalFileSystemURL")); + } + }, logError("getFile")); + }, logError("requestFileSystem")); + } + + function resolveFsContactImage() { + navigator.contacts.pickContact(function(contact) { + var logBox = document.getElementById("logContactBox"); + logBox.innerHTML = ""; + var resolveResult = document.createElement("p"); + if (contact.photos) { + var photoURL = contact.photos[0].value; + resolveLocalFileSystemURL(photoURL, function(entry) { + var contactImage = document.createElement("img"); + var contactLabelImage = document.createElement("p"); + contactLabelImage.innerHTML = "Result contact image"; + contactImage.setAttribute("src", entry.toURL()); + resolveResult.innerHTML = "Success resolve\n" + entry.toURL(); + logBox.appendChild(contactLabelImage); + logBox.appendChild(contactImage); + logBox.appendChild(resolveResult); + }, + function(err) { + console.log("resolve error" + err); + }); + } + else { + resolveResult.innerHTML = "Contact has no photos"; + logBox.appendChild(resolveResult); + } + }, + function(err) { + console.log("contact pick error" + err); + }); + } + + function clearLog() { + var log = document.getElementById("info"); + log.innerHTML = ""; + } + + function logMessage(message, color) { + var log = document.getElementById("info"); + var logLine = document.createElement('div'); + if (color) { + logLine.style.color = color; + } + logLine.innerHTML = message; + log.appendChild(logLine); + } + + function logError(serviceName) { + return function (err) { + logMessage("ERROR: " + serviceName + " " + JSON.stringify(err), "red"); + }; + } + + var fsRoots = { + "ios" : "library,library-nosync,documents,documents-nosync,cache,bundle,root,private", + "osx" : "library,library-nosync,documents,documents-nosync,cache,bundle,root,private", + "android" : "files,files-external,documents,sdcard,cache,cache-external,assets,root", + "amazon-fireos" : "files,files-external,documents,sdcard,cache,cache-external,root", + "windows": "temporary,persistent" + }; + + //Add title and align to content + var div = document.createElement('h2'); + div.appendChild(document.createTextNode('File Systems')); + div.setAttribute("align", "center"); + contentEl.appendChild(div); + + div = document.createElement('h3'); + div.appendChild(document.createTextNode('Results are displayed in yellow status box below with expected results noted under that')); + div.setAttribute("align", "center"); + contentEl.appendChild(div); + + div = document.createElement('div'); + div.setAttribute("id", "button"); + div.setAttribute("align", "center"); + contentEl.appendChild(div); + if (fsRoots.hasOwnProperty(cordova.platformId)) { + (fsRoots[cordova.platformId].split(',')).forEach(function (fs) { + if (cordova.platformId === 'ios' && fs === 'private') { + createActionButton("Test private URL (iOS)", function () { + clearLog(); + testPrivateURL(); + }, 'button'); + } else { + createActionButton(fs, function () { + clearLog(); + resolveFs(fs); + }, 'button'); + } + }); + } + + + div = document.createElement('div'); + div.setAttribute("id", "info"); + div.setAttribute("align", "center"); + contentEl.appendChild(div); + + div = document.createElement('h3'); + div.appendChild(document.createTextNode('For each test above, file or directory should be successfully found. ' + + 'Status box should say Resolving URL was Success. The first URL resolved is the internal URL. ' + + 'The second URL resolved is the absolute URL. Blue URLs must match.')); + contentEl.appendChild(div); + + div = document.createElement('h3'); + div.appendChild(document.createTextNode('For Test private URL (iOS), the private URL (first blue URL in status box) ' + + 'should be successfully resolved. Status box should say Successfully resolved. Both blue URLs below ' + + 'that should match.')); + contentEl.appendChild(div); + + div = document.createElement('h2'); + div.appendChild(document.createTextNode('Resolving content urls')); + div.setAttribute("align", "center"); + contentEl.appendChild(div); + + div = document.createElement('div'); + div.setAttribute("id", "contactButton"); + div.setAttribute("align", "center"); + contentEl.appendChild(div); + + div = document.createElement('div'); + div.setAttribute("id", "logContactBox"); + div.setAttribute("align", "center"); + contentEl.appendChild(div); + + createActionButton('show-contact-image', function () { + resolveFsContactImage(); + }, 'contactButton'); +}; diff --git a/plugins/cordova-plugin-file/tests/www/fixtures/asset-test/asset-test.txt b/plugins/cordova-plugin-file/tests/www/fixtures/asset-test/asset-test.txt new file mode 100644 index 0000000..2ee2df0 --- /dev/null +++ b/plugins/cordova-plugin-file/tests/www/fixtures/asset-test/asset-test.txt @@ -0,0 +1 @@ +This file is here for testing purposes \ No newline at end of file diff --git a/plugins/cordova-plugin-file/types/index.d.ts b/plugins/cordova-plugin-file/types/index.d.ts new file mode 100644 index 0000000..c748e3d --- /dev/null +++ b/plugins/cordova-plugin-file/types/index.d.ts @@ -0,0 +1,378 @@ +// Type definitions for Apache Cordova File System plugin +// Project: https://github.com/apache/cordova-plugin-file +// Definitions by: Microsoft Open Technologies Inc +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// +// Copyright (c) Microsoft Open Technologies, Inc. +// Licensed under the MIT license. + +interface Window { + /** + * Requests a filesystem in which to store application data. + * @param type Whether the filesystem requested should be persistent, as defined above. Use one of TEMPORARY or PERSISTENT. + * @param size This is an indicator of how much storage space, in bytes, the application expects to need. + * @param successCallback The callback that is called when the user agent provides a filesystem. + * @param errorCallback A callback that is called when errors happen, or when the request to obtain the filesystem is denied. + */ + requestFileSystem( + type: LocalFileSystem, + size: number, + successCallback: (fileSystem: FileSystem) => void, + errorCallback?: (fileError: FileError) => void): void; + /** + * Look up file system Entry referred to by local URL. + * @param string url URL referring to a local file or directory + * @param successCallback invoked with Entry object corresponding to URL + * @param errorCallback invoked if error occurs retrieving file system entry + */ + resolveLocalFileSystemURL(url: string, + successCallback: (entry: Entry) => void, + errorCallback?: (error: FileError) => void): void; + /** + * Look up file system Entry referred to by local URI. + * @param string uri URI referring to a local file or directory + * @param successCallback invoked with Entry object corresponding to URI + * @param errorCallback invoked if error occurs retrieving file system entry + */ + resolveLocalFileSystemURI(uri: string, + successCallback: (entry: Entry) => void, + errorCallback?: (error: FileError) => void): void; + TEMPORARY: number; + PERSISTENT: number; +} + +/** This interface represents a file system. */ +interface FileSystem { + /* The name of the file system, unique across the list of exposed file systems. */ + name: string; + /** The root directory of the file system. */ + root: DirectoryEntry; +} + +/** + * An abstract interface representing entries in a file system, + * each of which may be a File or DirectoryEntry. + */ +interface Entry { + /** Entry is a file. */ + isFile: boolean; + /** Entry is a directory. */ + isDirectory: boolean; + /** The name of the entry, excluding the path leading to it. */ + name: string; + /** The full absolute path from the root to the entry. */ + fullPath: string; + /** The file system on which the entry resides. */ + fileSystem: FileSystem; + nativeURL: string; + /** + * Look up metadata about this entry. + * @param successCallback A callback that is called with the time of the last modification. + * @param errorCallback A callback that is called when errors happen. + */ + getMetadata( + successCallback: (metadata: Metadata) => void, + errorCallback?: (error: FileError) => void): void; + /** + * Move an entry to a different location on the file system. It is an error to try to: + * move a directory inside itself or to any child at any depth;move an entry into its parent if a name different from its current one isn't provided; + * move a file to a path occupied by a directory; + * move a directory to a path occupied by a file; + * move any element to a path occupied by a directory which is not empty. + * A move of a file on top of an existing file must attempt to delete and replace that file. + * A move of a directory on top of an existing empty directory must attempt to delete and replace that directory. + * @param parent The directory to which to move the entry. + * @param newName The new name of the entry. Defaults to the Entry's current name if unspecified. + * @param successCallback A callback that is called with the Entry for the new location. + * @param errorCallback A callback that is called when errors happen. + */ + moveTo(parent: DirectoryEntry, + newName?: string, + successCallback?: (entry: Entry) => void, + errorCallback?: (error: FileError) => void): void; + /** + * Copy an entry to a different location on the file system. It is an error to try to: + * copy a directory inside itself or to any child at any depth; + * copy an entry into its parent if a name different from its current one isn't provided; + * copy a file to a path occupied by a directory; + * copy a directory to a path occupied by a file; + * copy any element to a path occupied by a directory which is not empty. + * A copy of a file on top of an existing file must attempt to delete and replace that file. + * A copy of a directory on top of an existing empty directory must attempt to delete and replace that directory. + * Directory copies are always recursive--that is, they copy all contents of the directory. + * @param parent The directory to which to move the entry. + * @param newName The new name of the entry. Defaults to the Entry's current name if unspecified. + * @param successCallback A callback that is called with the Entry for the new object. + * @param errorCallback A callback that is called when errors happen. + */ + copyTo(parent: DirectoryEntry, + newName?: string, + successCallback?: (entry: Entry) => void, + errorCallback?: (error: FileError) => void): void; + /** + * Returns a URL that can be used as the src attribute of a