From afa50236e222fe268b3f184ba99ab78fa49661c9 Mon Sep 17 00:00:00 2001 From: Morgan McMillian Date: Wed, 18 Jul 2018 21:22:02 -0700 Subject: [PATCH] remove the plugin tree for testing --- plugins/android.json | 55 - .../LICENSE | 21 - .../README.md | 271 -- .../package.json | 55 - .../plugin.xml | 44 - .../src/android/IntentShim.java | 794 ---- .../src/android/res/xml/provider_paths.xml | 3 - .../README.md | 172 - ...dova-android-support-gradle-release.gradle | 31 - .../package.json | 39 - .../plugin.xml | 26 - .../properties.gradle | 1 - .../scripts/apply-changes.js | 90 - .../cordova-plugin-console/CONTRIBUTING.md | 37 - plugins/cordova-plugin-console/LICENSE | 202 - plugins/cordova-plugin-console/NOTICE | 5 - plugins/cordova-plugin-console/README.md | 116 - .../cordova-plugin-console/RELEASENOTES.md | 126 - .../cordova-plugin-console/doc/de/README.md | 43 - .../cordova-plugin-console/doc/de/index.md | 41 - .../cordova-plugin-console/doc/es/README.md | 41 - .../cordova-plugin-console/doc/es/index.md | 39 - .../cordova-plugin-console/doc/fr/README.md | 41 - .../cordova-plugin-console/doc/fr/index.md | 39 - .../cordova-plugin-console/doc/it/README.md | 43 - .../cordova-plugin-console/doc/it/index.md | 41 - .../cordova-plugin-console/doc/ja/README.md | 43 - .../cordova-plugin-console/doc/ja/index.md | 41 - .../cordova-plugin-console/doc/ko/README.md | 43 - .../cordova-plugin-console/doc/ko/index.md | 41 - .../cordova-plugin-console/doc/pl/README.md | 43 - .../cordova-plugin-console/doc/pl/index.md | 41 - .../cordova-plugin-console/doc/ru/index.md | 31 - .../cordova-plugin-console/doc/zh/README.md | 43 - .../cordova-plugin-console/doc/zh/index.md | 41 - plugins/cordova-plugin-console/package.json | 80 - plugins/cordova-plugin-console/plugin.xml | 132 - .../src/ios/CDVLogger.h | 26 - .../src/ios/CDVLogger.m | 38 - .../src/ubuntu/console.cpp | 29 - .../src/ubuntu/console.h | 43 - .../src/wp/DebugConsole.cs | 47 - .../cordova-plugin-console/tests/package.json | 14 - .../cordova-plugin-console/tests/plugin.xml | 31 - plugins/cordova-plugin-console/tests/tests.js | 43 - plugins/cordova-plugin-device/CONTRIBUTING.md | 37 - plugins/cordova-plugin-device/LICENSE | 202 - plugins/cordova-plugin-device/NOTICE | 5 - plugins/cordova-plugin-device/README.md | 267 -- plugins/cordova-plugin-device/RELEASENOTES.md | 181 - .../cordova-plugin-device/doc/de/README.md | 203 - plugins/cordova-plugin-device/doc/de/index.md | 206 - .../cordova-plugin-device/doc/es/README.md | 216 - plugins/cordova-plugin-device/doc/es/index.md | 220 - .../cordova-plugin-device/doc/fr/README.md | 215 - plugins/cordova-plugin-device/doc/fr/index.md | 218 - .../cordova-plugin-device/doc/it/README.md | 203 - plugins/cordova-plugin-device/doc/it/index.md | 206 - .../cordova-plugin-device/doc/ja/README.md | 203 - plugins/cordova-plugin-device/doc/ja/index.md | 206 - .../cordova-plugin-device/doc/ko/README.md | 203 - plugins/cordova-plugin-device/doc/ko/index.md | 206 - .../cordova-plugin-device/doc/pl/README.md | 214 - plugins/cordova-plugin-device/doc/pl/index.md | 206 - plugins/cordova-plugin-device/doc/ru/index.md | 219 - .../cordova-plugin-device/doc/zh/README.md | 203 - plugins/cordova-plugin-device/doc/zh/index.md | 206 - plugins/cordova-plugin-device/package.json | 84 - plugins/cordova-plugin-device/plugin.xml | 93 - .../src/android/Device.java | 174 - .../src/browser/DeviceProxy.js | 84 - .../cordova-plugin-device/src/ios/CDVDevice.h | 30 - .../cordova-plugin-device/src/ios/CDVDevice.m | 112 - .../cordova-plugin-device/src/osx/CDVDevice.h | 28 - .../cordova-plugin-device/src/osx/CDVDevice.m | 113 - .../src/windows/DeviceProxy.js | 96 - .../cordova-plugin-device/tests/package.json | 14 - .../cordova-plugin-device/tests/plugin.xml | 31 - plugins/cordova-plugin-device/tests/tests.js | 113 - .../cordova-plugin-device/types/index.d.ts | 36 - .../CONTRIBUTING.md | 37 - plugins/cordova-plugin-file-transfer/LICENSE | 202 - plugins/cordova-plugin-file-transfer/NOTICE | 8 - .../cordova-plugin-file-transfer/README.md | 598 --- .../RELEASENOTES.md | 319 -- .../doc/de/README.md | 311 -- .../doc/de/index.md | 302 -- .../doc/es/README.md | 311 -- .../doc/es/index.md | 262 -- .../doc/fr/README.md | 270 -- .../doc/fr/index.md | 261 -- .../doc/it/README.md | 311 -- .../doc/it/index.md | 302 -- .../doc/ja/README.md | 311 -- .../doc/ja/index.md | 302 -- .../doc/ko/README.md | 311 -- .../doc/ko/index.md | 302 -- .../doc/pl/README.md | 311 -- .../doc/pl/index.md | 302 -- .../doc/ru/index.md | 290 -- .../doc/zh/README.md | 311 -- .../doc/zh/index.md | 302 -- .../cordova-plugin-file-transfer/package.json | 93 - .../cordova-plugin-file-transfer/plugin.xml | 170 - .../src/amazon/FileTransfer.java | 898 ---- .../src/android/FileProgressResult.java | 63 - .../src/android/FileTransfer.java | 932 ---- .../src/android/FileUploadResult.java | 73 - .../src/ios/CDVFileTransfer.h | 89 - .../src/ios/CDVFileTransfer.m | 861 ---- .../src/ubuntu/file-transfer.cpp | 265 -- .../src/ubuntu/file-transfer.h | 103 - .../src/windows/FileTransferProxy.js | 579 --- .../src/wp/FileTransfer.cs | 994 ---- .../tests/package.json | 14 - .../tests/plugin.xml | 34 - .../tests/tests.js | 1739 ------- .../types/index.d.ts | 136 - 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 | 835 ---- plugins/cordova-plugin-file/RELEASENOTES.md | 3 - 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 | 87 - plugins/cordova-plugin-file/plugin.xml | 260 - .../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 | 1225 ----- .../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/browser/FileProxy.js | 984 ---- .../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 | 750 --- 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 --- .../src/windows/FileProxy.js | 1190 ----- .../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 | 4163 ----------------- plugins/cordova-plugin-file/types/index.d.ts | 378 -- .../cordova-plugin-filechooser/LICENSE.txt | 13 - plugins/cordova-plugin-filechooser/README.md | 28 - .../filechooser.png | Bin 38968 -> 0 bytes .../cordova-plugin-filechooser/package.json | 45 - plugins/cordova-plugin-filechooser/plugin.xml | 30 - .../src/android/FileChooser.java | 82 - plugins/cordova-plugin-filepath/CHANGELOG.md | 18 - plugins/cordova-plugin-filepath/LICENSE.md | 202 - plugins/cordova-plugin-filepath/README.md | 44 - plugins/cordova-plugin-filepath/package.json | 56 - plugins/cordova-plugin-filepath/plugin.xml | 58 - .../src/android/FilePath.java | 431 -- .../CONTRIBUTING.md | 64 - plugins/cordova-plugin-inappbrowser/LICENSE | 202 - plugins/cordova-plugin-inappbrowser/NOTICE | 5 - plugins/cordova-plugin-inappbrowser/README.md | 676 --- .../RELEASENOTES.md | 677 --- .../doc/de/README.md | 388 -- .../doc/de/index.md | 357 -- .../doc/es/README.md | 388 -- .../doc/es/index.md | 357 -- .../doc/fr/README.md | 388 -- .../doc/fr/index.md | 357 -- .../doc/it/README.md | 388 -- .../doc/it/index.md | 357 -- .../doc/ja/README.md | 388 -- .../doc/ja/index.md | 357 -- .../doc/ko/README.md | 388 -- .../doc/ko/index.md | 357 -- .../doc/pl/README.md | 388 -- .../doc/pl/index.md | 357 -- .../doc/ru/index.md | 330 -- .../doc/zh/README.md | 388 -- .../doc/zh/index.md | 357 -- .../cordova-plugin-inappbrowser/package.json | 90 - .../cordova-plugin-inappbrowser/plugin.xml | 126 - .../src/android/InAppBrowser.java | 1259 ----- .../src/android/InAppBrowserDialog.java | 57 - .../src/android/InAppChromeClient.java | 133 - .../res/drawable-hdpi/ic_action_next_item.png | Bin 593 -> 0 bytes .../drawable-hdpi/ic_action_previous_item.png | Bin 599 -> 0 bytes .../res/drawable-hdpi/ic_action_remove.png | Bin 438 -> 0 bytes .../res/drawable-mdpi/ic_action_next_item.png | Bin 427 -> 0 bytes .../drawable-mdpi/ic_action_previous_item.png | Bin 438 -> 0 bytes .../res/drawable-mdpi/ic_action_remove.png | Bin 328 -> 0 bytes .../drawable-xhdpi/ic_action_next_item.png | Bin 727 -> 0 bytes .../ic_action_previous_item.png | Bin 744 -> 0 bytes .../res/drawable-xhdpi/ic_action_remove.png | Bin 536 -> 0 bytes .../drawable-xxhdpi/ic_action_next_item.png | Bin 1021 -> 0 bytes .../ic_action_previous_item.png | Bin 1038 -> 0 bytes .../res/drawable-xxhdpi/ic_action_remove.png | Bin 681 -> 0 bytes .../src/browser/InAppBrowserProxy.js | 247 - .../src/ios/CDVInAppBrowser.h | 118 - .../src/ios/CDVInAppBrowser.m | 1144 ----- .../src/osx/CDVInAppBrowser.h | 30 - .../src/osx/CDVInAppBrowser.m | 89 - .../src/windows/InAppBrowserProxy.js | 385 -- .../tests/.eslintrc.yml | 2 - .../tests/package.json | 14 - .../tests/plugin.xml | 33 - .../tests/resources/inject.css | 21 - .../tests/resources/inject.html | 44 - .../tests/resources/inject.js | 20 - .../tests/resources/local.html | 67 - .../tests/resources/local.pdf | Bin 8568 -> 0 bytes .../tests/resources/video.html | 45 - .../tests/tests.js | 696 --- .../types/index.d.ts | 221 - .../cordova-plugin-share-content/README.rst | 21 - .../cordova-plugin-share-content/package.json | 64 - .../cordova-plugin-share-content/plugin.xml | 43 - .../scripts/add_swift_support.js | 173 - .../src/android/ShareContentPlugin.java | 62 - .../ios/ShareContentPlugin-Bridging-Header.h | 6 - .../src/ios/ShareContentPlugin.swift | 25 - .../CONTRIBUTING.md | 37 - plugins/cordova-plugin-splashscreen/LICENSE | 202 - plugins/cordova-plugin-splashscreen/NOTICE | 5 - plugins/cordova-plugin-splashscreen/README.md | 522 --- .../RELEASENOTES.md | 238 - .../doc/de/README.md | 119 - .../doc/de/index.md | 78 - .../doc/es/README.md | 119 - .../doc/es/index.md | 76 - .../doc/fr/README.md | 119 - .../doc/fr/index.md | 78 - .../doc/it/README.md | 119 - .../doc/it/index.md | 78 - .../doc/ja/README.md | 119 - .../doc/ja/index.md | 78 - .../doc/ko/README.md | 119 - .../doc/ko/index.md | 78 - .../doc/pl/README.md | 119 - .../doc/pl/index.md | 78 - .../doc/ru/index.md | 75 - .../doc/zh/README.md | 119 - .../doc/zh/index.md | 78 - .../cordova-plugin-splashscreen/package.json | 83 - .../cordova-plugin-splashscreen/plugin.xml | 82 - .../src/android/SplashScreen.java | 413 -- .../src/browser/SplashScreenProxy.js | 170 - .../src/ios/CDVSplashScreen.h | 46 - .../src/ios/CDVSplashScreen.m | 514 -- .../src/ios/CDVViewController+SplashScreen.h | 28 - .../src/ios/CDVViewController+SplashScreen.m | 89 - .../src/wp/ResolutionHelper.cs | 39 - .../src/wp/SplashScreen.cs | 255 - .../contents.xcworkspacedata | 7 - .../CDVSplashScreenTest.xccheckout | 41 - .../xcschemes/CordovaLib.xcscheme | 77 - .../tests/ios/CDVSplashScreenTest/.npmignore | 1 - .../CDVSplashScreenLibTests/ImageNameTest.m | 702 --- .../ImageNameTestDelegates.h | 57 - .../ImageNameTestDelegates.m | 200 - .../CDVSplashScreenLibTests/Info.plist | 44 - .../project.pbxproj | 505 -- .../contents.xcworkspacedata | 7 - .../CDVSplashScreenTest.xccheckout | 41 - .../xcschemes/CDVSplashScreenLib.xcscheme | 77 - .../CDVSplashScreenLibTests.xcscheme | 96 - .../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 - .../tests/package.json | 14 - .../tests/plugin.xml | 29 - .../tests/tests.js | 64 - .../types/index.d.ts | 17 - .../cordova-plugin-statusbar/CONTRIBUTING.md | 37 - plugins/cordova-plugin-statusbar/LICENSE | 202 - plugins/cordova-plugin-statusbar/NOTICE | 5 - plugins/cordova-plugin-statusbar/README.md | 332 -- .../cordova-plugin-statusbar/RELEASENOTES.md | 172 - .../cordova-plugin-statusbar/doc/de/README.md | 276 -- .../cordova-plugin-statusbar/doc/de/index.md | 262 -- .../cordova-plugin-statusbar/doc/es/README.md | 276 -- .../cordova-plugin-statusbar/doc/es/index.md | 252 - .../cordova-plugin-statusbar/doc/fr/README.md | 276 -- .../cordova-plugin-statusbar/doc/fr/index.md | 262 -- .../cordova-plugin-statusbar/doc/it/README.md | 276 -- .../cordova-plugin-statusbar/doc/it/index.md | 262 -- .../cordova-plugin-statusbar/doc/ja/README.md | 276 -- .../cordova-plugin-statusbar/doc/ja/index.md | 262 -- .../cordova-plugin-statusbar/doc/ko/README.md | 276 -- .../cordova-plugin-statusbar/doc/ko/index.md | 262 -- .../cordova-plugin-statusbar/doc/pl/README.md | 276 -- .../cordova-plugin-statusbar/doc/pl/index.md | 262 -- .../cordova-plugin-statusbar/doc/ru/index.md | 238 - .../cordova-plugin-statusbar/doc/zh/README.md | 276 -- .../cordova-plugin-statusbar/doc/zh/index.md | 262 -- plugins/cordova-plugin-statusbar/package.json | 81 - plugins/cordova-plugin-statusbar/plugin.xml | 99 - .../src/android/StatusBar.java | 276 -- .../src/browser/StatusBarProxy.js | 50 - .../src/ios/CDVStatusBar.h | 50 - .../src/ios/CDVStatusBar.m | 479 -- .../src/windows/StatusBarProxy.js | 114 - .../src/wp/StatusBar.cs | 141 - .../tests/package.json | 14 - .../cordova-plugin-statusbar/tests/plugin.xml | 31 - .../cordova-plugin-statusbar/tests/tests.js | 151 - .../cordova-plugin-statusbar/types/index.d.ts | 77 - .../cordova-plugin-whitelist/CONTRIBUTING.md | 37 - plugins/cordova-plugin-whitelist/LICENSE | 202 - plugins/cordova-plugin-whitelist/NOTICE | 5 - plugins/cordova-plugin-whitelist/README.md | 163 - .../cordova-plugin-whitelist/RELEASENOTES.md | 75 - .../cordova-plugin-whitelist/doc/de/README.md | 148 - .../cordova-plugin-whitelist/doc/es/README.md | 148 - .../cordova-plugin-whitelist/doc/fr/README.md | 148 - .../cordova-plugin-whitelist/doc/it/README.md | 148 - .../cordova-plugin-whitelist/doc/ja/README.md | 148 - .../cordova-plugin-whitelist/doc/ko/README.md | 148 - .../cordova-plugin-whitelist/doc/pl/README.md | 148 - .../cordova-plugin-whitelist/doc/zh/README.md | 148 - plugins/cordova-plugin-whitelist/package.json | 64 - plugins/cordova-plugin-whitelist/plugin.xml | 48 - .../src/android/WhitelistPlugin.java | 161 - plugins/fetch.json | 116 - plugins/ionic-plugin-keyboard/LICENSE | 202 - plugins/ionic-plugin-keyboard/README.md | 128 - plugins/ionic-plugin-keyboard/package.json | 65 - plugins/ionic-plugin-keyboard/plugin.xml | 71 - .../src/android/IonicKeyboard.java | 130 - .../src/blackberry10/index.js | 125 - .../src/blackberry10/native/.cproject | 222 - .../src/blackberry10/native/.project | 76 - .../blackberry10/native/device/libKeyboard.so | Bin 289588 -> 0 bytes .../native/device/public/json_reader.o | Bin 81556 -> 0 bytes .../native/device/public/json_value.o | Bin 91652 -> 0 bytes .../native/device/public/json_writer.o | Bin 133040 -> 0 bytes .../native/device/public/plugin.o | Bin 50576 -> 0 bytes .../native/device/public/tokenizer.o | Bin 23640 -> 0 bytes .../native/device/src/CallKeyboard.o | Bin 5988 -> 0 bytes .../blackberry10/native/device/src/Logger.o | Bin 5192 -> 0 bytes .../native/device/src/keyboard_js.o | Bin 17352 -> 0 bytes .../native/device/src/keyboard_ndk.o | Bin 95672 -> 0 bytes .../native/public/json/autolink.h | 19 - .../blackberry10/native/public/json/config.h | 43 - .../native/public/json/features.h | 42 - .../native/public/json/forwards.h | 39 - .../blackberry10/native/public/json/json.h | 10 - .../blackberry10/native/public/json/reader.h | 196 - .../blackberry10/native/public/json/value.h | 1069 ----- .../blackberry10/native/public/json/writer.h | 174 - .../native/public/json_batchallocator.h | 125 - .../native/public/json_internalarray.inl | 448 -- .../native/public/json_internalmap.inl | 607 --- .../native/public/json_reader.cpp | 892 ---- .../blackberry10/native/public/json_value.cpp | 1726 ------- .../native/public/json_valueiterator.inl | 292 -- .../native/public/json_writer.cpp | 829 ---- .../src/blackberry10/native/public/plugin.cpp | 320 -- .../src/blackberry10/native/public/plugin.h | 70 - .../blackberry10/native/public/tokenizer.cpp | 222 - .../blackberry10/native/public/tokenizer.h | 55 - .../native/simulator/libKeyboard.so | Bin 1455634 -> 0 bytes .../native/simulator/public/json_reader.o | Bin 389836 -> 0 bytes .../native/simulator/public/json_value.o | Bin 526036 -> 0 bytes .../native/simulator/public/json_writer.o | Bin 471916 -> 0 bytes .../native/simulator/public/plugin.o | Bin 400112 -> 0 bytes .../native/simulator/public/tokenizer.o | Bin 145048 -> 0 bytes .../native/simulator/src/CallKeyboard.o | Bin 75616 -> 0 bytes .../native/simulator/src/Logger.o | Bin 55676 -> 0 bytes .../native/simulator/src/keyboard_js.o | Bin 95696 -> 0 bytes .../native/simulator/src/keyboard_ndk.o | Bin 373764 -> 0 bytes .../src/blackberry10/native/src/Logger.cpp | 104 - .../src/blackberry10/native/src/Logger.hpp | 49 - .../blackberry10/native/src/keyboard_js.cpp | 117 - .../blackberry10/native/src/keyboard_js.hpp | 42 - .../blackberry10/native/src/keyboard_ndk.cpp | 155 - .../blackberry10/native/src/keyboard_ndk.hpp | 71 - .../src/ios/IonicKeyboard.h | 16 - .../src/ios/IonicKeyboard.m | 176 - .../src/windows/KeyboardProxy.js | 37 - 424 files changed, 82953 deletions(-) delete mode 100644 plugins/android.json delete mode 100644 plugins/com-darryncampbell-cordova-plugin-intent/LICENSE delete mode 100644 plugins/com-darryncampbell-cordova-plugin-intent/README.md delete mode 100644 plugins/com-darryncampbell-cordova-plugin-intent/package.json delete mode 100644 plugins/com-darryncampbell-cordova-plugin-intent/plugin.xml delete mode 100644 plugins/com-darryncampbell-cordova-plugin-intent/src/android/IntentShim.java delete mode 100644 plugins/com-darryncampbell-cordova-plugin-intent/src/android/res/xml/provider_paths.xml delete mode 100644 plugins/cordova-android-support-gradle-release/README.md delete mode 100644 plugins/cordova-android-support-gradle-release/cordova-android-support-gradle-release.gradle delete mode 100644 plugins/cordova-android-support-gradle-release/package.json delete mode 100644 plugins/cordova-android-support-gradle-release/plugin.xml delete mode 100644 plugins/cordova-android-support-gradle-release/properties.gradle delete mode 100644 plugins/cordova-android-support-gradle-release/scripts/apply-changes.js delete mode 100644 plugins/cordova-plugin-console/CONTRIBUTING.md delete mode 100644 plugins/cordova-plugin-console/LICENSE delete mode 100644 plugins/cordova-plugin-console/NOTICE delete mode 100644 plugins/cordova-plugin-console/README.md delete mode 100644 plugins/cordova-plugin-console/RELEASENOTES.md delete mode 100644 plugins/cordova-plugin-console/doc/de/README.md delete mode 100644 plugins/cordova-plugin-console/doc/de/index.md delete mode 100644 plugins/cordova-plugin-console/doc/es/README.md delete mode 100644 plugins/cordova-plugin-console/doc/es/index.md delete mode 100644 plugins/cordova-plugin-console/doc/fr/README.md delete mode 100644 plugins/cordova-plugin-console/doc/fr/index.md delete mode 100644 plugins/cordova-plugin-console/doc/it/README.md delete mode 100644 plugins/cordova-plugin-console/doc/it/index.md delete mode 100644 plugins/cordova-plugin-console/doc/ja/README.md delete mode 100644 plugins/cordova-plugin-console/doc/ja/index.md delete mode 100644 plugins/cordova-plugin-console/doc/ko/README.md delete mode 100644 plugins/cordova-plugin-console/doc/ko/index.md delete mode 100644 plugins/cordova-plugin-console/doc/pl/README.md delete mode 100644 plugins/cordova-plugin-console/doc/pl/index.md delete mode 100644 plugins/cordova-plugin-console/doc/ru/index.md delete mode 100644 plugins/cordova-plugin-console/doc/zh/README.md delete mode 100644 plugins/cordova-plugin-console/doc/zh/index.md delete mode 100644 plugins/cordova-plugin-console/package.json delete mode 100644 plugins/cordova-plugin-console/plugin.xml delete mode 100644 plugins/cordova-plugin-console/src/ios/CDVLogger.h delete mode 100644 plugins/cordova-plugin-console/src/ios/CDVLogger.m delete mode 100644 plugins/cordova-plugin-console/src/ubuntu/console.cpp delete mode 100644 plugins/cordova-plugin-console/src/ubuntu/console.h delete mode 100644 plugins/cordova-plugin-console/src/wp/DebugConsole.cs delete mode 100644 plugins/cordova-plugin-console/tests/package.json delete mode 100644 plugins/cordova-plugin-console/tests/plugin.xml delete mode 100644 plugins/cordova-plugin-console/tests/tests.js delete mode 100644 plugins/cordova-plugin-device/CONTRIBUTING.md delete mode 100644 plugins/cordova-plugin-device/LICENSE delete mode 100644 plugins/cordova-plugin-device/NOTICE delete mode 100644 plugins/cordova-plugin-device/README.md delete mode 100644 plugins/cordova-plugin-device/RELEASENOTES.md delete mode 100644 plugins/cordova-plugin-device/doc/de/README.md delete mode 100644 plugins/cordova-plugin-device/doc/de/index.md delete mode 100644 plugins/cordova-plugin-device/doc/es/README.md delete mode 100644 plugins/cordova-plugin-device/doc/es/index.md delete mode 100644 plugins/cordova-plugin-device/doc/fr/README.md delete mode 100644 plugins/cordova-plugin-device/doc/fr/index.md delete mode 100644 plugins/cordova-plugin-device/doc/it/README.md delete mode 100644 plugins/cordova-plugin-device/doc/it/index.md delete mode 100644 plugins/cordova-plugin-device/doc/ja/README.md delete mode 100644 plugins/cordova-plugin-device/doc/ja/index.md delete mode 100644 plugins/cordova-plugin-device/doc/ko/README.md delete mode 100644 plugins/cordova-plugin-device/doc/ko/index.md delete mode 100644 plugins/cordova-plugin-device/doc/pl/README.md delete mode 100644 plugins/cordova-plugin-device/doc/pl/index.md delete mode 100644 plugins/cordova-plugin-device/doc/ru/index.md delete mode 100644 plugins/cordova-plugin-device/doc/zh/README.md delete mode 100644 plugins/cordova-plugin-device/doc/zh/index.md delete mode 100644 plugins/cordova-plugin-device/package.json delete mode 100644 plugins/cordova-plugin-device/plugin.xml delete mode 100644 plugins/cordova-plugin-device/src/android/Device.java delete mode 100644 plugins/cordova-plugin-device/src/browser/DeviceProxy.js delete mode 100644 plugins/cordova-plugin-device/src/ios/CDVDevice.h delete mode 100644 plugins/cordova-plugin-device/src/ios/CDVDevice.m delete mode 100644 plugins/cordova-plugin-device/src/osx/CDVDevice.h delete mode 100644 plugins/cordova-plugin-device/src/osx/CDVDevice.m delete mode 100644 plugins/cordova-plugin-device/src/windows/DeviceProxy.js delete mode 100644 plugins/cordova-plugin-device/tests/package.json delete mode 100644 plugins/cordova-plugin-device/tests/plugin.xml delete mode 100644 plugins/cordova-plugin-device/tests/tests.js delete mode 100644 plugins/cordova-plugin-device/types/index.d.ts delete mode 100644 plugins/cordova-plugin-file-transfer/CONTRIBUTING.md delete mode 100644 plugins/cordova-plugin-file-transfer/LICENSE delete mode 100644 plugins/cordova-plugin-file-transfer/NOTICE delete mode 100644 plugins/cordova-plugin-file-transfer/README.md delete mode 100644 plugins/cordova-plugin-file-transfer/RELEASENOTES.md delete mode 100644 plugins/cordova-plugin-file-transfer/doc/de/README.md delete mode 100644 plugins/cordova-plugin-file-transfer/doc/de/index.md delete mode 100644 plugins/cordova-plugin-file-transfer/doc/es/README.md delete mode 100644 plugins/cordova-plugin-file-transfer/doc/es/index.md delete mode 100644 plugins/cordova-plugin-file-transfer/doc/fr/README.md delete mode 100644 plugins/cordova-plugin-file-transfer/doc/fr/index.md delete mode 100644 plugins/cordova-plugin-file-transfer/doc/it/README.md delete mode 100644 plugins/cordova-plugin-file-transfer/doc/it/index.md delete mode 100644 plugins/cordova-plugin-file-transfer/doc/ja/README.md delete mode 100644 plugins/cordova-plugin-file-transfer/doc/ja/index.md delete mode 100644 plugins/cordova-plugin-file-transfer/doc/ko/README.md delete mode 100644 plugins/cordova-plugin-file-transfer/doc/ko/index.md delete mode 100644 plugins/cordova-plugin-file-transfer/doc/pl/README.md delete mode 100644 plugins/cordova-plugin-file-transfer/doc/pl/index.md delete mode 100644 plugins/cordova-plugin-file-transfer/doc/ru/index.md delete mode 100644 plugins/cordova-plugin-file-transfer/doc/zh/README.md delete mode 100644 plugins/cordova-plugin-file-transfer/doc/zh/index.md delete mode 100644 plugins/cordova-plugin-file-transfer/package.json delete mode 100644 plugins/cordova-plugin-file-transfer/plugin.xml delete mode 100644 plugins/cordova-plugin-file-transfer/src/amazon/FileTransfer.java delete mode 100644 plugins/cordova-plugin-file-transfer/src/android/FileProgressResult.java delete mode 100644 plugins/cordova-plugin-file-transfer/src/android/FileTransfer.java delete mode 100644 plugins/cordova-plugin-file-transfer/src/android/FileUploadResult.java delete mode 100644 plugins/cordova-plugin-file-transfer/src/ios/CDVFileTransfer.h delete mode 100644 plugins/cordova-plugin-file-transfer/src/ios/CDVFileTransfer.m delete mode 100644 plugins/cordova-plugin-file-transfer/src/ubuntu/file-transfer.cpp delete mode 100644 plugins/cordova-plugin-file-transfer/src/ubuntu/file-transfer.h delete mode 100644 plugins/cordova-plugin-file-transfer/src/windows/FileTransferProxy.js delete mode 100644 plugins/cordova-plugin-file-transfer/src/wp/FileTransfer.cs delete mode 100644 plugins/cordova-plugin-file-transfer/tests/package.json delete mode 100644 plugins/cordova-plugin-file-transfer/tests/plugin.xml delete mode 100644 plugins/cordova-plugin-file-transfer/tests/tests.js delete mode 100644 plugins/cordova-plugin-file-transfer/types/index.d.ts delete mode 100644 plugins/cordova-plugin-file/CONTRIBUTING.md delete mode 100644 plugins/cordova-plugin-file/LICENSE delete mode 100644 plugins/cordova-plugin-file/NOTICE delete mode 100644 plugins/cordova-plugin-file/README.md delete mode 100644 plugins/cordova-plugin-file/RELEASENOTES.md delete mode 100644 plugins/cordova-plugin-file/doc/de/README.md delete mode 100644 plugins/cordova-plugin-file/doc/de/index.md delete mode 100644 plugins/cordova-plugin-file/doc/de/plugins.md delete mode 100644 plugins/cordova-plugin-file/doc/es/README.md delete mode 100644 plugins/cordova-plugin-file/doc/es/index.md delete mode 100644 plugins/cordova-plugin-file/doc/es/plugins.md delete mode 100644 plugins/cordova-plugin-file/doc/fr/README.md delete mode 100644 plugins/cordova-plugin-file/doc/fr/index.md delete mode 100644 plugins/cordova-plugin-file/doc/fr/plugins.md delete mode 100644 plugins/cordova-plugin-file/doc/it/README.md delete mode 100644 plugins/cordova-plugin-file/doc/it/index.md delete mode 100644 plugins/cordova-plugin-file/doc/it/plugins.md delete mode 100644 plugins/cordova-plugin-file/doc/ja/README.md delete mode 100644 plugins/cordova-plugin-file/doc/ja/index.md delete mode 100644 plugins/cordova-plugin-file/doc/ja/plugins.md delete mode 100644 plugins/cordova-plugin-file/doc/ko/README.md delete mode 100644 plugins/cordova-plugin-file/doc/ko/index.md delete mode 100644 plugins/cordova-plugin-file/doc/ko/plugins.md delete mode 100644 plugins/cordova-plugin-file/doc/pl/README.md delete mode 100644 plugins/cordova-plugin-file/doc/pl/index.md delete mode 100644 plugins/cordova-plugin-file/doc/pl/plugins.md delete mode 100644 plugins/cordova-plugin-file/doc/plugins.md delete mode 100644 plugins/cordova-plugin-file/doc/ru/index.md delete mode 100644 plugins/cordova-plugin-file/doc/ru/plugins.md delete mode 100644 plugins/cordova-plugin-file/doc/zh/README.md delete mode 100644 plugins/cordova-plugin-file/doc/zh/index.md delete mode 100644 plugins/cordova-plugin-file/doc/zh/plugins.md delete mode 100644 plugins/cordova-plugin-file/package.json delete mode 100644 plugins/cordova-plugin-file/plugin.xml delete mode 100644 plugins/cordova-plugin-file/src/android/AssetFilesystem.java delete mode 100644 plugins/cordova-plugin-file/src/android/ContentFilesystem.java delete mode 100644 plugins/cordova-plugin-file/src/android/DirectoryManager.java delete mode 100644 plugins/cordova-plugin-file/src/android/EncodingException.java delete mode 100644 plugins/cordova-plugin-file/src/android/FileExistsException.java delete mode 100644 plugins/cordova-plugin-file/src/android/FileUtils.java delete mode 100644 plugins/cordova-plugin-file/src/android/Filesystem.java delete mode 100644 plugins/cordova-plugin-file/src/android/InvalidModificationException.java delete mode 100644 plugins/cordova-plugin-file/src/android/LocalFilesystem.java delete mode 100644 plugins/cordova-plugin-file/src/android/LocalFilesystemURL.java delete mode 100644 plugins/cordova-plugin-file/src/android/NoModificationAllowedException.java delete mode 100644 plugins/cordova-plugin-file/src/android/PendingRequests.java delete mode 100644 plugins/cordova-plugin-file/src/android/TypeMismatchException.java delete mode 100644 plugins/cordova-plugin-file/src/android/build-extras.gradle delete mode 100644 plugins/cordova-plugin-file/src/browser/FileProxy.js delete mode 100644 plugins/cordova-plugin-file/src/ios/CDVAssetLibraryFilesystem.h delete mode 100644 plugins/cordova-plugin-file/src/ios/CDVAssetLibraryFilesystem.m delete mode 100644 plugins/cordova-plugin-file/src/ios/CDVFile.h delete mode 100644 plugins/cordova-plugin-file/src/ios/CDVFile.m delete mode 100644 plugins/cordova-plugin-file/src/ios/CDVLocalFilesystem.h delete mode 100644 plugins/cordova-plugin-file/src/ios/CDVLocalFilesystem.m delete mode 100644 plugins/cordova-plugin-file/src/osx/CDVFile.h delete mode 100644 plugins/cordova-plugin-file/src/osx/CDVFile.m delete mode 100644 plugins/cordova-plugin-file/src/osx/CDVLocalFilesystem.h delete mode 100644 plugins/cordova-plugin-file/src/osx/CDVLocalFilesystem.m delete mode 100644 plugins/cordova-plugin-file/src/windows/FileProxy.js delete mode 100644 plugins/cordova-plugin-file/tests/package.json delete mode 100644 plugins/cordova-plugin-file/tests/plugin.xml delete mode 100644 plugins/cordova-plugin-file/tests/src/android/TestContentProvider.java delete mode 100644 plugins/cordova-plugin-file/tests/tests.js delete mode 100644 plugins/cordova-plugin-file/types/index.d.ts delete mode 100644 plugins/cordova-plugin-filechooser/LICENSE.txt delete mode 100644 plugins/cordova-plugin-filechooser/README.md delete mode 100644 plugins/cordova-plugin-filechooser/filechooser.png delete mode 100644 plugins/cordova-plugin-filechooser/package.json delete mode 100644 plugins/cordova-plugin-filechooser/plugin.xml delete mode 100644 plugins/cordova-plugin-filechooser/src/android/FileChooser.java delete mode 100644 plugins/cordova-plugin-filepath/CHANGELOG.md delete mode 100644 plugins/cordova-plugin-filepath/LICENSE.md delete mode 100644 plugins/cordova-plugin-filepath/README.md delete mode 100644 plugins/cordova-plugin-filepath/package.json delete mode 100644 plugins/cordova-plugin-filepath/plugin.xml delete mode 100644 plugins/cordova-plugin-filepath/src/android/FilePath.java delete mode 100644 plugins/cordova-plugin-inappbrowser/CONTRIBUTING.md delete mode 100644 plugins/cordova-plugin-inappbrowser/LICENSE delete mode 100644 plugins/cordova-plugin-inappbrowser/NOTICE delete mode 100644 plugins/cordova-plugin-inappbrowser/README.md delete mode 100644 plugins/cordova-plugin-inappbrowser/RELEASENOTES.md delete mode 100644 plugins/cordova-plugin-inappbrowser/doc/de/README.md delete mode 100644 plugins/cordova-plugin-inappbrowser/doc/de/index.md delete mode 100644 plugins/cordova-plugin-inappbrowser/doc/es/README.md delete mode 100644 plugins/cordova-plugin-inappbrowser/doc/es/index.md delete mode 100644 plugins/cordova-plugin-inappbrowser/doc/fr/README.md delete mode 100644 plugins/cordova-plugin-inappbrowser/doc/fr/index.md delete mode 100644 plugins/cordova-plugin-inappbrowser/doc/it/README.md delete mode 100644 plugins/cordova-plugin-inappbrowser/doc/it/index.md delete mode 100644 plugins/cordova-plugin-inappbrowser/doc/ja/README.md delete mode 100644 plugins/cordova-plugin-inappbrowser/doc/ja/index.md delete mode 100644 plugins/cordova-plugin-inappbrowser/doc/ko/README.md delete mode 100644 plugins/cordova-plugin-inappbrowser/doc/ko/index.md delete mode 100644 plugins/cordova-plugin-inappbrowser/doc/pl/README.md delete mode 100644 plugins/cordova-plugin-inappbrowser/doc/pl/index.md delete mode 100644 plugins/cordova-plugin-inappbrowser/doc/ru/index.md delete mode 100644 plugins/cordova-plugin-inappbrowser/doc/zh/README.md delete mode 100644 plugins/cordova-plugin-inappbrowser/doc/zh/index.md delete mode 100644 plugins/cordova-plugin-inappbrowser/package.json delete mode 100644 plugins/cordova-plugin-inappbrowser/plugin.xml delete mode 100644 plugins/cordova-plugin-inappbrowser/src/android/InAppBrowser.java delete mode 100644 plugins/cordova-plugin-inappbrowser/src/android/InAppBrowserDialog.java delete mode 100644 plugins/cordova-plugin-inappbrowser/src/android/InAppChromeClient.java delete mode 100644 plugins/cordova-plugin-inappbrowser/src/android/res/drawable-hdpi/ic_action_next_item.png delete mode 100644 plugins/cordova-plugin-inappbrowser/src/android/res/drawable-hdpi/ic_action_previous_item.png delete mode 100644 plugins/cordova-plugin-inappbrowser/src/android/res/drawable-hdpi/ic_action_remove.png delete mode 100644 plugins/cordova-plugin-inappbrowser/src/android/res/drawable-mdpi/ic_action_next_item.png delete mode 100644 plugins/cordova-plugin-inappbrowser/src/android/res/drawable-mdpi/ic_action_previous_item.png delete mode 100644 plugins/cordova-plugin-inappbrowser/src/android/res/drawable-mdpi/ic_action_remove.png delete mode 100644 plugins/cordova-plugin-inappbrowser/src/android/res/drawable-xhdpi/ic_action_next_item.png delete mode 100644 plugins/cordova-plugin-inappbrowser/src/android/res/drawable-xhdpi/ic_action_previous_item.png delete mode 100644 plugins/cordova-plugin-inappbrowser/src/android/res/drawable-xhdpi/ic_action_remove.png delete mode 100644 plugins/cordova-plugin-inappbrowser/src/android/res/drawable-xxhdpi/ic_action_next_item.png delete mode 100644 plugins/cordova-plugin-inappbrowser/src/android/res/drawable-xxhdpi/ic_action_previous_item.png delete mode 100644 plugins/cordova-plugin-inappbrowser/src/android/res/drawable-xxhdpi/ic_action_remove.png delete mode 100644 plugins/cordova-plugin-inappbrowser/src/browser/InAppBrowserProxy.js delete mode 100644 plugins/cordova-plugin-inappbrowser/src/ios/CDVInAppBrowser.h delete mode 100644 plugins/cordova-plugin-inappbrowser/src/ios/CDVInAppBrowser.m delete mode 100644 plugins/cordova-plugin-inappbrowser/src/osx/CDVInAppBrowser.h delete mode 100644 plugins/cordova-plugin-inappbrowser/src/osx/CDVInAppBrowser.m delete mode 100644 plugins/cordova-plugin-inappbrowser/src/windows/InAppBrowserProxy.js delete mode 100644 plugins/cordova-plugin-inappbrowser/tests/.eslintrc.yml delete mode 100644 plugins/cordova-plugin-inappbrowser/tests/package.json delete mode 100644 plugins/cordova-plugin-inappbrowser/tests/plugin.xml delete mode 100644 plugins/cordova-plugin-inappbrowser/tests/resources/inject.css delete mode 100644 plugins/cordova-plugin-inappbrowser/tests/resources/inject.html delete mode 100644 plugins/cordova-plugin-inappbrowser/tests/resources/inject.js delete mode 100644 plugins/cordova-plugin-inappbrowser/tests/resources/local.html delete mode 100644 plugins/cordova-plugin-inappbrowser/tests/resources/local.pdf delete mode 100644 plugins/cordova-plugin-inappbrowser/tests/resources/video.html delete mode 100644 plugins/cordova-plugin-inappbrowser/tests/tests.js delete mode 100644 plugins/cordova-plugin-inappbrowser/types/index.d.ts delete mode 100644 plugins/cordova-plugin-share-content/README.rst delete mode 100644 plugins/cordova-plugin-share-content/package.json delete mode 100644 plugins/cordova-plugin-share-content/plugin.xml delete mode 100644 plugins/cordova-plugin-share-content/scripts/add_swift_support.js delete mode 100644 plugins/cordova-plugin-share-content/src/android/ShareContentPlugin.java delete mode 100644 plugins/cordova-plugin-share-content/src/ios/ShareContentPlugin-Bridging-Header.h delete mode 100644 plugins/cordova-plugin-share-content/src/ios/ShareContentPlugin.swift delete mode 100644 plugins/cordova-plugin-splashscreen/CONTRIBUTING.md delete mode 100644 plugins/cordova-plugin-splashscreen/LICENSE delete mode 100644 plugins/cordova-plugin-splashscreen/NOTICE delete mode 100644 plugins/cordova-plugin-splashscreen/README.md delete mode 100644 plugins/cordova-plugin-splashscreen/RELEASENOTES.md delete mode 100644 plugins/cordova-plugin-splashscreen/doc/de/README.md delete mode 100644 plugins/cordova-plugin-splashscreen/doc/de/index.md delete mode 100644 plugins/cordova-plugin-splashscreen/doc/es/README.md delete mode 100644 plugins/cordova-plugin-splashscreen/doc/es/index.md delete mode 100644 plugins/cordova-plugin-splashscreen/doc/fr/README.md delete mode 100644 plugins/cordova-plugin-splashscreen/doc/fr/index.md delete mode 100644 plugins/cordova-plugin-splashscreen/doc/it/README.md delete mode 100644 plugins/cordova-plugin-splashscreen/doc/it/index.md delete mode 100644 plugins/cordova-plugin-splashscreen/doc/ja/README.md delete mode 100644 plugins/cordova-plugin-splashscreen/doc/ja/index.md delete mode 100644 plugins/cordova-plugin-splashscreen/doc/ko/README.md delete mode 100644 plugins/cordova-plugin-splashscreen/doc/ko/index.md delete mode 100644 plugins/cordova-plugin-splashscreen/doc/pl/README.md delete mode 100644 plugins/cordova-plugin-splashscreen/doc/pl/index.md delete mode 100644 plugins/cordova-plugin-splashscreen/doc/ru/index.md delete mode 100644 plugins/cordova-plugin-splashscreen/doc/zh/README.md delete mode 100644 plugins/cordova-plugin-splashscreen/doc/zh/index.md delete mode 100644 plugins/cordova-plugin-splashscreen/package.json delete mode 100644 plugins/cordova-plugin-splashscreen/plugin.xml delete mode 100644 plugins/cordova-plugin-splashscreen/src/android/SplashScreen.java delete mode 100644 plugins/cordova-plugin-splashscreen/src/browser/SplashScreenProxy.js delete mode 100644 plugins/cordova-plugin-splashscreen/src/ios/CDVSplashScreen.h delete mode 100644 plugins/cordova-plugin-splashscreen/src/ios/CDVSplashScreen.m delete mode 100644 plugins/cordova-plugin-splashscreen/src/ios/CDVViewController+SplashScreen.h delete mode 100644 plugins/cordova-plugin-splashscreen/src/ios/CDVViewController+SplashScreen.m delete mode 100644 plugins/cordova-plugin-splashscreen/src/wp/ResolutionHelper.cs delete mode 100644 plugins/cordova-plugin-splashscreen/src/wp/SplashScreen.cs delete mode 100644 plugins/cordova-plugin-splashscreen/tests/ios/CDVSplashScreenTest.xcworkspace/contents.xcworkspacedata delete mode 100644 plugins/cordova-plugin-splashscreen/tests/ios/CDVSplashScreenTest.xcworkspace/xcshareddata/CDVSplashScreenTest.xccheckout delete mode 100644 plugins/cordova-plugin-splashscreen/tests/ios/CDVSplashScreenTest.xcworkspace/xcshareddata/xcschemes/CordovaLib.xcscheme delete mode 100644 plugins/cordova-plugin-splashscreen/tests/ios/CDVSplashScreenTest/.npmignore delete mode 100644 plugins/cordova-plugin-splashscreen/tests/ios/CDVSplashScreenTest/CDVSplashScreenLibTests/ImageNameTest.m delete mode 100644 plugins/cordova-plugin-splashscreen/tests/ios/CDVSplashScreenTest/CDVSplashScreenLibTests/ImageNameTestDelegates.h delete mode 100644 plugins/cordova-plugin-splashscreen/tests/ios/CDVSplashScreenTest/CDVSplashScreenLibTests/ImageNameTestDelegates.m delete mode 100644 plugins/cordova-plugin-splashscreen/tests/ios/CDVSplashScreenTest/CDVSplashScreenLibTests/Info.plist delete mode 100644 plugins/cordova-plugin-splashscreen/tests/ios/CDVSplashScreenTest/CDVSplashScreenTest.xcodeproj/project.pbxproj delete mode 100644 plugins/cordova-plugin-splashscreen/tests/ios/CDVSplashScreenTest/CDVSplashScreenTest.xcodeproj/project.xcworkspace/contents.xcworkspacedata delete mode 100644 plugins/cordova-plugin-splashscreen/tests/ios/CDVSplashScreenTest/CDVSplashScreenTest.xcodeproj/project.xcworkspace/xcshareddata/CDVSplashScreenTest.xccheckout delete mode 100644 plugins/cordova-plugin-splashscreen/tests/ios/CDVSplashScreenTest/CDVSplashScreenTest.xcodeproj/xcshareddata/xcschemes/CDVSplashScreenLib.xcscheme delete mode 100644 plugins/cordova-plugin-splashscreen/tests/ios/CDVSplashScreenTest/CDVSplashScreenTest.xcodeproj/xcshareddata/xcschemes/CDVSplashScreenLibTests.xcscheme delete mode 100644 plugins/cordova-plugin-splashscreen/tests/ios/README.md delete mode 100644 plugins/cordova-plugin-splashscreen/tests/ios/doc/de/README.md delete mode 100644 plugins/cordova-plugin-splashscreen/tests/ios/doc/es/README.md delete mode 100644 plugins/cordova-plugin-splashscreen/tests/ios/doc/fr/README.md delete mode 100644 plugins/cordova-plugin-splashscreen/tests/ios/doc/it/README.md delete mode 100644 plugins/cordova-plugin-splashscreen/tests/ios/doc/ja/README.md delete mode 100644 plugins/cordova-plugin-splashscreen/tests/ios/doc/ko/README.md delete mode 100644 plugins/cordova-plugin-splashscreen/tests/ios/doc/pl/README.md delete mode 100644 plugins/cordova-plugin-splashscreen/tests/ios/doc/zh/README.md delete mode 100644 plugins/cordova-plugin-splashscreen/tests/ios/package.json delete mode 100644 plugins/cordova-plugin-splashscreen/tests/package.json delete mode 100644 plugins/cordova-plugin-splashscreen/tests/plugin.xml delete mode 100644 plugins/cordova-plugin-splashscreen/tests/tests.js delete mode 100644 plugins/cordova-plugin-splashscreen/types/index.d.ts delete mode 100644 plugins/cordova-plugin-statusbar/CONTRIBUTING.md delete mode 100644 plugins/cordova-plugin-statusbar/LICENSE delete mode 100644 plugins/cordova-plugin-statusbar/NOTICE delete mode 100644 plugins/cordova-plugin-statusbar/README.md delete mode 100644 plugins/cordova-plugin-statusbar/RELEASENOTES.md delete mode 100644 plugins/cordova-plugin-statusbar/doc/de/README.md delete mode 100644 plugins/cordova-plugin-statusbar/doc/de/index.md delete mode 100644 plugins/cordova-plugin-statusbar/doc/es/README.md delete mode 100644 plugins/cordova-plugin-statusbar/doc/es/index.md delete mode 100644 plugins/cordova-plugin-statusbar/doc/fr/README.md delete mode 100644 plugins/cordova-plugin-statusbar/doc/fr/index.md delete mode 100644 plugins/cordova-plugin-statusbar/doc/it/README.md delete mode 100644 plugins/cordova-plugin-statusbar/doc/it/index.md delete mode 100644 plugins/cordova-plugin-statusbar/doc/ja/README.md delete mode 100644 plugins/cordova-plugin-statusbar/doc/ja/index.md delete mode 100644 plugins/cordova-plugin-statusbar/doc/ko/README.md delete mode 100644 plugins/cordova-plugin-statusbar/doc/ko/index.md delete mode 100644 plugins/cordova-plugin-statusbar/doc/pl/README.md delete mode 100644 plugins/cordova-plugin-statusbar/doc/pl/index.md delete mode 100644 plugins/cordova-plugin-statusbar/doc/ru/index.md delete mode 100644 plugins/cordova-plugin-statusbar/doc/zh/README.md delete mode 100644 plugins/cordova-plugin-statusbar/doc/zh/index.md delete mode 100644 plugins/cordova-plugin-statusbar/package.json delete mode 100644 plugins/cordova-plugin-statusbar/plugin.xml delete mode 100644 plugins/cordova-plugin-statusbar/src/android/StatusBar.java delete mode 100644 plugins/cordova-plugin-statusbar/src/browser/StatusBarProxy.js delete mode 100644 plugins/cordova-plugin-statusbar/src/ios/CDVStatusBar.h delete mode 100644 plugins/cordova-plugin-statusbar/src/ios/CDVStatusBar.m delete mode 100644 plugins/cordova-plugin-statusbar/src/windows/StatusBarProxy.js delete mode 100644 plugins/cordova-plugin-statusbar/src/wp/StatusBar.cs delete mode 100644 plugins/cordova-plugin-statusbar/tests/package.json delete mode 100644 plugins/cordova-plugin-statusbar/tests/plugin.xml delete mode 100644 plugins/cordova-plugin-statusbar/tests/tests.js delete mode 100644 plugins/cordova-plugin-statusbar/types/index.d.ts delete mode 100644 plugins/cordova-plugin-whitelist/CONTRIBUTING.md delete mode 100644 plugins/cordova-plugin-whitelist/LICENSE delete mode 100644 plugins/cordova-plugin-whitelist/NOTICE delete mode 100644 plugins/cordova-plugin-whitelist/README.md delete mode 100644 plugins/cordova-plugin-whitelist/RELEASENOTES.md delete mode 100644 plugins/cordova-plugin-whitelist/doc/de/README.md delete mode 100644 plugins/cordova-plugin-whitelist/doc/es/README.md delete mode 100644 plugins/cordova-plugin-whitelist/doc/fr/README.md delete mode 100644 plugins/cordova-plugin-whitelist/doc/it/README.md delete mode 100644 plugins/cordova-plugin-whitelist/doc/ja/README.md delete mode 100644 plugins/cordova-plugin-whitelist/doc/ko/README.md delete mode 100644 plugins/cordova-plugin-whitelist/doc/pl/README.md delete mode 100644 plugins/cordova-plugin-whitelist/doc/zh/README.md delete mode 100644 plugins/cordova-plugin-whitelist/package.json delete mode 100644 plugins/cordova-plugin-whitelist/plugin.xml delete mode 100644 plugins/cordova-plugin-whitelist/src/android/WhitelistPlugin.java delete mode 100644 plugins/fetch.json delete mode 100644 plugins/ionic-plugin-keyboard/LICENSE delete mode 100644 plugins/ionic-plugin-keyboard/README.md delete mode 100644 plugins/ionic-plugin-keyboard/package.json delete mode 100644 plugins/ionic-plugin-keyboard/plugin.xml delete mode 100644 plugins/ionic-plugin-keyboard/src/android/IonicKeyboard.java delete mode 100644 plugins/ionic-plugin-keyboard/src/blackberry10/index.js delete mode 100644 plugins/ionic-plugin-keyboard/src/blackberry10/native/.cproject delete mode 100644 plugins/ionic-plugin-keyboard/src/blackberry10/native/.project delete mode 100755 plugins/ionic-plugin-keyboard/src/blackberry10/native/device/libKeyboard.so delete mode 100644 plugins/ionic-plugin-keyboard/src/blackberry10/native/device/public/json_reader.o delete mode 100644 plugins/ionic-plugin-keyboard/src/blackberry10/native/device/public/json_value.o delete mode 100644 plugins/ionic-plugin-keyboard/src/blackberry10/native/device/public/json_writer.o delete mode 100644 plugins/ionic-plugin-keyboard/src/blackberry10/native/device/public/plugin.o delete mode 100644 plugins/ionic-plugin-keyboard/src/blackberry10/native/device/public/tokenizer.o delete mode 100644 plugins/ionic-plugin-keyboard/src/blackberry10/native/device/src/CallKeyboard.o delete mode 100644 plugins/ionic-plugin-keyboard/src/blackberry10/native/device/src/Logger.o delete mode 100644 plugins/ionic-plugin-keyboard/src/blackberry10/native/device/src/keyboard_js.o delete mode 100644 plugins/ionic-plugin-keyboard/src/blackberry10/native/device/src/keyboard_ndk.o delete mode 100644 plugins/ionic-plugin-keyboard/src/blackberry10/native/public/json/autolink.h delete mode 100644 plugins/ionic-plugin-keyboard/src/blackberry10/native/public/json/config.h delete mode 100644 plugins/ionic-plugin-keyboard/src/blackberry10/native/public/json/features.h delete mode 100644 plugins/ionic-plugin-keyboard/src/blackberry10/native/public/json/forwards.h delete mode 100644 plugins/ionic-plugin-keyboard/src/blackberry10/native/public/json/json.h delete mode 100644 plugins/ionic-plugin-keyboard/src/blackberry10/native/public/json/reader.h delete mode 100644 plugins/ionic-plugin-keyboard/src/blackberry10/native/public/json/value.h delete mode 100644 plugins/ionic-plugin-keyboard/src/blackberry10/native/public/json/writer.h delete mode 100644 plugins/ionic-plugin-keyboard/src/blackberry10/native/public/json_batchallocator.h delete mode 100644 plugins/ionic-plugin-keyboard/src/blackberry10/native/public/json_internalarray.inl delete mode 100644 plugins/ionic-plugin-keyboard/src/blackberry10/native/public/json_internalmap.inl delete mode 100644 plugins/ionic-plugin-keyboard/src/blackberry10/native/public/json_reader.cpp delete mode 100644 plugins/ionic-plugin-keyboard/src/blackberry10/native/public/json_value.cpp delete mode 100644 plugins/ionic-plugin-keyboard/src/blackberry10/native/public/json_valueiterator.inl delete mode 100644 plugins/ionic-plugin-keyboard/src/blackberry10/native/public/json_writer.cpp delete mode 100644 plugins/ionic-plugin-keyboard/src/blackberry10/native/public/plugin.cpp delete mode 100644 plugins/ionic-plugin-keyboard/src/blackberry10/native/public/plugin.h delete mode 100644 plugins/ionic-plugin-keyboard/src/blackberry10/native/public/tokenizer.cpp delete mode 100644 plugins/ionic-plugin-keyboard/src/blackberry10/native/public/tokenizer.h delete mode 100755 plugins/ionic-plugin-keyboard/src/blackberry10/native/simulator/libKeyboard.so delete mode 100644 plugins/ionic-plugin-keyboard/src/blackberry10/native/simulator/public/json_reader.o delete mode 100644 plugins/ionic-plugin-keyboard/src/blackberry10/native/simulator/public/json_value.o delete mode 100644 plugins/ionic-plugin-keyboard/src/blackberry10/native/simulator/public/json_writer.o delete mode 100644 plugins/ionic-plugin-keyboard/src/blackberry10/native/simulator/public/plugin.o delete mode 100644 plugins/ionic-plugin-keyboard/src/blackberry10/native/simulator/public/tokenizer.o delete mode 100644 plugins/ionic-plugin-keyboard/src/blackberry10/native/simulator/src/CallKeyboard.o delete mode 100644 plugins/ionic-plugin-keyboard/src/blackberry10/native/simulator/src/Logger.o delete mode 100644 plugins/ionic-plugin-keyboard/src/blackberry10/native/simulator/src/keyboard_js.o delete mode 100644 plugins/ionic-plugin-keyboard/src/blackberry10/native/simulator/src/keyboard_ndk.o delete mode 100644 plugins/ionic-plugin-keyboard/src/blackberry10/native/src/Logger.cpp delete mode 100644 plugins/ionic-plugin-keyboard/src/blackberry10/native/src/Logger.hpp delete mode 100644 plugins/ionic-plugin-keyboard/src/blackberry10/native/src/keyboard_js.cpp delete mode 100644 plugins/ionic-plugin-keyboard/src/blackberry10/native/src/keyboard_js.hpp delete mode 100644 plugins/ionic-plugin-keyboard/src/blackberry10/native/src/keyboard_ndk.cpp delete mode 100644 plugins/ionic-plugin-keyboard/src/blackberry10/native/src/keyboard_ndk.hpp delete mode 100644 plugins/ionic-plugin-keyboard/src/ios/IonicKeyboard.h delete mode 100644 plugins/ionic-plugin-keyboard/src/ios/IonicKeyboard.m delete mode 100644 plugins/ionic-plugin-keyboard/src/windows/KeyboardProxy.js diff --git a/plugins/android.json b/plugins/android.json deleted file mode 100644 index 8dfb4a6..0000000 --- a/plugins/android.json +++ /dev/null @@ -1,55 +0,0 @@ -{ - "prepare_queue": { - "installed": [], - "uninstalled": [] - }, - "config_munge": { - "files": {} - }, - "installed_plugins": { - "cordova-plugin-filechooser": { - "PACKAGE_NAME": "com.monkeystew.goober_m" - }, - "cordova-plugin-share-content": { - "PACKAGE_NAME": "com.monkeystew.goober_m" - }, - "ionic-plugin-keyboard": { - "PACKAGE_NAME": "com.monkeystew.goober_m" - }, - "cordova-plugin-file": { - "PACKAGE_NAME": "com.monkeystew.goober_m" - }, - "cordova-plugin-file-transfer": { - "PACKAGE_NAME": "com.monkeystew.goober_m" - }, - "com-darryncampbell-cordova-plugin-intent": { - "PACKAGE_NAME": "com.monkeystew.goober_m" - }, - "cordova-plugin-inappbrowser": { - "PACKAGE_NAME": "com.monkeystew.goober_m" - }, - "cordova-plugin-whitelist": { - "PACKAGE_NAME": "com.monkeystew.goober_m" - }, - "cordova-plugin-statusbar": { - "PACKAGE_NAME": "com.monkeystew.goober_m" - }, - "cordova-plugin-splashscreen": { - "PACKAGE_NAME": "com.monkeystew.goober_m" - }, - "cordova-plugin-device": { - "PACKAGE_NAME": "com.monkeystew.goober_m" - }, - "cordova-plugin-console": { - "PACKAGE_NAME": "com.monkeystew.goober_m" - }, - "cordova-android-support-gradle-release": { - "ANDROID_SUPPORT_VERSION": "27.+", - "PACKAGE_NAME": "com.monkeystew.goober_m" - }, - "cordova-plugin-filepath": { - "PACKAGE_NAME": "com.monkeystew.goober_m" - } - }, - "dependent_plugins": {} -} \ No newline at end of file diff --git a/plugins/com-darryncampbell-cordova-plugin-intent/LICENSE b/plugins/com-darryncampbell-cordova-plugin-intent/LICENSE deleted file mode 100644 index 65d8f14..0000000 --- a/plugins/com-darryncampbell-cordova-plugin-intent/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2017 Darryn - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/plugins/com-darryncampbell-cordova-plugin-intent/README.md b/plugins/com-darryncampbell-cordova-plugin-intent/README.md deleted file mode 100644 index e300ba3..0000000 --- a/plugins/com-darryncampbell-cordova-plugin-intent/README.md +++ /dev/null @@ -1,271 +0,0 @@ -*This plugin is provided without guarantee or warranty* -========================================================= - -[![npm version](http://img.shields.io/npm/v/com-darryncampbell-cordova-plugin-intent.svg?style=flat-square)](https://npmjs.org/package/com-darryncampbell-cordova-plugin-intent "View this project on npm") -[![npm downloads](http://img.shields.io/npm/dm/com-darryncampbell-cordova-plugin-intent.svg?style=flat-square)](https://npmjs.org/package/com-darryncampbell-cordova-plugin-intent "View this project on npm") -[![npm downloads](http://img.shields.io/npm/dt/com-darryncampbell-cordova-plugin-intent.svg?style=flat-square)](https://npmjs.org/package/com-darryncampbell-cordova-plugin-intent "View this project on npm") -[![npm licence](http://img.shields.io/npm/l/com-darryncampbell-cordova-plugin-intent.svg?style=flat-square)](https://npmjs.org/package/com-darryncampbell-cordova-plugin-intent "View this project on npm") - -Note: this is the current underlying implementation for https://www.npmjs.com/package/@ionic-native/web-intent and https://ionicframework.com/docs/native/web-intent/ - -# Interaction with Camera Plugin -If you are installing this plugin along with cordova-plugin-camera you **MUST install cordova-plugin-camera first.** - -# Overview -This Cordova plugin provides a general purpose shim layer for the Android intent mechanism, exposing various ways to handle sending and receiving intents. - -## Credits -This project uses code released under the following MIT projects: -- https://github.com/napolitano/cordova-plugin-intent (marked as no longer maintained) -- https://github.com/Initsogar/cordova-webintent.git (no longer available on github but the project is forked here: https://github.com/darryncampbell/cordova-webintent) -This project is also released under MIT. Credit is given in the code where appropriate - -## IntentShim -This plugin defines a `window.plugins.intentShim` object which provides an API for interacting with the Android intent mechanism on any Android device. - -## Testing / Example -An example application is available at https://github.com/darryncampbell/plugin-intent-api-exerciser to demonstrate the API and can be used to test the functionality. - -## Installation - -### Cordova Version < 7 - cordova plugin add https://github.com/darryncampbell/darryncampbell-cordova-plugin-intent.git - -### Cordova Version >= 7 - cordova plugin add com-darryncampbell-cordova-plugin-intent - -## Supported Platforms -- Android - -## intentShim.registerBroadcastReceiver - -Registers a broadcast receiver for the specified filters - - window.plugins.intentShim.registerBroadcastReceiver(filters, callback); - -### Description - -The `intentShim.registerBroadcastReceiver` function registers a dynamic broadcast receiver for the specified list of filters and invokes the specified callback when any of those filters are received - -### Android Quirks - -Any existing broadcast receiver is unregistered when this method is called. To register for multiple types of broadcast, specify multiple filters. - -### Example - -Register a broadcast receiver for two filters: - - window.plugins.intentShim.registerBroadcastReceiver({ - filterActions: [ - 'com.darryncampbell.cordova.plugin.broadcastIntent.ACTION', - 'com.darryncampbell.cordova.plugin.broadcastIntent.ACTION_2' - ] - }, - function(intent) { - console.log('Received broadcast intent: ' + JSON.stringify(intent.extras)); - } - ); - - -## intentShim.unregisterBroadcastReceiver - -Unregisters the broadcast receiver - - window.plugins.intentShim.unregisterBroadcastReceiver(); - -### Description - -The `intentShim.unregisterBroadcastReceiver` function unregisters the broadcast receiver registered with `intentShim.registerBroadcastReceiver(filters, callback);`. No further broadcasts will be received for any registered filter after this call. - -### Android Quirks - -The developer is responsible for calling unregister / register when their application goes into the background or comes back to the foreground, if desired. - -### Example - -Unregister the broadcast receiver when the application receives an onPause event: - - bindEvents: function() { - document.addEventListener('pause', this.onPause, false); - }, - onPause: function() - { - window.plugins.intentShim.unregisterBroadcastReceiver(); - } - -## intentShim.sendBroadcast - -Sends a broadcast intent - - window.plugins.intentShim.sendBroadcast(action, extras, successCallback, failureCallback); - -### Description - -The `intentShim.sendBroadcast` function sends an Android broadcast intent with a specified action - -### Example - -Send a broadcast intent to a specified action that contains a random number in the extras - - window.plugins.intentShim.startActivity( - { - action: "com.darryncampbell.cordova.plugin.intent.ACTION", - extras: { - 'random.number': Math.floor((Math.random() * 1000) + 1) - } - }, - function() {}, - function() {alert('Failed to open URL via Android Intent')} - ); - - -## intentShim.onIntent - -Returns the content of the intent used whenever the application activity is launched - - window.plugins.intentShim.onIntent(callback); - -### Description - -The `intentShim.onIntent` function returns the intent which launched the Activity and maps to the Android Activity's onNewIntent() method, https://developer.android.com/reference/android/app/Activity.html#onNewIntent(android.content.Intent). The registered callback is invoked whenever the activity is launched - -### Android Quirks - -By default the android application will be created with launch mode set to 'SingleTop'. If you wish to change this to 'SingleTask' you can do so by modifying `config.xml` as follows: - - - ... - - -See https://www.mobomo.com/2011/06/android-understanding-activity-launchmode/ for more information on the differences between the two. - -### Example - -Registers a callback to be invoked - - window.plugins.intentShim.onIntent(function (intent) { - console.log('Received Intent: ' + JSON.stringify(intent.extras)); - }); - -## intentShim.startActivity - -Starts a new activity using an intent built from action, url, type, extras or some subset of those parameters - - window.plugins.intentShim.startActivity(params, successCallback, failureCallback); - -### Description - -The `intentShim.startActivity` function maps to Android's activity method startActivity, https://developer.android.com/reference/android/app/Activity.html#startActivity(android.content.Intent) to launch a new activity. - -### Android Quirks - -Some common actions are defined as constants in the plugin, see below. - -### Examples - -Launch the maps activity - - window.plugins.intentShim.startActivity( - { - action: window.plugins.intentShim.ACTION_VIEW, - url: 'geo:0,0?q=London' - }, - function() {}, - function() {alert('Failed to open URL via Android Intent')} - ); - -Launch the web browser - - window.plugins.intentShim.startActivity( - { - action: window.plugins.intentShim.ACTION_VIEW, - url: 'http://www.google.co.uk' - }, - function() {}, - function() {alert('Failed to open URL via Android Intent')} - ); - -## intentShim.getIntent - -Retrieves the intent that launched the activity - - window.plugins.intentShim.getIntent(resultCallback, failureCallback); - -### Description - -The `intentShim.getIntent` function maps to Android's activity method getIntent, https://developer.android.com/reference/android/app/Activity.html#getIntent() to return the intent that started this activity. - -### Example - - window.plugins.intentShim.getIntent( - function(intent) - { - console.log('Action' + JSON.stringify(intent.action)); - var intentExtras = intent.extras; - if (intentExtras == null) - intentExtras = "No extras in intent"; - console.log('Launch Intent Extras: ' + JSON.stringify(intentExtras)); - }, - function() - { - console.log('Error getting launch intent'); - }); - - -## intentShim.startActivityForResult - -Starts a new activity and return the result to the application - - window.plugins.intentShim.startActivityForResult(params, resultCallback, failureCallback); - -### Description - -The `intentShim.startActivityForResult` function maps to Android's activity method startActivityForResult, https://developer.android.com/reference/android/app/Activity.html#startActivityForResult(android.content.Intent, int) to launch a new activity and the resulting data is returned via the resultCallback. - -### Android Quirks - -Some common actions are defined as constants in the plugin, see below. - -### Example - -Pick an Android contact - - window.plugins.intentShim.startActivityForResult( - { - action: window.plugins.intentShim.ACTION_PICK, - url: "content://com.android.contacts/contacts", - requestCode: 1 - }, - function(intent) - { - if (intent.extras.requestCode == 1) - { - console.log('Picked contact: ' + intent.data); - } - }, - function() - { - console.log("StartActivityForResult failure"); - }); - - -## Predefined Constants - -The following constants are defined in the plugin for use in JavaScript -- window.plugins.intentShim.ACTION_SEND -- window.plugins.intentShim.ACTION_VIEW -- window.plugins.intentShim.EXTRA_TEXT -- window.plugins.intentShim.EXTRA_SUBJECT -- window.plugins.intentShim.EXTRA_STREAM -- window.plugins.intentShim.EXTRA_EMAIL -- window.plugins.intentShim.ACTION_CALL -- window.plugins.intentShim.ACTION_SENDTO -- window.plugins.intentShim.ACTION_GET_CONTENT -- window.plugins.intentShim.ACTION_PICK - -## Tested Versions - -Tested with Cordova version 6.5.0 and Cordova Android version 6.2.1 - - - diff --git a/plugins/com-darryncampbell-cordova-plugin-intent/package.json b/plugins/com-darryncampbell-cordova-plugin-intent/package.json deleted file mode 100644 index 7fdfa1a..0000000 --- a/plugins/com-darryncampbell-cordova-plugin-intent/package.json +++ /dev/null @@ -1,55 +0,0 @@ -{ - "_from": "com-darryncampbell-cordova-plugin-intent@^1.1.0", - "_id": "com-darryncampbell-cordova-plugin-intent@1.1.0", - "_inBundle": false, - "_integrity": "sha512-KPyU4RlOl1ofliMSyHms3eyyzIAvRCEpGda5T8j3XXmYeU0YdLG7UeHat84eJWByjv8K7XhMbVu841DnipPrLg==", - "_location": "/com-darryncampbell-cordova-plugin-intent", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "com-darryncampbell-cordova-plugin-intent@^1.1.0", - "name": "com-darryncampbell-cordova-plugin-intent", - "escapedName": "com-darryncampbell-cordova-plugin-intent", - "rawSpec": "^1.1.0", - "saveSpec": null, - "fetchSpec": "^1.1.0" - }, - "_requiredBy": [ - "#USER", - "/" - ], - "_resolved": "https://registry.npmjs.org/com-darryncampbell-cordova-plugin-intent/-/com-darryncampbell-cordova-plugin-intent-1.1.0.tgz", - "_shasum": "ab7506183a9d171d6448e79c9722f2526f8a7efc", - "_spec": "com-darryncampbell-cordova-plugin-intent@^1.1.0", - "_where": "/home/thrrgilag/workspace/cordova/Goober", - "author": { - "name": "Darryn Campbell" - }, - "bugs": { - "url": "https://github.com/darryncampbell/darryncampbell-cordova-plugin-intent/issues" - }, - "bundleDependencies": false, - "cordova": { - "id": "com-darryncampbell-cordova-plugin-intent", - "platforms": [ - "android" - ] - }, - "deprecated": false, - "description": "General purpose intent shim layer for cordova appliations on Android. Handles various techniques for sending and receiving intents.", - "homepage": "https://github.com/darryncampbell/darryncampbell-cordova-plugin-intent#readme", - "keywords": [ - "ecosystem:cordova", - "cordova-android", - "Intent" - ], - "license": "MIT", - "main": "intentShim.js", - "name": "com-darryncampbell-cordova-plugin-intent", - "repository": { - "type": "git", - "url": "git+https://github.com/darryncampbell/darryncampbell-cordova-plugin-intent.git" - }, - "version": "1.1.0" -} diff --git a/plugins/com-darryncampbell-cordova-plugin-intent/plugin.xml b/plugins/com-darryncampbell-cordova-plugin-intent/plugin.xml deleted file mode 100644 index e5f233f..0000000 --- a/plugins/com-darryncampbell-cordova-plugin-intent/plugin.xml +++ /dev/null @@ -1,44 +0,0 @@ - - - Intent Shim - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/plugins/com-darryncampbell-cordova-plugin-intent/src/android/IntentShim.java b/plugins/com-darryncampbell-cordova-plugin-intent/src/android/IntentShim.java deleted file mode 100644 index b67978e..0000000 --- a/plugins/com-darryncampbell-cordova-plugin-intent/src/android/IntentShim.java +++ /dev/null @@ -1,794 +0,0 @@ -package com.darryncampbell.cordova.plugin.intent; - -import android.Manifest; -import android.app.Activity; -import android.content.BroadcastReceiver; -import android.content.ClipData; -import android.content.ComponentName; -import android.content.ContentResolver; -import android.content.Context; -import android.content.Intent; -import android.content.IntentFilter; -import android.content.pm.PackageManager; -import android.database.Cursor; -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.support.v4.app.ActivityCompat; -import android.support.v4.content.ContextCompat; -import android.support.v4.content.FileProvider; -import android.text.Html; -import android.util.Log; -import android.webkit.MimeTypeMap; - -import org.apache.cordova.CallbackContext; -import org.apache.cordova.CordovaActivity; -import org.apache.cordova.CordovaPlugin; -import org.apache.cordova.CordovaResourceApi; -import org.apache.cordova.PluginResult; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import java.io.File; - -import java.lang.reflect.Array; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -import static android.os.Environment.getExternalStorageDirectory; -import static android.os.Environment.getExternalStorageState; - -public class IntentShim extends CordovaPlugin { - - private static final String LOG_TAG = "Cordova Intents Shim"; - private CallbackContext onNewIntentCallbackContext = null; - private CallbackContext onBroadcastCallbackContext = null; - private CallbackContext onActivityResultCallbackContext = null; - - private Intent deferredIntent = null; - - public IntentShim() { - - } - - public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException - { - Log.d(LOG_TAG, "Action: " + action); - if (action.equals("startActivity") || action.equals("startActivityForResult")) - { - // Credit: https://github.com/chrisekelley/cordova-webintent - if (args.length() != 1) { - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.INVALID_ACTION)); - return false; - } - - JSONObject obj = args.getJSONObject(0); - Intent intent = populateIntent(obj, callbackContext); - int requestCode = obj.has("requestCode") ? obj.getInt("requestCode") : 1; - - boolean bExpectResult = false; - if (action.equals("startActivityForResult")) - { - bExpectResult = true; - this.onActivityResultCallbackContext = callbackContext; - } - startActivity(intent, bExpectResult, requestCode, callbackContext); - - return true; - } - else if (action.equals("sendBroadcast")) - { - // Credit: https://github.com/chrisekelley/cordova-webintent - if (args.length() != 1) { - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.INVALID_ACTION)); - return false; - } - - // Parse the arguments - JSONObject obj = args.getJSONObject(0); - Intent intent = populateIntent(obj, callbackContext); - - sendBroadcast(intent); - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK)); - return true; - } - else if (action.equals("startService")) - { - if (args.length() != 1) { - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.INVALID_ACTION)); - return false; - } - JSONObject obj = args.getJSONObject(0); - Intent intent = populateIntent(obj, callbackContext); - startService(intent); - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK)); - return true; - } - else if (action.equals("registerBroadcastReceiver")) { - try - { - // Ensure we only have a single registered broadcast receiver - ((CordovaActivity)this.cordova.getActivity()).unregisterReceiver(myBroadcastReceiver); - } - catch (IllegalArgumentException e) {} - - // No error callback - if(args.length() != 1) { - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.INVALID_ACTION)); - return false; - } - - // Expect an array of filterActions - JSONObject obj = args.getJSONObject(0); - JSONArray filterActions = obj.has("filterActions") ? obj.getJSONArray("filterActions") : null; - if (filterActions == null || filterActions.length() == 0) - { - // The arguments are not correct - Log.w(LOG_TAG, "filterActions argument is not in the expected format"); - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.INVALID_ACTION)); - return false; - } - - this.onBroadcastCallbackContext = callbackContext; - - PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT); - result.setKeepCallback(true); - - IntentFilter filter = new IntentFilter(); - for (int i = 0; i < filterActions.length(); i++) { - Log.d(LOG_TAG, "Registering broadcast receiver for filter: " + filterActions.getString(i)); - filter.addAction(filterActions.getString(i)); - } - - // Allow an array of filterCategories - JSONArray filterCategories = obj.has("filterCategories") ? obj.getJSONArray("filterCategories") : null; - if (filterCategories != null) { - for (int i = 0; i < filterCategories.length(); i++) { - Log.d(LOG_TAG, "Registering broadcast receiver for category filter: " + filterCategories.getString(i)); - filter.addCategory(filterCategories.getString(i)); - } - } - - // Add any specified Data Schemes - // https://github.com/darryncampbell/darryncampbell-cordova-plugin-intent/issues/24 - JSONArray filterDataSchemes = obj.has("filterDataSchemes") ? obj.getJSONArray("filterDataSchemes") : null; - if (filterDataSchemes != null && filterDataSchemes.length() > 0) - { - for (int i = 0; i < filterDataSchemes.length(); i++) - { - Log.d(LOG_TAG, "Associating data scheme to filter: " + filterDataSchemes.getString(i)); - filter.addDataScheme(filterDataSchemes.getString(i)); - } - } - - ((CordovaActivity)this.cordova.getActivity()).registerReceiver(myBroadcastReceiver, filter); - - callbackContext.sendPluginResult(result); - } - else if (action.equals("unregisterBroadcastReceiver")) - { - try - { - ((CordovaActivity)this.cordova.getActivity()).unregisterReceiver(myBroadcastReceiver); - } - catch (IllegalArgumentException e) {} - } - else if (action.equals("onIntent")) - { - // Credit: https://github.com/napolitano/cordova-plugin-intent - if(args.length() != 1) { - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.INVALID_ACTION)); - return false; - } - - this.onNewIntentCallbackContext = callbackContext; - - if (this.deferredIntent != null) { - fireOnNewIntent(this.deferredIntent); - this.deferredIntent = null; - } - - PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT); - result.setKeepCallback(true); - callbackContext.sendPluginResult(result); - return true; - } - else if (action.equals("onActivityResult")) - { - if(args.length() != 1) { - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.INVALID_ACTION)); - return false; - } - - this.onActivityResultCallbackContext = callbackContext; - - PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT); - result.setKeepCallback(true); - callbackContext.sendPluginResult(result); - return true; - } - else if (action.equals("getIntent")) - { - // Credit: https://github.com/napolitano/cordova-plugin-intent - if(args.length() != 0) { - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.INVALID_ACTION)); - return false; - } - - Intent intent; - - if (this.deferredIntent != null) { - intent = this.deferredIntent; - this.deferredIntent = null; - } - else { - intent = cordova.getActivity().getIntent(); - } - - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, getIntentJson(intent))); - return true; - } - else if (action.equals("sendResult")) - { - // Assuming this application was started with startActivityForResult, send the result back - // https://github.com/darryncampbell/darryncampbell-cordova-plugin-intent/issues/3 - Intent result = new Intent(); - if (args.length() > 0) - { - JSONObject json = args.getJSONObject(0); - JSONObject extras = (json.has("extras"))?json.getJSONObject("extras"):null; - - // Populate the extras if any exist - if (extras != null) { - JSONArray extraNames = extras.names(); - for (int i = 0; i < extraNames.length(); i++) { - String key = extraNames.getString(i); - String value = extras.getString(key); - result.putExtra(key, value); - } - } - } - - //set result - cordova.getActivity().setResult(Activity.RESULT_OK, result); - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK)); - - //finish the activity - cordova.getActivity().finish(); - - } - else if (action.equals("realPathFromUri")) - { - if (args.length() != 1) { - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.INVALID_ACTION)); - return false; - } - - JSONObject obj = args.getJSONObject(0); - String realPath = getRealPathFromURI_API19(obj, callbackContext); - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, realPath)); - return true; - - } - - return true; - } - - private Uri remapUriWithFileProvider(String uriAsString, final CallbackContext callbackContext) - { - // Create the URI via FileProvider Special case for N and above when installing apks - int permissionCheck = ContextCompat.checkSelfPermission(this.cordova.getActivity(), - Manifest.permission.READ_EXTERNAL_STORAGE); - if (permissionCheck != PackageManager.PERMISSION_GRANTED) - { - // Could do better here - if the app does not already have permission should - // only continue when we get the success callback from this. - ActivityCompat.requestPermissions(this.cordova.getActivity(), - new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1); - callbackContext.error("Please grant read external storage permission"); - return null; - } - - try - { - String externalStorageState = getExternalStorageState(); - if (externalStorageState.equals(Environment.MEDIA_MOUNTED) || externalStorageState.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) { - String fileName = uriAsString.substring(uriAsString.indexOf('/') + 2, uriAsString.length()); - File uriAsFile = new File(fileName); - boolean fileExists = uriAsFile.exists(); - if (!fileExists) - { - Log.e(LOG_TAG, "File at path " + uriAsFile.getPath() + " with name " + uriAsFile.getName() + "does not exist"); - callbackContext.error("File not found: " + uriAsFile.toString()); - return null; - } - String PACKAGE_NAME = this.cordova.getActivity().getPackageName() + ".provider"; - Uri uri = FileProvider.getUriForFile(this.cordova.getActivity().getApplicationContext(), PACKAGE_NAME, uriAsFile); - return uri; - } - else - { - Log.e(LOG_TAG, "Storage directory is not mounted. Please ensure the device is not connected via USB for file transfer"); - callbackContext.error("Storage directory is returning not mounted"); - return null; - } - } - catch(StringIndexOutOfBoundsException e) - { - Log.e(LOG_TAG, "URL is not well formed"); - callbackContext.error("URL is not well formed"); - return null; - } - } - - private String getRealPathFromURI_API19(JSONObject obj, CallbackContext callbackContext) throws JSONException - { - // Credit: https://stackoverflow.com/questions/2789276/android-get-real-path-by-uri-getpath/2790688 - Uri uri = obj.has("uri") ? Uri.parse(obj.getString("uri")) : null; - if (uri == null) - { - Log.w(LOG_TAG, "URI is not a specified parameter"); - throw new JSONException("URI is not a specified parameter"); - } - if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) { - String filePath = ""; - if (uri.getHost().contains("com.android.providers.media")) { - int permissionCheck = ContextCompat.checkSelfPermission(this.cordova.getActivity(), - Manifest.permission.READ_EXTERNAL_STORAGE); - if (permissionCheck != PackageManager.PERMISSION_GRANTED) - { - // Could do better here - if the app does not already have permission should - // only continue when we get the success callback from this. - ActivityCompat.requestPermissions(this.cordova.getActivity(), - new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1); - callbackContext.error("Please grant read external storage permission"); - return null; - } - - // Image pick from recent - String wholeID = DocumentsContract.getDocumentId(uri); - - // Split at colon, use second item in the array - String id = wholeID.split(":")[1]; - - String[] column = {MediaStore.Images.Media.DATA}; - - // where id is equal to - String sel = MediaStore.Images.Media._ID + "=?"; - - // This line requires read storage permission - - Cursor cursor = this.cordova.getActivity().getApplicationContext().getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, - column, sel, new String[]{id}, null); - - int columnIndex = cursor.getColumnIndex(column[0]); - - if (cursor.moveToFirst()) { - filePath = cursor.getString(columnIndex); - } - cursor.close(); - return filePath; - } else { - // image pick from gallery - String[] proj = {MediaStore.Images.Media.DATA}; - Cursor cursor = this.cordova.getActivity().getApplicationContext().getContentResolver().query(uri, proj, null, null, null); - int column_index - = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); - cursor.moveToFirst(); - return cursor.getString(column_index); - } - } - - return "Requires KK or higher"; - } - - private void startActivity(Intent i, boolean bExpectResult, int requestCode, CallbackContext callbackContext) { - - if (i.resolveActivityInfo(this.cordova.getActivity().getPackageManager(), 0) != null) - { - if (bExpectResult) - { - cordova.setActivityResultCallback(this); - ((CordovaActivity) this.cordova.getActivity()).startActivityForResult(i, requestCode); - } - else - { - ((CordovaActivity)this.cordova.getActivity()).startActivity(i); - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK)); - } - } - else - { - // Return an error as there is no app to handle this intent - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR)); - } - } - - private void sendBroadcast(Intent intent) { - ((CordovaActivity)this.cordova.getActivity()).sendBroadcast(intent); - } - - private void startService(Intent intent) - { - ((CordovaActivity)this.cordova.getActivity()).startService(intent); - } - - private Intent populateIntent(JSONObject obj, CallbackContext callbackContext) throws JSONException - { - // Credit: https://github.com/chrisekelley/cordova-webintent - // Credit: https://github.com/chrisekelley/cordova-webintent - String type = obj.has("type") ? obj.getString("type") : null; - String packageAssociated = obj.has("package") ? obj.getString("package") : null; - - //Uri uri = obj.has("url") ? resourceApi.remapUri(Uri.parse(obj.getString("url"))) : null; - Uri uri = null; - final CordovaResourceApi resourceApi = webView.getResourceApi(); - if (obj.has("url")) - { - String uriAsString = obj.getString("url"); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && uriAsString.startsWith("file://")) - { - uri = remapUriWithFileProvider(uriAsString, callbackContext); - } - else - { - uri = resourceApi.remapUri(Uri.parse(obj.getString("url"))); - } - } - - JSONObject extras = obj.has("extras") ? obj.getJSONObject("extras") : null; - Map extrasMap = new HashMap(); - Bundle bundle = null; - String bundleKey = ""; - if (extras != null) { - JSONArray extraNames = extras.names(); - for (int i = 0; i < extraNames.length(); i++) { - String key = extraNames.getString(i); - Object extrasObj = extras.get(key); - if (extrasObj instanceof JSONObject) { - // The extra is a bundle - bundleKey = key; - bundle = toBundle((JSONObject) extras.get(key)); - } else { - extrasMap.put(key, extras.get(key)); - } - } - } - - String action = obj.has("action") ? obj.getString("action") : null; - Intent i = new Intent(); - if (action != null) - i.setAction(action); - - if (type != null && uri != null) { - i.setDataAndType(uri, type); //Fix the crash problem with android 2.3.6 - } else { - if (type != null) { - i.setType(type); - } - if (uri != null) - { - i.setData(uri); - } - } - - JSONObject component = obj.has("component") ? obj.getJSONObject("component") : null; - if (component != null) - { - // User has specified an explicit intent - String componentPackage = component.has("package") ? component.getString("package") : null; - String componentClass = component.has("class") ? component.getString("class") : null; - if (componentPackage == null || componentClass == null) - { - Log.w(LOG_TAG, "Component specified but missing corresponding package or class"); - throw new JSONException("Component specified but missing corresponding package or class"); - } - - else - { - ComponentName componentName = new ComponentName(componentPackage, componentClass); - i.setComponent(componentName); - } - } - - if (packageAssociated != null) - i.setPackage(packageAssociated); - - JSONArray flags = obj.has("flags") ? obj.getJSONArray("flags") : null; - if (flags != null) - { - int length = flags.length(); - for (int k = 0; k < length; k++) - { - i.addFlags(flags.getInt(k)); - } - } - - if (bundle != null) - i.putExtra(bundleKey, bundle); - - for (String key : extrasMap.keySet()) { - Object value = extrasMap.get(key); - String valueStr = String.valueOf(value); - // If type is text html, the extra text must sent as HTML - if (key.equals(Intent.EXTRA_TEXT) && type.equals("text/html")) { - i.putExtra(key, Html.fromHtml(valueStr)); - } else if (key.equals(Intent.EXTRA_STREAM)) { - // allows sharing of images as attachments. - // value in this case should be a URI of a file - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && valueStr.startsWith("file://")) - { - Uri uriOfStream = remapUriWithFileProvider(valueStr, callbackContext); - if (uriOfStream != null) - i.putExtra(key, uriOfStream); - } - else - { - //final CordovaResourceApi resourceApi = webView.getResourceApi(); - i.putExtra(key, resourceApi.remapUri(Uri.parse(valueStr))); - } - } else if (key.equals(Intent.EXTRA_EMAIL)) { - // allows to add the email address of the receiver - i.putExtra(Intent.EXTRA_EMAIL, new String[] { valueStr }); - } else { - if (value instanceof Boolean) { - i.putExtra(key, Boolean.valueOf(valueStr)); - } else if(value instanceof Integer) { - i.putExtra(key, Integer.valueOf(valueStr)); - } else if(value instanceof Long) { - i.putExtra(key, Long.valueOf(valueStr)); - } else if(value instanceof Double) { - i.putExtra(key, Double.valueOf(valueStr)); - } else { - i.putExtra(key, valueStr); - } - } - } - - i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); - - return i; - } - - @Override - public void onNewIntent(Intent intent) { - if (this.onNewIntentCallbackContext != null) { - fireOnNewIntent(intent); - } - else { - // save the intent for use when onIntent action is called in the execute method - this.deferredIntent = intent; - } - } - - @Override - public void onActivityResult(int requestCode, int resultCode, Intent intent) - { - super.onActivityResult(requestCode, resultCode, intent); - if (onActivityResultCallbackContext != null && intent != null) - { - intent.putExtra("requestCode", requestCode); - intent.putExtra("resultCode", resultCode); - PluginResult result = new PluginResult(PluginResult.Status.OK, getIntentJson(intent)); - result.setKeepCallback(true); - onActivityResultCallbackContext.sendPluginResult(result); - } - else if (onActivityResultCallbackContext != null) - { - Intent canceledIntent = new Intent(); - canceledIntent.putExtra("requestCode", requestCode); - canceledIntent.putExtra("resultCode", resultCode); - PluginResult canceledResult = new PluginResult(PluginResult.Status.OK, getIntentJson(canceledIntent)); - canceledResult.setKeepCallback(true); - onActivityResultCallbackContext.sendPluginResult(canceledResult); - } - - } - - private BroadcastReceiver myBroadcastReceiver = new BroadcastReceiver() { - @Override - public void onReceive(Context context, Intent intent) { - String action = intent.getAction(); - if (onBroadcastCallbackContext != null) - { - PluginResult result = new PluginResult(PluginResult.Status.OK, getIntentJson(intent)); - result.setKeepCallback(true); - onBroadcastCallbackContext.sendPluginResult(result); - } - } - }; - - /** - * Sends the provided Intent to the onNewIntentCallbackContext. - * - * @param intent This is the intent to send to the JS layer. - */ - private void fireOnNewIntent(Intent intent) { - PluginResult result = new PluginResult(PluginResult.Status.OK, getIntentJson(intent)); - result.setKeepCallback(true); - this.onNewIntentCallbackContext.sendPluginResult(result); - } - - /** - * Return JSON representation of intent attributes - * - * @param intent - * Credit: https://github.com/napolitano/cordova-plugin-intent - */ - private JSONObject getIntentJson(Intent intent) { - JSONObject intentJSON = null; - ClipData clipData = null; - JSONObject[] items = null; - ContentResolver cR = this.cordova.getActivity().getApplicationContext().getContentResolver(); - MimeTypeMap mime = MimeTypeMap.getSingleton(); - - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { - clipData = intent.getClipData(); - if(clipData != null) { - int clipItemCount = clipData.getItemCount(); - items = new JSONObject[clipItemCount]; - - for (int i = 0; i < clipItemCount; i++) { - - ClipData.Item item = clipData.getItemAt(i); - - try { - items[i] = new JSONObject(); - items[i].put("htmlText", item.getHtmlText()); - items[i].put("intent", item.getIntent()); - items[i].put("text", item.getText()); - items[i].put("uri", item.getUri()); - - if (item.getUri() != null) { - String type = cR.getType(item.getUri()); - String extension = mime.getExtensionFromMimeType(cR.getType(item.getUri())); - - items[i].put("type", type); - items[i].put("extension", extension); - } - - } catch (JSONException e) { - Log.d(LOG_TAG, " Error thrown during intent > JSON conversion"); - Log.d(LOG_TAG, e.getMessage()); - Log.d(LOG_TAG, Arrays.toString(e.getStackTrace())); - } - - } - } - } - - try { - intentJSON = new JSONObject(); - - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { - if(items != null) { - intentJSON.put("clipItems", new JSONArray(items)); - } - } - - intentJSON.put("type", intent.getType()); - intentJSON.put("extras", toJsonObject(intent.getExtras())); - intentJSON.put("action", intent.getAction()); - intentJSON.put("categories", intent.getCategories()); - intentJSON.put("flags", intent.getFlags()); - intentJSON.put("component", intent.getComponent()); - intentJSON.put("data", intent.getData()); - intentJSON.put("package", intent.getPackage()); - - return intentJSON; - } catch (JSONException e) { - Log.d(LOG_TAG, " Error thrown during intent > JSON conversion"); - Log.d(LOG_TAG, e.getMessage()); - Log.d(LOG_TAG, Arrays.toString(e.getStackTrace())); - - return null; - } - } - - private static JSONObject toJsonObject(Bundle bundle) { - // Credit: https://github.com/napolitano/cordova-plugin-intent - try { - return (JSONObject) toJsonValue(bundle); - } catch (JSONException e) { - throw new IllegalArgumentException("Cannot convert bundle to JSON: " + e.getMessage(), e); - } - } - - private static Object toJsonValue(final Object value) throws JSONException { - // Credit: https://github.com/napolitano/cordova-plugin-intent - if (value == null) { - return null; - } else if (value instanceof Bundle) { - final Bundle bundle = (Bundle) value; - final JSONObject result = new JSONObject(); - for (final String key : bundle.keySet()) { - result.put(key, toJsonValue(bundle.get(key))); - } - return result; - } else if ((value.getClass().isArray())) { - final JSONArray result = new JSONArray(); - int length = Array.getLength(value); - for (int i = 0; i < length; ++i) { - result.put(i, toJsonValue(Array.get(value, i))); - } - return result; - } - else if (value instanceof ArrayList) { - final ArrayList arrayList = (ArrayList)value; - final JSONArray result = new JSONArray(); - for (int i = 0; i < arrayList.size(); i++) - result.put(toJsonValue(arrayList.get(i))); - return result; - } - else if ( - value instanceof String - || value instanceof Boolean - || value instanceof Integer - || value instanceof Long - || value instanceof Double) { - return value; - } else { - return String.valueOf(value); - } - } - - private Bundle toBundle(final JSONObject obj) { - Bundle returnBundle = new Bundle(); - if (obj == null) { - return null; - } - try { - Iterator keys = obj.keys(); - while(keys.hasNext()) - { - String key = (String)keys.next(); - Object compare = obj.get(key); - if (obj.get(key) instanceof String) - returnBundle.putString(key, obj.getString(key)); - else if (obj.get(key) instanceof Boolean) - returnBundle.putBoolean(key, obj.getBoolean(key)); - else if (obj.get(key) instanceof Integer) - returnBundle.putInt(key, obj.getInt(key)); - else if (obj.get(key) instanceof Long) - returnBundle.putLong(key, obj.getLong(key)); - else if (obj.get(key) instanceof Double) - returnBundle.putDouble(key, obj.getDouble(key)); - else if (obj.get(key).getClass().isArray() || obj.get(key) instanceof JSONArray) - { - JSONArray jsonArray = obj.getJSONArray(key); - int length = jsonArray.length(); - if (jsonArray.get(0) instanceof String) - { - String[] stringArray = new String[length]; - for (int j = 0; j < length; j++) - stringArray[j] = jsonArray.getString(j); - returnBundle.putStringArray(key, stringArray); - //returnBundle.putParcelableArray(key, obj.get); - } - else - { - Bundle[] bundleArray = new Bundle[length]; - for (int k = 0; k < length ; k++) - bundleArray[k] = toBundle(jsonArray.getJSONObject(k)); - returnBundle.putParcelableArray(key, bundleArray); - } - } - else if (obj.get(key) instanceof JSONObject) - returnBundle.putBundle(key, toBundle((JSONObject)obj.get(key))); - } - } - catch (JSONException e) { - e.printStackTrace(); - } - - - return returnBundle; - } -} diff --git a/plugins/com-darryncampbell-cordova-plugin-intent/src/android/res/xml/provider_paths.xml b/plugins/com-darryncampbell-cordova-plugin-intent/src/android/res/xml/provider_paths.xml deleted file mode 100644 index 3785fcc..0000000 --- a/plugins/com-darryncampbell-cordova-plugin-intent/src/android/res/xml/provider_paths.xml +++ /dev/null @@ -1,3 +0,0 @@ - - - \ No newline at end of file diff --git a/plugins/cordova-android-support-gradle-release/README.md b/plugins/cordova-android-support-gradle-release/README.md deleted file mode 100644 index 97ade49..0000000 --- a/plugins/cordova-android-support-gradle-release/README.md +++ /dev/null @@ -1,172 +0,0 @@ -cordova-android-support-gradle-release -====================================== - -This Cordova/Phonegap plugin for Android aligns various versions of the Android Support libraries specified by other plugins to a specific version. - - - -**Table of Contents** - -- [Purpose](#purpose) -- [Installation](#installation) -- [Library versions](#library-versions) - - [Default version](#default-version) - - [Other versions](#other-versions) -- [Example cases](#example-cases) - - [Example 1](#example-1) - - [Example 2](#example-2) -- [Credits](#credits) -- [License](#license) - - - -# Purpose - -**TL;DR**: To prevent build failures caused by including different versions of the support libraries. - -Some Cordova plugins include [Android Support Libraries](https://developer.android.com/topic/libraries/support-library/index.html) to faciliate them. -Most commonly, these are now included into the Cordova project by specifying them as Gradle dependencies (see the [Cordova plugin spec documentation](https://cordova.apache.org/docs/en/latest/plugin_ref/spec.html#framework)). - -Example plugins: -- [cordova-diagnostic-plugin](https://github.com/dpa99c/cordova-diagnostic-plugin) -- [Telerik ImagePicker plugin](https://github.com/Telerik-Verified-Plugins/ImagePicker) -- [cordova-plugin-local-notifications](https://github.com/katzer/cordova-plugin-local-notifications/) -- [cordova-plugin-facebook4](https://github.com/jeduan/cordova-plugin-facebook4) - -The problem arises when these plugins specify different versions of the support libraries. This can cause build failures to occur, which are not easy to resolve without changes by the plugin authors to align the specified versions. See these issues: - -- [phonegap-plugin-barcodescanner#480](https://github.com/phonegap/phonegap-plugin-barcodescanner/issues/480) -- [cordova-plugin-facebook4#507](https://github.com/jeduan/cordova-plugin-facebook4/issues/507) -- [cordova-plugin-local-notifications#1322](https://github.com/katzer/cordova-plugin-local-notifications/issues/1322) -- [cordova-diagnostic-plugin#211](https://github.com/dpa99c/cordova-diagnostic-plugin/issues/211) - -To resolve these version collisions, this plugin injects a Gradle configuration file into the native Android platform project, which overrides any versions specified by other plugins, and forces them to the version specified in its Gradle file. - -If you're encountering similar problems with the Play Services and/or Firebase libraries, checkout the sister plugins: -- [cordova-android-play-services-gradle-release](https://github.com/dpa99c/cordova-android-play-services-gradle-release) -- [cordova-android-firebase-gradle-release](https://github.com/dpa99c/cordova-android-firebase-gradle-release) - - - -# Installation - - $ cordova plugin add cordova-android-support-gradle-release - $ cordova plugin add cordova-android-support-gradle-release --variable ANDROID_SUPPORT_VERSION={required version} - -The plugin needs to be installed with the [`cordova-fetch`](https://cordova.apache.org/news/2016/05/24/tools-release.html) mechanism in order to satisfy its [package dependencies](https://github.com/dpa99c/cordova-android-support-gradle-release/blob/master/package.json#L8) by installing it via npm. - -Therefore if you're installing with `cordova@6`, you'll need to explicitly specify the `--fetch` option: - - $ cordova plugin add cordova-android-support-gradle-release --fetch - -# Library versions - -## Default version -By default, this plugin will use the major version of the most recent release of the support libraries - [see here](https://developer.android.com/topic/libraries/support-library/revisions.html) for a list recent versions. "Most recent release" means the highest major version that will not result in an Alpha or Beta version being included. - - $ cordova plugin add cordova-android-support-gradle-release - -For example, if the most recent versions are: -- `26.0.0 Beta 2` -- `25.4.0` - -Then this plugin will default to `25.+` because `26` is still in Beta. - -## Other versions - -In some cases, you may want to specify a different version of the support libraries. For example, [Telerik ImagePicker plugin v2.1.7](https://github.com/Telerik-Verified-Plugins/ImagePicker/tree/2.1.7) specifies `v23` because it contains code that is incompatible with `v24+`. - -In this case, including the default version of this plugin will still result in a build error. So this plugin enables you to specify other versions of the support library using the `ANDROID_SUPPORT_VERSION` plugin variable. - -In the above case, you'd want to install v23 of the support library. To so, you'd specify the version via the variable: - - cordova plugin add cordova-android-support-gradle-release --variable ANDROID_SUPPORT_VERSION=23.+ - -# Example cases - -## Example 1 - -Uses v25 of the support libraries to fix the build issue. - -1. `cordova create test1 && cd test1/` -2. `cordova platform add android@latest` -3. `cordova plugin add cordova-plugin-facebook4@1.9.1 --save --variable APP_ID="123456789" --variable APP_NAME="myApplication"` -4. `cordova compile` - -Observe the build succeeds and in the console output is `v25.3.1` of Android Support Library: - - :prepareComAndroidSupportSupportV42531Library - -5. `cordova plugin add de.appplant.cordova.plugin.local-notification@0.8.5` -6. `cordova compile` - -Observe the build failed and in the console output is higher than `v25.3.1` (e.g `v26.0.0-alpha1`) of Android Support Library: - - :prepareComAndroidSupportSupportV42600Alpha1Library - -7. `cordova plugin add cordova-android-support-gradle-release --variable ANDROID_SUPPORT_VERSION=25.+` -8. `cordova prepare && cordova compile` - -Observe the build succeeds and in the console output is `v25` of Android Support Library. - -## Example 2 - -Uses v23 of the support libraries to fix the build issue, because v2.1.7 of the ImagePicker only works with v23. - -1. `cordova create test2 && cd test2/` -2. `cordova platform add android@latest` -3. `cordova plugin add https://github.com/Telerik-Verified-Plugins/ImagePicker.git#2.1.7` -4. `cordova compile` - -Observe the build succeeds and in the console output is `v23.4.0` of Android Support Library: - - :prepareComAndroidSupportSupportV42340Library - -5. `cordova plugin add cordova.plugins.diagnostic@3.6.5` - -Observe the build failed and in the console output is higher than `v23.4.0` (e.g `v26.0.0-alpha1`) of Android Support Library: - - :prepareComAndroidSupportSupportV42600Alpha1Library - -7. `cordova plugin add cordova-android-support-gradle-release` -8. `cordova compile` - -Observe the build still failed and in the console output is still higher than `v23.4.0` (e.g `v25.3.1`) of Android Support Library: - - :prepareComAndroidSupportSupportV42531Library - -9. `cordova plugin rm cordova-android-support-gradle-release` -10. `cordova plugin add cordova-android-support-gradle-release --variable ANDROID_SUPPORT_VERSION=23.+` -11. `cordova prepare && cordova compile` - -Observe the build succeeds and in the console output is v23 of Android Support Library. - - -# Credits - -Thanks to [**Chris Scott, Transistor Software**](https://github.com/christocracy) for his idea of extending the initial implementation to support dynamic specification of the library version via a plugin variable in [cordova-google-api-version](https://github.com/transistorsoft/cordova-google-api-version) - -License -================ - -The MIT License - -Copyright (c) 2017 Dave Alden / Working Edge Ltd. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. \ No newline at end of file diff --git a/plugins/cordova-android-support-gradle-release/cordova-android-support-gradle-release.gradle b/plugins/cordova-android-support-gradle-release/cordova-android-support-gradle-release.gradle deleted file mode 100644 index 1b0bd72..0000000 --- a/plugins/cordova-android-support-gradle-release/cordova-android-support-gradle-release.gradle +++ /dev/null @@ -1,31 +0,0 @@ -repositories{ - // Google APIs are now hosted at Maven - maven { - url 'https://maven.google.com' - } -} - -def PLUGIN_NAME = "cordova-android-support-gradle-release" - -// Fetch ANDROID_SUPPORT_VERSION var from properties.gradle -apply from: PLUGIN_NAME + '/properties.gradle' - -// List of libs to search for. -def LIBS = [ - 'com.android.support' -] - -def IGNORED = [ - 'multidex', - 'multidex-instrumentation' -] - -println("+-----------------------------------------------------------------"); -println("| " + PLUGIN_NAME + ": " + ANDROID_SUPPORT_VERSION); -println("+-----------------------------------------------------------------"); - -configurations.all { - resolutionStrategy.eachDependency { DependencyResolveDetails details -> - if (details.requested.group in LIBS && !(details.requested.name in IGNORED)) { details.useVersion ANDROID_SUPPORT_VERSION } - } -} diff --git a/plugins/cordova-android-support-gradle-release/package.json b/plugins/cordova-android-support-gradle-release/package.json deleted file mode 100644 index 3e3e9a7..0000000 --- a/plugins/cordova-android-support-gradle-release/package.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "_from": "cordova-android-support-gradle-release@^1.4.4", - "_id": "cordova-android-support-gradle-release@1.4.4", - "_inBundle": false, - "_integrity": "sha512-DOwZ+MX0CBoagXV6cHqfQacVjsrDea8z2wuM427AIvi2eAFvojw85o1XMCdJ4kSDMbsUUaNPw12h7uY0m+rcvg==", - "_location": "/cordova-android-support-gradle-release", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "cordova-android-support-gradle-release@^1.4.4", - "name": "cordova-android-support-gradle-release", - "escapedName": "cordova-android-support-gradle-release", - "rawSpec": "^1.4.4", - "saveSpec": null, - "fetchSpec": "^1.4.4" - }, - "_requiredBy": [ - "#USER", - "/" - ], - "_resolved": "https://registry.npmjs.org/cordova-android-support-gradle-release/-/cordova-android-support-gradle-release-1.4.4.tgz", - "_shasum": "6a64db69f36c332727d95b421d53c25dfe99684d", - "_spec": "cordova-android-support-gradle-release@^1.4.4", - "_where": "/home/thrrgilag/workspace/cordova/Goober", - "author": { - "name": "Dave Alden" - }, - "bundleDependencies": false, - "dependencies": { - "xml2js": "~0.4.19" - }, - "deprecated": false, - "description": "Cordova/Phonegap plugin to align various versions of the Android Support libraries specified by other plugins to a specific version", - "devDependencies": {}, - "license": "MIT", - "name": "cordova-android-support-gradle-release", - "version": "1.4.4" -} diff --git a/plugins/cordova-android-support-gradle-release/plugin.xml b/plugins/cordova-android-support-gradle-release/plugin.xml deleted file mode 100644 index 7407f7b..0000000 --- a/plugins/cordova-android-support-gradle-release/plugin.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - cordova-android-support-gradle-release - Cordova/Phonegap plugin to align various versions of the Android Support libraries specified by other plugins to a specific version - Dave Alden - - - - - - - - - - - - - - - - - diff --git a/plugins/cordova-android-support-gradle-release/properties.gradle b/plugins/cordova-android-support-gradle-release/properties.gradle deleted file mode 100644 index 5d42a85..0000000 --- a/plugins/cordova-android-support-gradle-release/properties.gradle +++ /dev/null @@ -1 +0,0 @@ -ext {ANDROID_SUPPORT_VERSION = "27.+"} \ No newline at end of file diff --git a/plugins/cordova-android-support-gradle-release/scripts/apply-changes.js b/plugins/cordova-android-support-gradle-release/scripts/apply-changes.js deleted file mode 100644 index 12adaf0..0000000 --- a/plugins/cordova-android-support-gradle-release/scripts/apply-changes.js +++ /dev/null @@ -1,90 +0,0 @@ -const PLUGIN_NAME = "cordova-android-support-gradle-release"; -const V6 = "cordova-android@6"; -const V7 = "cordova-android@7"; -const PACKAGE_PATTERN = /(compile "com.android.support:[^:]+:)([^"]+)"/g; -const PROPERTIES_TEMPLATE = 'ext {ANDROID_SUPPORT_VERSION = ""}'; - -var FILE_PATHS = {}; -FILE_PATHS[V6] = { - "build.gradle": "platforms/android/build.gradle", - "properties.gradle": "platforms/android/"+PLUGIN_NAME+"/properties.gradle" -}; -FILE_PATHS[V7] = { - "build.gradle": "platforms/android/app/build.gradle", - "properties.gradle": "platforms/android/app/"+PLUGIN_NAME+"/properties.gradle" -}; - -var deferral, fs, path, parser, platformVersion; - - -function log(message) { - console.log(PLUGIN_NAME + ": " + message); -} - -function onError(error) { - log("ERROR: " + error); - deferral.resolve(); -} - -function getCordovaAndroidVersion(){ - var cordovaVersion = require(path.resolve(process.cwd(),'platforms/android/cordova/version')); - return parseInt(cordovaVersion.version) === 7 ? V7 : V6; -} - - -function run() { - try { - fs = require('fs'); - path = require('path'); - parser = require('xml2js'); - } catch (e) { - throw("Failed to load dependencies. If using cordova@6 CLI, ensure this plugin is installed with the --fetch option: " + e.toString()); - } - - platformVersion = getCordovaAndroidVersion(); - log("Android platform: " + platformVersion); - - var data = fs.readFileSync(path.resolve(process.cwd(), 'config.xml')); - parser.parseString(data, attempt(function (err, result) { - if (err) throw err; - var version, plugins = result.widget.plugin; - for (var n = 0, len = plugins.length; n < len; n++) { - var plugin = plugins[n]; - if (plugin.$.name === PLUGIN_NAME && plugin.variable && plugin.variable.length > 0) { - version = plugin.variable.pop().$.value; - break; - } - } - if (version) { - // build.gradle - var buildGradlePath = path.resolve(process.cwd(), FILE_PATHS[platformVersion]["build.gradle"]); - var contents = fs.readFileSync(buildGradlePath).toString(); - fs.writeFileSync(buildGradlePath, contents.replace(PACKAGE_PATTERN, "$1" + version + '"'), 'utf8'); - log("Wrote custom version '" + version + "' to " + buildGradlePath); - - // properties.gradle - var propertiesGradlePath = path.resolve(process.cwd(), FILE_PATHS[platformVersion]["properties.gradle"]); - fs.writeFileSync(propertiesGradlePath, PROPERTIES_TEMPLATE.replace(//, version), 'utf8'); - log("Wrote custom version '" + version + "' to " + propertiesGradlePath); - } else { - log("No custom version found in config.xml - using plugin default"); - } - deferral.resolve(); - })); -} - -function attempt(fn) { - return function () { - try { - fn.apply(this, arguments); - } catch (e) { - onError("EXCEPTION: " + e.toString()); - } - } -} - -module.exports = function (ctx) { - deferral = ctx.requireCordovaModule('q').defer(); - attempt(run)(); - return deferral.promise; -}; diff --git a/plugins/cordova-plugin-console/CONTRIBUTING.md b/plugins/cordova-plugin-console/CONTRIBUTING.md deleted file mode 100644 index 4c8e6a5..0000000 --- a/plugins/cordova-plugin-console/CONTRIBUTING.md +++ /dev/null @@ -1,37 +0,0 @@ - - -# 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-console/LICENSE b/plugins/cordova-plugin-console/LICENSE deleted file mode 100644 index 7a4a3ea..0000000 --- a/plugins/cordova-plugin-console/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - 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-console/NOTICE b/plugins/cordova-plugin-console/NOTICE deleted file mode 100644 index 8ec56a5..0000000 --- a/plugins/cordova-plugin-console/NOTICE +++ /dev/null @@ -1,5 +0,0 @@ -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-console/README.md b/plugins/cordova-plugin-console/README.md deleted file mode 100644 index f534be4..0000000 --- a/plugins/cordova-plugin-console/README.md +++ /dev/null @@ -1,116 +0,0 @@ ---- -title: Console -description: Get JavaScript logs in your native logs. ---- - - -|AppVeyor|Travis CI| -|:-:|:-:| -|[![Build status](https://ci.appveyor.com/api/projects/status/github/apache/cordova-plugin-console?branch=master)](https://ci.appveyor.com/project/ApacheSoftwareFoundation/cordova-plugin-console)|[![Build Status](https://travis-ci.org/apache/cordova-plugin-console.svg?branch=master)](https://travis-ci.org/apache/cordova-plugin-console)| - -# cordova-plugin-console - -## Deprecated - -> This plugin is no longer being worked on as the functionality provided by this plugin is now included in cordova-ios 4.5.0 or greater, and support is already built in to cordova-windows > 5.0.0. You should upgrade your application to use version 2.0.0 of this plugin. It will detect whether or not the plugin is required based on the version of cordova-ios and cordova-windows your app uses. -> Please file issues for this plugin against their respective platforms (cordova-ios, cordova-windows). - -## Description - -This plugin is meant to ensure that console.log() is as useful as it can be. -It adds additional function for iOS, Ubuntu, Windows Phone 8, and Windows. If -you are happy with how console.log() works for you, then you probably -don't need this plugin. - -This plugin defines a global `console` object. - -Although the object is in the global scope, features provided by this plugin -are not available until after the `deviceready` event. - - document.addEventListener("deviceready", onDeviceReady, false); - function onDeviceReady() { - console.log("console.log works well"); - } - -:warning: 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%20Console%22%20ORDER%20BY%20priority%20DESC%2C%20summary%20ASC%2C%20updatedDate%20DESC) - - -## Installation - - cordova plugin add cordova-plugin-console - -### Android Quirks - -On some platforms other than Android, console.log() will act on multiple -arguments, such as console.log("1", "2", "3"). However, Android will act only -on the first argument. Subsequent arguments to console.log() will be ignored. -This plugin is not the cause of that, it is a limitation of Android itself. - -## Supported Methods - -The plugin support following methods of the `console` object: - -- `console.log` -- `console.error` -- `console.exception` -- `console.warn` -- `console.info` -- `console.debug` -- `console.assert` -- `console.dir` -- `console.dirxml` -- `console.time` -- `console.timeEnd` -- `console.table` - -## Partially supported Methods - -Methods of the `console` object which implemented, but behave different from browser implementation: - -- `console.group` -- `console.groupCollapsed` - -The grouping methods are just log name of the group and don't actually indicate grouping for later -calls to `console` object methods. - -## Not supported Methods - -Methods of the `console` object which are implemented, but do nothing: - -- `console.clear` -- `console.trace` -- `console.groupEnd` -- `console.timeStamp` -- `console.profile` -- `console.profileEnd` -- `console.count` - -## Supported formatting - -The following formatting options available: - -Format chars: - -* `%j` - format arg as JSON -* `%o` - format arg as JSON -* `%c` - format arg as `''`. No color formatting could be done. -* `%%` - replace with `'%'` - -Any other char following `%` will format its arg via `toString()`. diff --git a/plugins/cordova-plugin-console/RELEASENOTES.md b/plugins/cordova-plugin-console/RELEASENOTES.md deleted file mode 100644 index a6168e0..0000000 --- a/plugins/cordova-plugin-console/RELEASENOTES.md +++ /dev/null @@ -1,126 +0,0 @@ - -# Release Notes - -### 1.1.0 (Sep 18, 2017) -* [CB-13170](https://issues.apache.org/jira/browse/CB-13170) Integrated this plugin into `cordova-ios@4.5.0`. This plugin will not install for `cordova-ios >= 4.5.0`. -* [CB-13028](https://issues.apache.org/jira/browse/CB-13028) (CI) **Browser** builds on `Travis` and `AppVeyor` -* [CB-13000](https://issues.apache.org/jira/browse/CB-13000) (CI) Speed up **Android** builds -* [CB-12991](https://issues.apache.org/jira/browse/CB-12991) (CI) Updated CI badges -* [CB-12935](https://issues.apache.org/jira/browse/CB-12935) (**windows**) Enable paramedic builds on AppVeyor -* [CB-12935](https://issues.apache.org/jira/browse/CB-12935) (**ios**, **Android**) Run `paramedic` builds on `Travis` -* [CB-12847](https://issues.apache.org/jira/browse/CB-12847) added `bugs` entry to `package.json`. - -### 1.0.7 (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 - -### 1.0.6 (Feb 28, 2017) -* [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 - -### 1.0.5 (Dec 07, 2016) -* [CB-12224](https://issues.apache.org/jira/browse/CB-12224) Updated version and RELEASENOTES.md for release 1.0.5 -* [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. - -### 1.0.4 (Sep 08, 2016) -* [CB-11795](https://issues.apache.org/jira/browse/CB-11795) Add 'protective' entry to `cordovaDependencies` -* add `JIRA` issue tracker link -* Add badges for paramedic builds on Jenkins -* Add pull request template. -* [CB-10996](https://issues.apache.org/jira/browse/CB-10996) Adding front matter to README.md - -### 1.0.3 (Apr 15, 2016) -* [CB-10720](https://issues.apache.org/jira/browse/CB-10720) Minor spelling/formatting changes. -* [CB-10636](https://issues.apache.org/jira/browse/CB-10636) Add `JSHint` for plugins - -### 1.0.2 (Nov 18, 2015) -* [CB-10035](https://issues.apache.org/jira/browse/CB-10035) Updated `RELEASENOTES` to be newest to oldest -* Fixing contribute link. -* Document formatting options for the console object -* [CB-5089](https://issues.apache.org/jira/browse/CB-5089) Document supported methods for console object -* reverted `d58f218b9149d362ebb0b8ce697cf403569d14cd` because `logger` is not needed on **Android** - -### 1.0.1 (Jun 17, 2015) -* move logger.js and console-via-logger.js to common modules, instead of the numerous repeats that were there. -* clean up tests, info is below log level so it does not exist by default. -* add a couple tests -* [CB-9191](https://issues.apache.org/jira/browse/CB-9191) Add basic test -* [CB-9128](https://issues.apache.org/jira/browse/CB-9128) cordova-plugin-console documentation translation: cordova-plugin-console -* attempt to fix npm markdown issue - -### 1.0.0 (Apr 15, 2015) -* [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) changed plugin-id to pacakge-name -* [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: renamed Windows8 to Windows -* [CB-8653](https://issues.apache.org/jira/browse/CB-8653) Updated Readme -* [CB-8560](https://issues.apache.org/jira/browse/CB-8560) Integrate TravisCI -* [CB-8438](https://issues.apache.org/jira/browse/CB-8438) cordova-plugin-console documentation translation: cordova-plugin-console -* [CB-8538](https://issues.apache.org/jira/browse/CB-8538) Added package.json file -* [CB-8362](https://issues.apache.org/jira/browse/CB-8362) Add Windows platform section to Console plugin - -### 0.2.13 (Feb 04, 2015) -* [CB-8351](https://issues.apache.org/jira/browse/CB-8351) ios: Use argumentForIndex rather than NSArray extension - -### 0.2.12 (Dec 02, 2014) -* [CB-7977](https://issues.apache.org/jira/browse/CB-7977) Mention `deviceready` in plugin docs -* [CB-7700](https://issues.apache.org/jira/browse/CB-7700) cordova-plugin-console documentation translation: cordova-plugin-console - -### 0.2.11 (Sep 17, 2014) -* [CB-7249](https://issues.apache.org/jira/browse/CB-7249) cordova-plugin-console documentation translation - -### 0.2.10 (Aug 06, 2014) -* [CB-6127](https://issues.apache.org/jira/browse/CB-6127) Updated translations for docs - -### 0.2.9 (Jun 05, 2014) -* [CB-6848](https://issues.apache.org/jira/browse/CB-6848) Add Android quirk, list applicable platforms -* [CB-6796](https://issues.apache.org/jira/browse/CB-6796) Add license -* [CB-6491](https://issues.apache.org/jira/browse/CB-6491) add CONTRIBUTING.md - -### 0.2.8 (Apr 17, 2014) -* [CB-6460](https://issues.apache.org/jira/browse/CB-6460): Update license headers -* Add NOTICE file - -### 0.2.7 (Feb 05, 2014) -* Native console needs to be called DebugConsole to avoid ambiguous reference. This commit requires the 3.4.0 version of the native class factory -* [CB-4718](https://issues.apache.org/jira/browse/CB-4718) fixed Console plugin not working on wp - -### 0.2.6 (Jan 02, 2014) -* [CB-5658](https://issues.apache.org/jira/browse/CB-5658) Add doc/index.md for Console plugin - -### 0.2.5 (Dec 4, 2013) -* add ubuntu platform - -### 0.2.4 (Oct 28, 2013) -* [CB-5154](https://issues.apache.org/jira/browse/CB-5154) log formatting incorrectly to native -* [CB-5128](https://issues.apache.org/jira/browse/CB-5128): added repo + issue tag to plugin.xml for console plugin -* [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) renaming org.apache.cordova.core.console to org.apache.cordova.console -* Rename CHANGELOG.md -> RELEASENOTES.md -* [CB-4752](https://issues.apache.org/jira/browse/CB-4752) Incremented plugin version on dev branch. - - diff --git a/plugins/cordova-plugin-console/doc/de/README.md b/plugins/cordova-plugin-console/doc/de/README.md deleted file mode 100644 index 933c1b7..0000000 --- a/plugins/cordova-plugin-console/doc/de/README.md +++ /dev/null @@ -1,43 +0,0 @@ - - -# cordova-plugin-console - -[![Build Status](https://travis-ci.org/apache/cordova-plugin-console.svg)](https://travis-ci.org/apache/cordova-plugin-console) - -Dieses Plugin stellt sicher, dass der Befehl console.log() so hilfreich ist, wie er sein kann. Es fügt zusätzliche Funktion für iOS, Ubuntu, Windows Phone 8 und Windows. Teilweise kann es vorkommen, dass der Befehl console.log() nicht korrekt erkannt wird, und es zu Fehlern bzw. zu nicht angezeigten Logs in der Console kommt. Wenn Sie mit der derzeitigen Funktionsweise zufrieden sind, kann es sein, dass Sie dieses Plugin nicht benötigen. - -Dieses Plugin wird ein global-`console`-Objekt definiert. - -Obwohl das Objekt im globalen Gültigkeitsbereich ist, stehen Features von diesem Plugin nicht bis nach dem `deviceready`-Ereignis. - - document.addEventListener("deviceready", onDeviceReady, false); - function onDeviceReady() { - console.log("console.log works well"); - } - - -## Installation - - cordova plugin add cordova-plugin-console - - -### Android Eigenarten - -Auf einigen Plattformen als Android fungieren console.log() auf mehrere Argumente wie console.log ("1", "2", "3"). Android wird jedoch nur auf das erste Argument fungieren. Nachfolgende Argumente zu console.log() werden ignoriert. Dieses Plugin ist nicht die Verantwortung dafür, es ist eine Einschränkung von Android selbst. \ No newline at end of file diff --git a/plugins/cordova-plugin-console/doc/de/index.md b/plugins/cordova-plugin-console/doc/de/index.md deleted file mode 100644 index 9551782..0000000 --- a/plugins/cordova-plugin-console/doc/de/index.md +++ /dev/null @@ -1,41 +0,0 @@ - - -# cordova-plugin-console - -Dieses Plugin stellt sicher, dass der Befehl console.log() so hilfreich ist, wie er sein kann. Es fügt zusätzliche Funktion für iOS, Ubuntu, Windows Phone 8 und Windows 8 hinzu. Teilweise kann es vorkommen, dass der Befehl console.log() nicht korrekt erkannt wird, und es zu Fehlern bzw. zu nicht angezeigten Logs in der Console kommt. Wenn Sie mit der derzeitigen Funktionsweise zufrieden sind, kann es sein, dass Sie dieses Plugin nicht benötigen. - -Dieses Plugin wird ein global-`console`-Objekt definiert. - -Obwohl das Objekt im globalen Gültigkeitsbereich ist, stehen Features von diesem Plugin nicht bis nach dem `deviceready`-Ereignis. - - document.addEventListener("deviceready", onDeviceReady, false); - function onDeviceReady() { - console.log("console.log works well"); - } - - -## Installation - - cordova plugin add cordova-plugin-console - - -### Android Eigenarten - -Auf einigen Plattformen als Android fungieren console.log() auf mehrere Argumente wie console.log ("1", "2", "3"). Android wird jedoch nur auf das erste Argument fungieren. Nachfolgende Argumente zu console.log() werden ignoriert. Dieses Plugin ist nicht die Verantwortung dafür, es ist eine Einschränkung von Android selbst. diff --git a/plugins/cordova-plugin-console/doc/es/README.md b/plugins/cordova-plugin-console/doc/es/README.md deleted file mode 100644 index b089d63..0000000 --- a/plugins/cordova-plugin-console/doc/es/README.md +++ /dev/null @@ -1,41 +0,0 @@ - - -# cordova-plugin-console - -[![Build Status](https://travis-ci.org/apache/cordova-plugin-console.svg)](https://travis-ci.org/apache/cordova-plugin-console) - -Este plugin es para asegurarse de que console.log() es tan útil como puede ser. Agrega la función adicional para iOS, Ubuntu, Windows Phone 8 y Windows. Si estás contento con cómo funciona console.log() para ti, entonces probablemente no necesitas este plugin. - -Este plugin define un global `console` objeto. - -Aunque el objeto está en el ámbito global, características proporcionadas por este plugin no están disponibles hasta después de la `deviceready` evento. - - document.addEventListener ("deviceready", onDeviceReady, false); - function onDeviceReady() {console.log ("console.log funciona bien");} - - -## Instalación - - cordova plugin add cordova-plugin-console - - -### Rarezas Android - -En algunas plataformas que no sean Android, console.log() actuará en varios argumentos, como console.log ("1", "2", "3"). Sin embargo, Android actuará sólo en el primer argumento. Se omitirá posteriores argumentos para console.log(). Este plugin no es la causa de eso, es una limitación propia de Android. \ No newline at end of file diff --git a/plugins/cordova-plugin-console/doc/es/index.md b/plugins/cordova-plugin-console/doc/es/index.md deleted file mode 100644 index e6b8e68..0000000 --- a/plugins/cordova-plugin-console/doc/es/index.md +++ /dev/null @@ -1,39 +0,0 @@ - - -# cordova-plugin-console - -Este plugin es para asegurarse de que console.log() es tan útil como puede ser. Añade función adicional para iOS, Windows Phone 8, Ubuntu y Windows 8. Si estás contento con cómo funciona console.log() para ti, entonces probablemente no necesitas este plugin. - -Este plugin define un global `console` objeto. - -Aunque el objeto está en el ámbito global, características proporcionadas por este plugin no están disponibles hasta después de la `deviceready` evento. - - document.addEventListener ("deviceready", onDeviceReady, false); - function onDeviceReady() {console.log ("console.log funciona bien");} - - -## Instalación - - Cordova plugin agregar cordova-plugin-console - - -### Rarezas Android - -En algunas plataformas que no sean Android, console.log() actuará en varios argumentos, como console.log ("1", "2", "3"). Sin embargo, Android actuará sólo en el primer argumento. Se omitirá posteriores argumentos para console.log(). Este plugin no es la causa de eso, es una limitación propia de Android. diff --git a/plugins/cordova-plugin-console/doc/fr/README.md b/plugins/cordova-plugin-console/doc/fr/README.md deleted file mode 100644 index 74207ac..0000000 --- a/plugins/cordova-plugin-console/doc/fr/README.md +++ /dev/null @@ -1,41 +0,0 @@ - - -# cordova-plugin-console - -[![Build Status](https://travis-ci.org/apache/cordova-plugin-console.svg)](https://travis-ci.org/apache/cordova-plugin-console) - -Ce plugin est destiné à faire en sorte que console.log() est aussi utile que possible. Il ajoute une fonction supplémentaire pour iOS, Ubuntu, Windows Phone 8 et Windows. Si vous êtes satisfait du fonctionnement de console.log() pour vous, alors vous avez probablement pas besoin ce plugin. - -Ce plugin définit un global `console` objet. - -Bien que l'objet est dans la portée globale, les fonctions offertes par ce plugin ne sont pas disponibles jusqu'après la `deviceready` événement. - - document.addEventListener (« deviceready », onDeviceReady, false) ; - function onDeviceReady() {console.log ("console.log fonctionne bien");} - - -## Installation - - cordova plugin add cordova-plugin-console - - -### Quirks Android - -Sur certaines plateformes autres que Android, console.log() va agir sur plusieurs arguments, tels que console.log ("1", "2", "3"). Toutefois, Android doit agir uniquement sur le premier argument. Les arguments suivants à console.log() seront ignorées. Ce plugin n'est pas la cause de cela, il s'agit d'une limitation d'Android lui-même. \ No newline at end of file diff --git a/plugins/cordova-plugin-console/doc/fr/index.md b/plugins/cordova-plugin-console/doc/fr/index.md deleted file mode 100644 index d0dbba5..0000000 --- a/plugins/cordova-plugin-console/doc/fr/index.md +++ /dev/null @@ -1,39 +0,0 @@ - - -# cordova-plugin-console - -Ce plugin est destiné à faire en sorte que console.log() est aussi utile que possible. Il ajoute une fonction supplémentaire pour iOS, Ubuntu, Windows Phone 8 et Windows 8. Si vous êtes satisfait du fonctionnement de console.log() pour vous, alors vous avez probablement pas besoin ce plugin. - -Ce plugin définit un global `console` objet. - -Bien que l'objet est dans la portée globale, les fonctions offertes par ce plugin ne sont pas disponibles jusqu'après la `deviceready` événement. - - document.addEventListener (« deviceready », onDeviceReady, false) ; - function onDeviceReady() {console.log ("console.log fonctionne bien");} - - -## Installation - - Cordova plugin ajouter cordova-plugin-console - - -### Quirks Android - -Sur certaines plateformes autres que Android, console.log() va agir sur plusieurs arguments, tels que console.log ("1", "2", "3"). Toutefois, Android doit agir uniquement sur le premier argument. Les arguments suivants à console.log() seront ignorées. Ce plugin n'est pas la cause de cela, il s'agit d'une limitation d'Android lui-même. diff --git a/plugins/cordova-plugin-console/doc/it/README.md b/plugins/cordova-plugin-console/doc/it/README.md deleted file mode 100644 index 5394d55..0000000 --- a/plugins/cordova-plugin-console/doc/it/README.md +++ /dev/null @@ -1,43 +0,0 @@ - - -# cordova-plugin-console - -[![Build Status](https://travis-ci.org/apache/cordova-plugin-console.svg)](https://travis-ci.org/apache/cordova-plugin-console) - -Questo plugin è intesa a garantire che console.log() è tanto utile quanto può essere. Aggiunge una funzione aggiuntiva per iOS, Ubuntu, Windows Phone 8 e Windows. Se sei soddisfatto di come console.log() funziona per voi, quindi probabilmente non è necessario questo plugin. - -Questo plugin definisce un oggetto globale `console`. - -Sebbene l'oggetto sia in ambito globale, funzionalità fornite da questo plugin non sono disponibili fino a dopo l'evento `deviceready`. - - document.addEventListener("deviceready", onDeviceReady, false); - function onDeviceReady() { - console.log("console.log works well"); - } - - -## Installazione - - cordova plugin add cordova-plugin-console - - -### Stranezze Android - -Su alcune piattaforme diverse da Android, console.log() agirà su più argomenti, come ad esempio console ("1", "2", "3"). Tuttavia, Android agirà solo sul primo argomento. Argomenti successivi a console.log() verranno ignorati. Questo plugin non è la causa di ciò, è una limitazione di Android stesso. \ No newline at end of file diff --git a/plugins/cordova-plugin-console/doc/it/index.md b/plugins/cordova-plugin-console/doc/it/index.md deleted file mode 100644 index f0625b3..0000000 --- a/plugins/cordova-plugin-console/doc/it/index.md +++ /dev/null @@ -1,41 +0,0 @@ - - -# cordova-plugin-console - -Questo plugin è intesa a garantire che console.log() è tanto utile quanto può essere. Aggiunge una funzione aggiuntiva per iOS, Ubuntu, Windows 8 e Windows Phone 8. Se sei soddisfatto di come console.log() funziona per voi, quindi probabilmente non è necessario questo plugin. - -Questo plugin definisce un oggetto globale `console`. - -Sebbene l'oggetto sia in ambito globale, funzionalità fornite da questo plugin non sono disponibili fino a dopo l'evento `deviceready`. - - document.addEventListener("deviceready", onDeviceReady, false); - function onDeviceReady() { - console.log("console.log works well"); - } - - -## Installazione - - cordova plugin add cordova-plugin-console - - -### Stranezze Android - -Su alcune piattaforme diverse da Android, console.log() agirà su più argomenti, come ad esempio console ("1", "2", "3"). Tuttavia, Android agirà solo sul primo argomento. Argomenti successivi a console.log() verranno ignorati. Questo plugin non è la causa di ciò, è una limitazione di Android stesso. diff --git a/plugins/cordova-plugin-console/doc/ja/README.md b/plugins/cordova-plugin-console/doc/ja/README.md deleted file mode 100644 index 059c373..0000000 --- a/plugins/cordova-plugin-console/doc/ja/README.md +++ /dev/null @@ -1,43 +0,0 @@ - - -# cordova-plugin-console - -[![Build Status](https://travis-ci.org/apache/cordova-plugin-console.svg)](https://travis-ci.org/apache/cordova-plugin-console) - -ã“ã®ãƒ—ラグインã¯ã€ãã® console.log() ãŒã™ã‚‹ã“ã¨ãŒã§ãã¾ã™ä¾¿åˆ©ãªã“ã¨ã‚’確èªã™ã‚‹ã‚‚ã®ã§ã™ã€‚ ãれ㯠iOSã€Ubuntuã€Windows Phone 8 ã¯ã€Windows ã«è¿½åŠ ã®é–¢æ•°ã‚’追加ã—ã¾ã™ã€‚ å ´åˆã¯ã‚ãªãŸã®ãŸã‚ã® console.log() ã®ä½œå“ã«æº€è¶³ã—ã¦ã„ã‚‹ã—ã€ãŠãらãå¿…è¦ã¯ã‚ã‚Šã¾ã›ã‚“ã“ã®ãƒ—ラグイン。 - -ã“ã®ãƒ—ラグインã§ã¯ã€ã‚°ãƒ­ãƒ¼ãƒãƒ« ・ `console` オブジェクトを定義ã—ã¾ã™ã€‚ - -オブジェクトã¯ã€ã‚°ãƒ­ãƒ¼ãƒãƒ« スコープã§ã§ã™ãŒã€ã“ã®ãƒ—ラグインã«ã‚ˆã£ã¦æä¾›ã•ã‚Œã‚‹æ©Ÿèƒ½ã¯ã€`deviceready` イベントã®å¾Œã¾ã§ä½¿ç”¨ã§ãã¾ã›ã‚“。 - - document.addEventListener("deviceready", onDeviceReady, false); - function onDeviceReady() { - console.log("console.log works well"); - } - - -## インストール - - cordova plugin add cordova-plugin-console - - -### Android ã®ç™– - -アンドロイド以外ã®ã„ãã¤ã‹ã®ãƒ—ラットフォーム㧠console.log() 㯠console.log (「1ã€ã€ã€Œ2ã€ã€ã€Œ3ã€) ãªã©ã€è¤‡æ•°ã®å¼•æ•°ã«å‹•ä½œã—ã¾ã™ã€‚ ã—ã‹ã—ã€ã‚¢ãƒ³ãƒ‰ãƒ­ã‚¤ãƒ‰ã¯ã€æœ€åˆã®å¼•æ•°ã§ã®ã¿å‹•ä½œã—ã¾ã™ã€‚ console.log() ã«å¾Œç¶šã®å¼•æ•°ã¯ç„¡è¦–ã•ã‚Œã¾ã™ã€‚ ã“ã®ãƒ—ラグインãŒåŽŸå› ã§ã¯ãªã„ã€ãれ㯠Android ã®è‡ªä½“ã®åˆ¶é™ã§ã™ã€‚ \ No newline at end of file diff --git a/plugins/cordova-plugin-console/doc/ja/index.md b/plugins/cordova-plugin-console/doc/ja/index.md deleted file mode 100644 index 413593c..0000000 --- a/plugins/cordova-plugin-console/doc/ja/index.md +++ /dev/null @@ -1,41 +0,0 @@ - - -# cordova-plugin-console - -ã“ã®ãƒ—ラグインã¯ã€ãã® console.log() ãŒã™ã‚‹ã“ã¨ãŒã§ãã¾ã™ä¾¿åˆ©ãªã“ã¨ã‚’確èªã™ã‚‹ã‚‚ã®ã§ã™ã€‚ ãã‚Œã¯ã€iOSã€Ubuntuã€Windows Phone 8 ãŠã‚ˆã³ Windows 8 ã®è¿½åŠ é–¢æ•°ã‚’追加ã—ã¾ã™ã€‚ å ´åˆã¯ã‚ãªãŸã®ãŸã‚ã® console.log() ã®ä½œå“ã«æº€è¶³ã—ã¦ã„ã‚‹ã—ã€ãŠãらãå¿…è¦ã¯ã‚ã‚Šã¾ã›ã‚“ã“ã®ãƒ—ラグイン。 - -ã“ã®ãƒ—ラグインã§ã¯ã€ã‚°ãƒ­ãƒ¼ãƒãƒ« ・ `console` オブジェクトを定義ã—ã¾ã™ã€‚ - -オブジェクトã¯ã€ã‚°ãƒ­ãƒ¼ãƒãƒ« スコープã§ã§ã™ãŒã€ã“ã®ãƒ—ラグインã«ã‚ˆã£ã¦æä¾›ã•ã‚Œã‚‹æ©Ÿèƒ½ã¯ã€`deviceready` イベントã®å¾Œã¾ã§ä½¿ç”¨ã§ãã¾ã›ã‚“。 - - document.addEventListener("deviceready", onDeviceReady, false); - function onDeviceReady() { - console.log("console.log works well"); - } - - -## インストール - - cordova plugin add cordova-plugin-console - - -### Android ã®ç™– - -アンドロイド以外ã®ã„ãã¤ã‹ã®ãƒ—ラットフォーム㧠console.log() 㯠console.log (「1ã€ã€ã€Œ2ã€ã€ã€Œ3ã€) ãªã©ã€è¤‡æ•°ã®å¼•æ•°ã«å‹•ä½œã—ã¾ã™ã€‚ ã—ã‹ã—ã€ã‚¢ãƒ³ãƒ‰ãƒ­ã‚¤ãƒ‰ã¯ã€æœ€åˆã®å¼•æ•°ã§ã®ã¿å‹•ä½œã—ã¾ã™ã€‚ console.log() ã«å¾Œç¶šã®å¼•æ•°ã¯ç„¡è¦–ã•ã‚Œã¾ã™ã€‚ ã“ã®ãƒ—ラグインãŒåŽŸå› ã§ã¯ãªã„ã€ãれ㯠Android ã®è‡ªä½“ã®åˆ¶é™ã§ã™ã€‚ diff --git a/plugins/cordova-plugin-console/doc/ko/README.md b/plugins/cordova-plugin-console/doc/ko/README.md deleted file mode 100644 index d03ee5a..0000000 --- a/plugins/cordova-plugin-console/doc/ko/README.md +++ /dev/null @@ -1,43 +0,0 @@ - - -# cordova-plugin-console - -[![Build Status](https://travis-ci.org/apache/cordova-plugin-console.svg)](https://travis-ci.org/apache/cordova-plugin-console) - -ì´ í”ŒëŸ¬ê·¸ì¸ì„ console.log()ë¡œ 수 유용 ë˜ë„ë¡ ì˜ë¯¸ìž…니다. ê·¸ê²ƒì€ iOS, 우분투, Windows Phone 8, ë° ì°½ì— ëŒ€ í•œ 추가 ê¸°ëŠ¥ì„ ì¶”ê°€í•©ë‹ˆë‹¤. Console.log() ë‹¹ì‹ ì„ ìœ„í•´ ìž‘ë™ í•˜ëŠ” 어떻게 행복 í•œ 경우ì—, 그때 ë‹¹ì‹ ì€ ì•„ë§ˆ í•„ìš” 하지 ì•ŠìŠµë‹ˆë‹¤ì´ í”ŒëŸ¬ê·¸ì¸. - -ì´ í”ŒëŸ¬ê·¸ì¸ ê¸€ë¡œë²Œ `console` 개체를 ì •ì˜í•©ë‹ˆë‹¤. - -개체가 ì „ì—­ ë²”ìœ„ì— ìžˆì§€ë§Œ,ì´ í”ŒëŸ¬ê·¸ì¸ì— ì˜í•´ 제공 ë˜ëŠ” 기능 하지 사용할 수 있습니다까지 `deviceready` ì´ë²¤íŠ¸ 후. - - document.addEventListener("deviceready", onDeviceReady, false); - function onDeviceReady() { - console.log("console.log works well"); - } - - -## 설치 - - cordova plugin add cordova-plugin-console - - -### 안 ë“œ ë¡œì´ë“œ ë‹¨ì  - -안 ë“œ ë¡œì´ë“œ ì´ì™¸ì˜ ì¼ë¶€ 플랫í¼ì—ì„œ console.log() console.log ("1", "2", "3")와 ê°™ì´ ì—¬ëŸ¬ ì¸ìˆ˜ì— ìž‘ë™í•  것 ì´ë‹¤. 그러나, 안 ë“œ ë¡œì´ë“œëŠ” 첫 번째 ì¸ìˆ˜ì—만 ìž‘ë™í•  것 ì´ë‹¤. Console.log() í›„ì† ì¸ìˆ˜ëŠ” 무시 ë©ë‹ˆë‹¤. ì´ í”ŒëŸ¬ê·¸ì¸ì˜ ì›ì¸ì´ ë˜ì§€ 않습니다, 그리고 ê·¸ê²ƒì€ ì•ˆ ë“œ ë¡œì´ë“œ ìžì²´ì˜ 한계입니다. \ No newline at end of file diff --git a/plugins/cordova-plugin-console/doc/ko/index.md b/plugins/cordova-plugin-console/doc/ko/index.md deleted file mode 100644 index ca631e4..0000000 --- a/plugins/cordova-plugin-console/doc/ko/index.md +++ /dev/null @@ -1,41 +0,0 @@ - - -# cordova-plugin-console - -ì´ í”ŒëŸ¬ê·¸ì¸ì„ console.log()ë¡œ 수 유용 ë˜ë„ë¡ ì˜ë¯¸ìž…니다. IOS, 우분투, Windows Phone 8 ë° ìœˆë„ìš° 8ì— ëŒ€ í•œ 추가 ê¸°ëŠ¥ì„ ì¶”ê°€ 하 ê³  합니다. Console.log() ë‹¹ì‹ ì„ ìœ„í•´ ìž‘ë™ í•˜ëŠ” 어떻게 행복 í•œ 경우ì—, 그때 ë‹¹ì‹ ì€ ì•„ë§ˆ í•„ìš” 하지 ì•ŠìŠµë‹ˆë‹¤ì´ í”ŒëŸ¬ê·¸ì¸. - -ì´ í”ŒëŸ¬ê·¸ì¸ ê¸€ë¡œë²Œ `console` 개체를 ì •ì˜í•©ë‹ˆë‹¤. - -개체가 ì „ì—­ ë²”ìœ„ì— ìžˆì§€ë§Œ,ì´ í”ŒëŸ¬ê·¸ì¸ì— ì˜í•´ 제공 ë˜ëŠ” 기능 하지 사용할 수 있습니다까지 `deviceready` ì´ë²¤íŠ¸ 후. - - document.addEventListener("deviceready", onDeviceReady, false); - function onDeviceReady() { - console.log("console.log works well"); - } - - -## 설치 - - cordova plugin add cordova-plugin-console - - -### 안 ë“œ ë¡œì´ë“œ ë‹¨ì  - -안 ë“œ ë¡œì´ë“œ ì´ì™¸ì˜ ì¼ë¶€ 플랫í¼ì—ì„œ console.log() console.log ("1", "2", "3")와 ê°™ì´ ì—¬ëŸ¬ ì¸ìˆ˜ì— ìž‘ë™í•  것 ì´ë‹¤. 그러나, 안 ë“œ ë¡œì´ë“œëŠ” 첫 번째 ì¸ìˆ˜ì—만 ìž‘ë™í•  것 ì´ë‹¤. Console.log() í›„ì† ì¸ìˆ˜ëŠ” 무시 ë©ë‹ˆë‹¤. ì´ í”ŒëŸ¬ê·¸ì¸ì˜ ì›ì¸ì´ ë˜ì§€ 않습니다, 그리고 ê·¸ê²ƒì€ ì•ˆ ë“œ ë¡œì´ë“œ ìžì²´ì˜ 한계입니다. diff --git a/plugins/cordova-plugin-console/doc/pl/README.md b/plugins/cordova-plugin-console/doc/pl/README.md deleted file mode 100644 index 78ab9d2..0000000 --- a/plugins/cordova-plugin-console/doc/pl/README.md +++ /dev/null @@ -1,43 +0,0 @@ - - -# cordova-plugin-console - -[![Build Status](https://travis-ci.org/apache/cordova-plugin-console.svg)](https://travis-ci.org/apache/cordova-plugin-console) - -Ten plugin jest przeznaczona do zapewnienia, że console.log() jest tak przydatne, jak to może być. To dodaje dodatkowÄ… funkcjÄ™ dla iOS, Ubuntu, Windows Phone 8 i Windows. JeÅ›li jesteÅ› zadowolony z jak console.log() pracuje dla Ciebie, wtedy prawdopodobnie nie potrzebujÄ… tej wtyczki. - -Ten plugin definiuje obiekt globalny `console`. - -Mimo, że obiekt jest w globalnym zasiÄ™gu, funkcji oferowanych przez ten plugin nie sÄ… dostÄ™pne dopiero po turnieju `deviceready`. - - document.addEventListener("deviceready", onDeviceReady, false); - function onDeviceReady() { - console.log("console.log works well"); - } - - -## Instalacja - - cordova plugin add cordova-plugin-console - - -### Dziwactwa Androida - -Na niektórych platformach innych niż Android console.log() bÄ™dzie dziaÅ‚ać na wielu argumentów, takich jak console.log ("1", "2", "3"). Jednak Android bÄ™dzie dziaÅ‚ać tylko na pierwszy argument. Kolejne argumenty do console.log() bÄ™dÄ… ignorowane. Ten plugin nie jest przyczynÄ…, że, jest to ograniczenie Androida, sam. \ No newline at end of file diff --git a/plugins/cordova-plugin-console/doc/pl/index.md b/plugins/cordova-plugin-console/doc/pl/index.md deleted file mode 100644 index 922b577..0000000 --- a/plugins/cordova-plugin-console/doc/pl/index.md +++ /dev/null @@ -1,41 +0,0 @@ - - -# cordova-plugin-console - -Ten plugin jest przeznaczona do zapewnienia, że console.log() jest tak przydatne, jak to może być. To dodaje dodatkowÄ… funkcjÄ™ dla iOS, Ubuntu, Windows Phone 8 i Windows 8. JeÅ›li jesteÅ› zadowolony z jak console.log() pracuje dla Ciebie, wtedy prawdopodobnie nie potrzebujÄ… tej wtyczki. - -Ten plugin definiuje obiekt globalny `console`. - -Mimo, że obiekt jest w globalnym zasiÄ™gu, funkcji oferowanych przez ten plugin nie sÄ… dostÄ™pne dopiero po turnieju `deviceready`. - - document.addEventListener("deviceready", onDeviceReady, false); - function onDeviceReady() { - console.log("console.log works well"); - } - - -## Instalacja - - cordova plugin add cordova-plugin-console - - -### Dziwactwa Androida - -Na niektórych platformach innych niż Android console.log() bÄ™dzie dziaÅ‚ać na wielu argumentów, takich jak console.log ("1", "2", "3"). Jednak Android bÄ™dzie dziaÅ‚ać tylko na pierwszy argument. Kolejne argumenty do console.log() bÄ™dÄ… ignorowane. Ten plugin nie jest przyczynÄ…, że, jest to ograniczenie Androida, sam. diff --git a/plugins/cordova-plugin-console/doc/ru/index.md b/plugins/cordova-plugin-console/doc/ru/index.md deleted file mode 100644 index 3cfe15d..0000000 --- a/plugins/cordova-plugin-console/doc/ru/index.md +++ /dev/null @@ -1,31 +0,0 @@ - - -# cordova-plugin-console - -Этот плагин предназначен Ð´Ð»Ñ Ð¾Ð±ÐµÑÐ¿ÐµÑ‡ÐµÐ½Ð¸Ñ ÐºÐ°Ðº полезным, поÑкольку Ñто может быть что console.log(). Он добавлÑет дополнительные функции Ð´Ð»Ñ iOS, Ubuntu, Windows Phone 8 и Windows 8. ЕÑли вы не довольны как console.log() работает Ð´Ð»Ñ Ð²Ð°Ñ, то вы вероÑтно не нужен Ñтот плагин. - -## УÑтановка - - cordova plugin add cordova-plugin-console - - -### ОÑобенноÑти Android - -Ðа некоторых платформах, отличных от Android console.log() будет дейÑтвовать на неÑкольких аргументов, например console.log («1», «2», «3»). Тем не менее Android будет дейÑтвовать только на первого аргумента. ПоÑледующие аргументы Ð´Ð»Ñ console.log() будет игнорироватьÑÑ. Этот плагин не ÑвлÑетÑÑ Ð¿Ñ€Ð¸Ñ‡Ð¸Ð½Ð¾Ð¹ Ñтого, Ñто ограничение Android Ñам. diff --git a/plugins/cordova-plugin-console/doc/zh/README.md b/plugins/cordova-plugin-console/doc/zh/README.md deleted file mode 100644 index ce27c3e..0000000 --- a/plugins/cordova-plugin-console/doc/zh/README.md +++ /dev/null @@ -1,43 +0,0 @@ - - -# cordova-plugin-console - -[![Build Status](https://travis-ci.org/apache/cordova-plugin-console.svg)](https://travis-ci.org/apache/cordova-plugin-console) - -這個外掛程å¼æ˜¯ç‚ºäº†ç¢ºä¿è©² console.log() 是一樣有用,它å¯ä»¥æ˜¯ã€‚ 它將添加附加功能的 iOS,Ubuntu,Windows Phone 8 和視窗。 如果你是快樂與 console.log() 是如何為你工作,那麼å¯èƒ½ä¸éœ€è¦é€™å€‹å¤–掛程å¼ã€‚ - -這個外掛程å¼å®šç¾©äº†ä¸€å€‹å…¨åŸŸ `console` 物件。 - -儘管物件是在全çƒç¯„åœå…§ï¼Œæ供這個外掛程å¼çš„功能ä¸å¯ç”¨ç›´åˆ° `deviceready` 事件之後。 - - document.addEventListener("deviceready", onDeviceReady, false); - function onDeviceReady() { - console.log("console.log works well"); - } - - -## å®‰è£ - - cordova plugin add cordova-plugin-console - - -### Android 的怪癖 - -在一些平臺上除了 Android,console.log() 亦會根據多個åƒæ•¸ï¼Œå¦‚ console.log ("1"ã€"2"ã€"3")。 然而,安å“系統åªäº¦æœƒæ ¹æ“šç¬¬ä¸€å€‹åƒæ•¸ã€‚ å° console.log() 的後續åƒæ•¸å°‡è¢«å¿½ç•¥ã€‚ 這個外掛程å¼ä¸æ˜¯çš„原因,它是一個 android 作業系統本身的é™åˆ¶ã€‚ \ No newline at end of file diff --git a/plugins/cordova-plugin-console/doc/zh/index.md b/plugins/cordova-plugin-console/doc/zh/index.md deleted file mode 100644 index e18a141..0000000 --- a/plugins/cordova-plugin-console/doc/zh/index.md +++ /dev/null @@ -1,41 +0,0 @@ - - -# cordova-plugin-console - -這個外掛程å¼æ˜¯ç‚ºäº†ç¢ºä¿è©² console.log() 是一樣有用,它å¯ä»¥æ˜¯ã€‚ 它將添加附加功能的 iOS〠Ubuntu,Windows Phone 8 å’Œ Windows 8。 如果你是快樂與 console.log() 是如何為你工作,那麼å¯èƒ½ä¸éœ€è¦é€™å€‹å¤–掛程å¼ã€‚ - -這個外掛程å¼å®šç¾©äº†ä¸€å€‹å…¨åŸŸ `console` 物件。 - -儘管物件是在全çƒç¯„åœå…§ï¼Œæ供這個外掛程å¼çš„功能ä¸å¯ç”¨ç›´åˆ° `deviceready` 事件之後。 - - document.addEventListener("deviceready", onDeviceReady, false); - function onDeviceReady() { - console.log("console.log works well"); - } - - -## å®‰è£ - - cordova plugin add cordova-plugin-console - - -### Android 的怪癖 - -在一些平臺上除了 Android,console.log() 亦會根據多個åƒæ•¸ï¼Œå¦‚ console.log ("1"ã€"2"ã€"3")。 然而,安å“系統åªäº¦æœƒæ ¹æ“šç¬¬ä¸€å€‹åƒæ•¸ã€‚ å° console.log() 的後續åƒæ•¸å°‡è¢«å¿½ç•¥ã€‚ 這個外掛程å¼ä¸æ˜¯çš„原因,它是一個 android 作業系統本身的é™åˆ¶ã€‚ diff --git a/plugins/cordova-plugin-console/package.json b/plugins/cordova-plugin-console/package.json deleted file mode 100644 index 0eeba9a..0000000 --- a/plugins/cordova-plugin-console/package.json +++ /dev/null @@ -1,80 +0,0 @@ -{ - "_from": "cordova-plugin-console@^1.1.0", - "_id": "cordova-plugin-console@1.1.0", - "_inBundle": false, - "_integrity": "sha1-4vusECkBeeRMtyxf28QQpTHBzW0=", - "_location": "/cordova-plugin-console", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "cordova-plugin-console@^1.1.0", - "name": "cordova-plugin-console", - "escapedName": "cordova-plugin-console", - "rawSpec": "^1.1.0", - "saveSpec": null, - "fetchSpec": "^1.1.0" - }, - "_requiredBy": [ - "#USER", - "/" - ], - "_resolved": "https://registry.npmjs.org/cordova-plugin-console/-/cordova-plugin-console-1.1.0.tgz", - "_shasum": "e2fbac10290179e44cb72c5fdbc410a531c1cd6d", - "_spec": "cordova-plugin-console@^1.1.0", - "_where": "/home/thrrgilag/workspace/cordova/Goober", - "author": { - "name": "Apache Software Foundation" - }, - "bugs": { - "url": "https://issues.apache.org/jira/browse/CB" - }, - "bundleDependencies": false, - "cordova": { - "id": "cordova-plugin-console", - "platforms": [ - "ios", - "ubuntu", - "wp7", - "wp8", - "windows8", - "windows" - ] - }, - "deprecated": "This plugin has been deprecated since it is now included in the latest versions of cordova-ios", - "description": "Cordova Console Plugin", - "devDependencies": { - "jshint": "^2.6.0" - }, - "engines": { - "cordovaDependencies": { - ">=2.0.0": { - "cordova-ios": "<4.5.0", - "cordova-windows": "<=5.0.0" - } - } - }, - "homepage": "https://github.com/apache/cordova-plugin-console#readme", - "keywords": [ - "cordova", - "console", - "ecosystem:cordova", - "cordova-ios", - "cordova-ubuntu", - "cordova-wp7", - "cordova-wp8", - "cordova-windows8", - "cordova-windows" - ], - "license": "Apache-2.0", - "name": "cordova-plugin-console", - "repository": { - "type": "git", - "url": "git+https://github.com/apache/cordova-plugin-console.git" - }, - "scripts": { - "jshint": "node node_modules/jshint/bin/jshint www && node node_modules/jshint/bin/jshint src && node node_modules/jshint/bin/jshint tests", - "test": "npm run jshint" - }, - "version": "1.1.0" -} diff --git a/plugins/cordova-plugin-console/plugin.xml b/plugins/cordova-plugin-console/plugin.xml deleted file mode 100644 index e2d6fc3..0000000 --- a/plugins/cordova-plugin-console/plugin.xml +++ /dev/null @@ -1,132 +0,0 @@ - - - - - - Console - Cordova Console Plugin - Apache 2.0 - cordova,console - https://git-wip-us.apache.org/repos/asf/cordova-plugin-console.git - https://issues.apache.org/jira/browse/CB/component/12320644 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/plugins/cordova-plugin-console/src/ios/CDVLogger.h b/plugins/cordova-plugin-console/src/ios/CDVLogger.h deleted file mode 100644 index 7cfb306..0000000 --- a/plugins/cordova-plugin-console/src/ios/CDVLogger.h +++ /dev/null @@ -1,26 +0,0 @@ -/* - 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 CDVLogger : CDVPlugin - -- (void)logLevel:(CDVInvokedUrlCommand*)command; - -@end diff --git a/plugins/cordova-plugin-console/src/ios/CDVLogger.m b/plugins/cordova-plugin-console/src/ios/CDVLogger.m deleted file mode 100644 index ccfa3a5..0000000 --- a/plugins/cordova-plugin-console/src/ios/CDVLogger.m +++ /dev/null @@ -1,38 +0,0 @@ -/* - 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 "CDVLogger.h" -#import - -@implementation CDVLogger - -/* log a message */ -- (void)logLevel:(CDVInvokedUrlCommand*)command -{ - id level = [command argumentAtIndex:0]; - id message = [command argumentAtIndex:1]; - - if ([level isEqualToString:@"LOG"]) { - NSLog(@"%@", message); - } else { - NSLog(@"%@: %@", level, message); - } -} - -@end diff --git a/plugins/cordova-plugin-console/src/ubuntu/console.cpp b/plugins/cordova-plugin-console/src/ubuntu/console.cpp deleted file mode 100644 index 9de09f4..0000000 --- a/plugins/cordova-plugin-console/src/ubuntu/console.cpp +++ /dev/null @@ -1,29 +0,0 @@ -/* - * 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 "console.h" - -#include - -Console::Console(Cordova *cordova) : CPlugin(cordova) { -} - -void Console::logLevel(int scId, int ecId, QString level, QString message) { - Q_UNUSED(scId) - Q_UNUSED(ecId) - - if (level != "LOG") - std::cout << "[" << level.toStdString() << "] "; - std::cout << message.toStdString() << std::endl; -} diff --git a/plugins/cordova-plugin-console/src/ubuntu/console.h b/plugins/cordova-plugin-console/src/ubuntu/console.h deleted file mode 100644 index 3f3d163..0000000 --- a/plugins/cordova-plugin-console/src/ubuntu/console.h +++ /dev/null @@ -1,43 +0,0 @@ -/* - * 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 CONSOLE_H_FDSVCXGFRS -#define CONSOLE_H_FDSVCXGFRS - -#include - -#include - -class Console : public CPlugin { - Q_OBJECT -public: - explicit Console(Cordova *cordova); - - virtual const QString fullName() override { - return Console::fullID(); - } - - virtual const QString shortName() override { - return "Console"; - } - - static const QString fullID() { - return "Console"; - } - -public slots: - void logLevel(int scId, int ecId, QString level, QString message); -}; - -#endif diff --git a/plugins/cordova-plugin-console/src/wp/DebugConsole.cs b/plugins/cordova-plugin-console/src/wp/DebugConsole.cs deleted file mode 100644 index 9bb5476..0000000 --- a/plugins/cordova-plugin-console/src/wp/DebugConsole.cs +++ /dev/null @@ -1,47 +0,0 @@ -/* - 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.Windows.Shapes; -using System.Diagnostics; - -namespace WPCordovaClassLib.Cordova.Commands -{ - public class DebugConsole : BaseCommand - { - public void logLevel(string options) - { - string[] args = JSON.JsonHelper.Deserialize(options); - string level = args[0]; - string msg = args[1]; - - if (level.Equals("LOG")) - { - Debug.WriteLine(msg); - } - else - { - Debug.WriteLine(level + ": " + msg); - } - } - } -} diff --git a/plugins/cordova-plugin-console/tests/package.json b/plugins/cordova-plugin-console/tests/package.json deleted file mode 100644 index c7bc7ea..0000000 --- a/plugins/cordova-plugin-console/tests/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "cordova-plugin-console-tests", - "version": "1.0.7-dev", - "description": "", - "cordova": { - "id": "cordova-plugin-console-tests", - "platforms": [] - }, - "keywords": [ - "ecosystem:cordova" - ], - "author": "", - "license": "Apache 2.0" -} diff --git a/plugins/cordova-plugin-console/tests/plugin.xml b/plugins/cordova-plugin-console/tests/plugin.xml deleted file mode 100644 index 37c17d7..0000000 --- a/plugins/cordova-plugin-console/tests/plugin.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - - Cordova Console Plugin Tests - Apache 2.0 - - - - diff --git a/plugins/cordova-plugin-console/tests/tests.js b/plugins/cordova-plugin-console/tests/tests.js deleted file mode 100644 index 74765d9..0000000 --- a/plugins/cordova-plugin-console/tests/tests.js +++ /dev/null @@ -1,43 +0,0 @@ -/* - * - * 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 */ - -exports.defineAutoTests = function () { - describe("Console", function () { - it("console.spec.1 should exist", function() { - expect(window.console).toBeDefined(); - }); - - it("console.spec.2 has required methods log|warn|error", function(){ - expect(window.console.log).toBeDefined(); - expect(typeof window.console.log).toBe('function'); - - expect(window.console.warn).toBeDefined(); - expect(typeof window.console.warn).toBe('function'); - - expect(window.console.error).toBeDefined(); - expect(typeof window.console.error).toBe('function'); - }); - }); -}; - -exports.defineManualTests = function (contentEl, createActionButton) {}; diff --git a/plugins/cordova-plugin-device/CONTRIBUTING.md b/plugins/cordova-plugin-device/CONTRIBUTING.md deleted file mode 100644 index 4c8e6a5..0000000 --- a/plugins/cordova-plugin-device/CONTRIBUTING.md +++ /dev/null @@ -1,37 +0,0 @@ - - -# 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-device/LICENSE b/plugins/cordova-plugin-device/LICENSE deleted file mode 100644 index 7a4a3ea..0000000 --- a/plugins/cordova-plugin-device/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - 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-device/NOTICE b/plugins/cordova-plugin-device/NOTICE deleted file mode 100644 index 8ec56a5..0000000 --- a/plugins/cordova-plugin-device/NOTICE +++ /dev/null @@ -1,5 +0,0 @@ -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-device/README.md b/plugins/cordova-plugin-device/README.md deleted file mode 100644 index 048f028..0000000 --- a/plugins/cordova-plugin-device/README.md +++ /dev/null @@ -1,267 +0,0 @@ ---- -title: Device -description: Get device information. ---- - - -|AppVeyor|Travis CI| -|:-:|:-:| -|[![Build status](https://ci.appveyor.com/api/projects/status/github/apache/cordova-plugin-device?branch=master)](https://ci.appveyor.com/project/ApacheSoftwareFoundation/cordova-plugin-device)|[![Build Status](https://travis-ci.org/apache/cordova-plugin-device.svg?branch=master)](https://travis-ci.org/apache/cordova-plugin-device)| - -# cordova-plugin-device - -This plugin defines a global `device` object, which describes the device's hardware and software. -Although the object is in the global scope, it is not available until after the `deviceready` event. - -```js -document.addEventListener("deviceready", onDeviceReady, false); -function onDeviceReady() { - console.log(device.cordova); -} -``` - -Report issues with this plugin 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%20Device%22%20ORDER%20BY%20priority%20DESC%2C%20summary%20ASC%2C%20updatedDate%20DESC) - - -## Installation - - cordova plugin add cordova-plugin-device - -## Properties - -- device.cordova -- device.model -- device.platform -- device.uuid -- device.version -- device.manufacturer -- device.isVirtual -- device.serial - -## device.cordova - -Get the version of Cordova running on the device. - -### Supported Platforms - -- Android -- Browser -- iOS -- Windows -- OSX - -## device.model - -The `device.model` returns the name of the device's model or -product. The value is set by the device manufacturer and may be -different across versions of the same product. - -### Supported Platforms - -- Android -- Browser -- iOS -- Windows -- OSX - -### Quick Example - -```js -// Android: Nexus One returns "Passion" (Nexus One code name) -// Motorola Droid returns "voles" -// BlackBerry: Torch 9800 returns "9800" -// Browser: Google Chrome returns "Chrome" -// Safari returns "Safari" -// iOS: for the iPad Mini, returns iPad2,5; iPhone 5 is iPhone 5,1. See http://theiphonewiki.com/wiki/index.php?title=Models -// OSX: returns "x86_64" -// -var model = device.model; -``` - -### Android Quirks - -- Gets the [product name](http://developer.android.com/reference/android/os/Build.html#PRODUCT) instead of the [model name](http://developer.android.com/reference/android/os/Build.html#MODEL), which is often the production code name. For example, the Nexus One returns `Passion`, and Motorola Droid returns `voles`. - -## device.platform - -Get the device's operating system name. - -```js -var string = device.platform; -``` -### Supported Platforms - -- Android -- Browser -- iOS -- Windows -- OSX - -### Quick Example - -```js -// Depending on the device, a few examples are: -// - "Android" -// - "BlackBerry 10" -// - "browser" -// - "iOS" -// - "WinCE" -// - "Tizen" -// - "Mac OS X" -var devicePlatform = device.platform; -``` - -## device.uuid - -Get the device's Universally Unique Identifier ([UUID](http://en.wikipedia.org/wiki/Universally_Unique_Identifier)). - -```js -var string = device.uuid; -``` - -### Description - -The details of how a UUID is generated are determined by the device manufacturer and are specific to the device's platform or model. - -### Supported Platforms - -- Android -- iOS -- Windows -- OSX - -### Quick Example - -```js -// Android: Returns a random 64-bit integer (as a string, again!) -// The integer is generated on the device's first boot -// -// BlackBerry: Returns the PIN number of the device -// This is a nine-digit unique integer (as a string, though!) -// -// iPhone: (Paraphrased from the UIDevice Class documentation) -// Returns the [UIDevice identifierForVendor] UUID which is unique and the same for all apps installed by the same vendor. However the UUID can be different if the user deletes all apps from the vendor and then reinstalls it. -// Windows Phone 7 : Returns a hash of device+current user, -// if the user is not defined, a guid is generated and will persist until the app is uninstalled -// Tizen: returns the device IMEI (International Mobile Equipment Identity or IMEI is a number -// unique to every GSM and UMTS mobile phone. -var deviceID = device.uuid; -``` - -### iOS Quirk - -The `uuid` on iOS uses the identifierForVendor property. It is unique to the device across the same vendor, but will be different for different vendors and will change if all apps from the vendor are deleted and then reinstalled. -Refer [here](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIDevice_Class/#//apple_ref/occ/instp/UIDevice/identifierForVendor) for details. -The UUID will be the same if app is restored from a backup or iCloud as it is saved in preferences. Users using older versions of this plugin will still receive the same previous UUID generated by another means as it will be retrieved from preferences. - -### OSX Quirk - -The `uuid` on OSX is generated automatically if it does not exist yet and is stored in the `standardUserDefaults` in the `CDVUUID` property. - -## device.version - -Get the operating system version. - - var string = device.version; - -### Supported Platforms - -- Android 2.1+ -- Browser -- iOS -- Windows -- OSX - -### Quick Example - -```js -// Android: Froyo OS would return "2.2" -// Eclair OS would return "2.1", "2.0.1", or "2.0" -// Version can also return update level "2.1-update1" -// -// BlackBerry: Torch 9800 using OS 6.0 would return "6.0.0.600" -// -// Browser: Returns version number for the browser -// -// iPhone: iOS 3.2 returns "3.2" -// -// Windows Phone 7: returns current OS version number, ex. on Mango returns 7.10.7720 -// Windows 8: return the current OS version, ex on Windows 8.1 returns 6.3.9600.16384 -// Tizen: returns "TIZEN_20120425_2" -// OSX: El Capitan would return "10.11.2" -// -var deviceVersion = device.version; -``` - -## device.manufacturer - -Get the device's manufacturer. - - var string = device.manufacturer; - -### Supported Platforms - -- Android -- iOS -- Windows - -### Quick Example - -```js -// Android: Motorola XT1032 would return "motorola" -// BlackBerry: returns "BlackBerry" -// iPhone: returns "Apple" -// -var deviceManufacturer = device.manufacturer; -``` - -## device.isVirtual - -whether the device is running on a simulator. - -```js -var isSim = device.isVirtual; -``` - -### Supported Platforms - -- Android 2.1+ -- Browser -- iOS -- Windows -- OSX - -### OSX and Browser Quirk - -The `isVirtual` property on OS X and Browser always returns false. - -## device.serial - -Get the device hardware serial number ([SERIAL](http://developer.android.com/reference/android/os/Build.html#SERIAL)). - -```js -var string = device.serial; -``` - -### Supported Platforms - -- Android -- OSX - diff --git a/plugins/cordova-plugin-device/RELEASENOTES.md b/plugins/cordova-plugin-device/RELEASENOTES.md deleted file mode 100644 index 12d4008..0000000 --- a/plugins/cordova-plugin-device/RELEASENOTES.md +++ /dev/null @@ -1,181 +0,0 @@ - -# Release Notes - -### 2.0.2 (Apr 12, 2018) -* [CB-13893](https://issues.apache.org/jira/browse/CB-13893) **iOS** delete `libz.tbd` from device plugin - -### 2.0.1 (Dec 27, 2017) -* [CB-13702](https://issues.apache.org/jira/browse/CB-13702) Fix to allow 2.0.0 version install - -### 2.0.0 (Dec 15, 2017) -* [CB-13670](https://issues.apache.org/jira/browse/CB-13670) Remove deprecated platforms - -### 1.1.7 (Nov 06, 2017) -* [CB-13472](https://issues.apache.org/jira/browse/CB-13472) (CI) Fixed Travis **Android** builds again -* [CB-12895](https://issues.apache.org/jira/browse/CB-12895) setup `eslint` and removed `jshint` -* [CB-13113](https://issues.apache.org/jira/browse/CB-13113) (browser) `device.isVirtual` is always false -* [CB-13028](https://issues.apache.org/jira/browse/CB-13028) (CI) **Browser** builds on Travis and AppVeyor -* [CB-13000](https://issues.apache.org/jira/browse/CB-13000) (CI) Speed up **Android** builds -* [CB-12847](https://issues.apache.org/jira/browse/CB-12847) added `bugs` entry to `package.json`. - -### 1.1.6 (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 -* [CB-12105](https://issues.apache.org/jira/browse/CB-12105) (browser) Properly detect Edge - -### 1.1.5 (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 - -### 1.1.4 (Dec 07, 2016) -* [CB-12224](https://issues.apache.org/jira/browse/CB-12224) Updated version and RELEASENOTES.md for release 1.1.4 -* [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. - -### 1.1.3 (Sep 08, 2016) -* [CB-11795](https://issues.apache.org/jira/browse/CB-11795) Add 'protective' entry to cordovaDependencies -* Add badges for paramedic builds on Jenkins -* Add pull request template. -* Readme: Add fenced code blocks with langauage hints -* [CB-10996](https://issues.apache.org/jira/browse/CB-10996) Adding front matter to `README.md` - -### 1.1.2 (Apr 15, 2016) -* Use passed device, follow create policy forf `CFUUIDCreate` -* [CB-10631](https://issues.apache.org/jira/browse/CB-10631) Fix for `device.uuid` in **iOS 5.1.1** -* Updating the comment to exclude URL -* [CB-10636](https://issues.apache.org/jira/browse/CB-10636) Add `JSHint` for plugins -* Refactored `deviceInfo` on **iOS** for better readability. - -### 1.1.1 (Jan 15, 2016) -* [CB-10238](https://issues.apache.org/jira/browse/CB-10238) **OSX** Move `device-plugin` out from `cordovalib` to the plugin repository -* [CB-9923](https://issues.apache.org/jira/browse/CB-9923) Update `device.platform` documentation for **Browser** platform - -### 1.1.0 (Nov 18, 2015) -* [CB-10035](https://issues.apache.org/jira/browse/CB-10035) Updated `RELEASENOTES` to be newest to oldest -* Add `isVirtual` for **Windows Phone 8.x** -* Added basic **Android** support for hardware serial number -* [CB-9865](https://issues.apache.org/jira/browse/CB-9865) Better simulator detection for **iOS** -* Fixing contribute link. -* Added **WP8** implementation -* update to use `TARGET_OS_SIMULATOR` as `TARGET_IPHONE_SIMULATOR` is deprecated. -* update code to use 'isVirtual' -* create test to verify existence and type of new property 'isVirtual' -* add `isSimulator` for **iOS** & **Android** device -* Updated documentation to mention backwards compatibility -* Updated **README** to reflect new behaviour and quirks on **iOS** -* Check user defaults first to maintain backwards compatibility -* Changed `UUID` to use `[UIDevice identifierForVendor]` - -### 1.0.1 (Jun 17, 2015) -* [CB-9128](https://issues.apache.org/jira/browse/CB-9128) cordova-plugin-device documentation translation: cordova-plugin-device -* Attempts to corrent npm markdown issue - -### 1.0.0 (Apr 15, 2015) -* [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) 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 -* [CB-8653](https://issues.apache.org/jira/browse/CB-8653) Updated Readme -* remove defunct windows8 version -* add travis badge -* Add cross-plugin ios paramedic test running for TravisCI -* [CB-8538](https://issues.apache.org/jira/browse/CB-8538) Added package.json file - -### 0.3.0 (Feb 04, 2015) -* Added device.manufacturer property for Android, iOS, Blackberry, WP8 -* Support for Windows Phone 8 ANID2 ANID is only supported up to Windows Phone 7.5 -* [CB-8351](https://issues.apache.org/jira/browse/CB-8351) Use a local copy of uniqueAppInstanceIdentifier rather than CordovaLib's version -* browser: Fixed a bug that caused an "cannot call method of undefined" error if the browser's user agent wasn't recognized - -### 0.2.13 (Dec 02, 2014) -* Changing `device.platform` to always report the platform as "browser". -* [CB-5892](https://issues.apache.org/jira/browse/CB-5892) - Remove deprecated `window.Settings` -* [CB-7700](https://issues.apache.org/jira/browse/CB-7700) cordova-plugin-device documentation translation: cordova-plugin-device -* [CB-7571](https://issues.apache.org/jira/browse/CB-7571) Bump version of nested plugin to match parent plugin - -### 0.2.12 (Sep 17, 2014) -* [CB-7471](https://issues.apache.org/jira/browse/CB-7471) cordova-plugin-device documentation translation -* [CB-7552](https://issues.apache.org/jira/browse/CB-7552) device.name docs have not been removed -* [fxos] Fix cordova version -* added status box and documentation to manual tests -* [fxos] Fix cordova version -* added status box and documentation to manual tests -* Added plugin support for the browser -* [CB-7262](https://issues.apache.org/jira/browse/CB-7262) Adds support for universal windows apps. - -### 0.2.11 (Aug 06, 2014) -* [FFOS] update DeviceProxy.js -* [CB-6127](https://issues.apache.org/jira/browse/CB-6127) Updated translations for docs -* Use Windows system calls to get better info - -### 0.2.10 (Jun 05, 2014) -* [CB-6127](https://issues.apache.org/jira/browse/CB-6127) Spanish and French Translations added. Github close #12 -* Changing 1.5 to 2.0 -* added firefoxos version - conversion -* added firefoxos version -* [CB-6800](https://issues.apache.org/jira/browse/CB-6800) Add license -* [CB-6491](https://issues.apache.org/jira/browse/CB-6491) add CONTRIBUTING.md - -### 0.2.9 (Apr 17, 2014) -* [CB-5105](https://issues.apache.org/jira/browse/CB-5105): [Android, windows8, WP, BlackBerry10] Removed dead code for device.version -* [CB-6422](https://issues.apache.org/jira/browse/CB-6422): [windows8] use cordova/exec/proxy -* [CB-6460](https://issues.apache.org/jira/browse/CB-6460): Update license headers -* Add NOTICE file - -### 0.2.8 (Feb 05, 2014) -* Tizen support added - -### 0.2.7 (Jan 07, 2014) -* [CB-5737](https://issues.apache.org/jira/browse/CB-5737) Fix exception on close caused by left over telephony code from [CB-5504](https://issues.apache.org/jira/browse/CB-5504) - -### 0.2.6 (Jan 02, 2014) -* [CB-5658](https://issues.apache.org/jira/browse/CB-5658) Add doc/index.md for Device plugin -* [CB-5504](https://issues.apache.org/jira/browse/CB-5504) Moving Telephony Logic out of Device - -### 0.2.5 (Dec 4, 2013) -* [CB-5316](https://issues.apache.org/jira/browse/CB-5316) Spell Cordova as a brand unless it's a command or script -* [ubuntu] use cordova/exec/proxy -* add ubuntu platform -* Modify Device.platform logic to use amazon-fireos as the platform for Amazon Devices -* 1. Added amazon-fireos platform. 2. Change to use cordova-amazon-fireos as the platform if user agent contains 'cordova-amazon-fireos' - -### 0.2.4 (Oct 28, 2013) -* [CB-5128](https://issues.apache.org/jira/browse/CB-5128): added repo + issue tag in plugin.xml for device plugin -* [CB-5085](https://issues.apache.org/jira/browse/CB-5085) device.cordova returning wrong value -* [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 -* [windows8] commandProxy has moved -* [BlackBerry10] removed uneeded permission tags in plugin.xml -* [CB-4889](https://issues.apache.org/jira/browse/CB-4889) renaming org.apache.cordova.core.device to org.apache.cordova.device -* Rename CHANGELOG.md -> RELEASENOTES.md -* updated to use commandProxy for ffos -* add firefoxos support -* [CB-4752](https://issues.apache.org/jira/browse/CB-4752) Incremented plugin version on dev branch. - -### 0.2.1 (Sept 5, 2013) -* removed extraneous print statement -* [CB-4432](https://issues.apache.org/jira/browse/CB-4432) copyright notice change diff --git a/plugins/cordova-plugin-device/doc/de/README.md b/plugins/cordova-plugin-device/doc/de/README.md deleted file mode 100644 index 81f89e9..0000000 --- a/plugins/cordova-plugin-device/doc/de/README.md +++ /dev/null @@ -1,203 +0,0 @@ - - -# cordova-plugin-device - -[![Build Status](https://travis-ci.org/apache/cordova-plugin-device.svg?branch=master)](https://travis-ci.org/apache/cordova-plugin-device) - -Dieses Plugin definiert eine globale `device` -Objekt, das des Geräts Hard- und Software beschreibt. Das Objekt im globalen Gültigkeitsbereich ist es zwar nicht verfügbar bis nach dem `deviceready` Ereignis. - - document.addEventListener("deviceready", onDeviceReady, false); - function onDeviceReady() { - console.log(device.cordova); - } - - -## Installation - - cordova plugin add cordova-plugin-device - - -## Eigenschaften - - * device.cordova - * device.model - * device.platform - * device.uuid - * device.version - -## device.cordova - -Rufen Sie die Version von Cordova, die auf dem Gerät ausgeführt. - -### Unterstützte Plattformen - - * Amazon Fire OS - * Android - * BlackBerry 10 - * Browser - * Firefox OS - * iOS - * Tizen - * Windows Phone 7 und 8 - * Windows 8 - -## device.model - -Die `device.model` gibt den Namen der Modell- oder des Geräts zurück. Der Wert wird vom Gerätehersteller festgelegt und kann zwischen den Versionen des gleichen Produkts unterschiedlich sein. - -### Unterstützte Plattformen - - * Android - * BlackBerry 10 - * Browser - * iOS - * Tizen - * Windows Phone 7 und 8 - * Windows 8 - -### Kurzes Beispiel - - // Android: Nexus One returns "Passion" (Nexus One code name) - // Motorola Droid returns "voles" - // BlackBerry: Torch 9800 returns "9800" - // Browser: Google Chrome returns "Chrome" - // Safari returns "Safari" - // iOS: for the iPad Mini, returns iPad2,5; iPhone 5 is iPhone 5,1. Finden Sie unter http://theiphonewiki.com/wiki/index.php?title=Models / / Var-Modell = device.model; - - -### Android Eigenarten - - * Ruft den [Produktname](http://developer.android.com/reference/android/os/Build.html#PRODUCT) anstelle des [Modellnamens](http://developer.android.com/reference/android/os/Build.html#MODEL), das ist oft der Codename für die Produktion. Beispielsweise das Nexus One gibt `Passion` , und Motorola Droid gibt`voles`. - -### Tizen Macken - - * Gibt z. B. das Gerätemodell von dem Kreditor zugeordnet,`TIZEN` - -### Windows Phone 7 und 8 Eigenarten - - * Gibt das vom Hersteller angegebenen Gerätemodell zurück. Beispielsweise gibt der Samsung-Fokus`SGH-i917`. - -## device.platform - -Name des Betriebssystems des Geräts zu erhalten. - - var string = device.platform; - - -### Unterstützte Plattformen - - * Android - * BlackBerry 10 - * Browser4 - * Firefox OS - * iOS - * Tizen - * Windows Phone 7 und 8 - * Windows 8 - -### Kurzes Beispiel - - // Depending on the device, a few examples are: - // - "Android" - // - "BlackBerry 10" - // - Browser: returns "MacIntel" on Mac - // returns "Win32" on Windows - // - "iOS" - // - "WinCE" - // - "Tizen" - var devicePlatform = device.platform; - - -### Windows Phone 7 Macken - -Windows Phone 7 Geräte melden die Plattform als`WinCE`. - -### Windows Phone 8 Macken - -Windows Phone 8 Geräte melden die Plattform als`Win32NT`. - -## device.uuid - -Des Geräts Universally Unique Identifier ([UUID](http://en.wikipedia.org/wiki/Universally_Unique_Identifier) zu erhalten). - - var string = device.uuid; - - -### Beschreibung - -Die Details wie eine UUID generiert wird werden vom Gerätehersteller und beziehen sich auf die Plattform oder das Modell des Geräts. - -### Unterstützte Plattformen - - * Android - * BlackBerry 10 - * iOS - * Tizen - * Windows Phone 7 und 8 - * Windows 8 - -### Kurzes Beispiel - - / / Android: wird eine zufällige 64-Bit-Ganzzahl (als Zeichenfolge, wieder!) / / die ganze Zahl wird beim ersten Start des Geräts erzeugt / / / / BlackBerry: gibt die PIN-Nummer des Gerätes / / Dies ist eine neunstellige eindeutige Ganzzahl (als String, obwohl!) / / / / iPhone: (paraphrasiert aus der Dokumentation zur UIDevice-Klasse) / / liefert eine Reihe von Hash-Werte, die aus mehreren Hardware erstellt identifiziert. - / / Es ist gewährleistet, dass für jedes Gerät eindeutig sein und kann nicht gebunden werden / / an den Benutzer weitergeleitet. - / / Windows Phone 7: gibt einen Hash des Gerät + aktueller Benutzer, / / wenn der Benutzer nicht definiert ist, eine Guid generiert und wird weiter bestehen, bis die app deinstalliert wird / / Tizen: gibt das Gerät IMEI (International Mobile Equipment Identity oder IMEI ist eine Zahl / / einzigartig für jedes GSM- und UMTS-Handy. - var deviceID = device.uuid; - - -### iOS Quirk - -Die `uuid` auf iOS ist nicht eindeutig zu einem Gerät, aber für jede Anwendung, für jede Installation variiert. Es ändert sich, wenn Sie löschen und neu die app installieren, und möglicherweise auch beim iOS zu aktualisieren, oder auch ein Upgrade möglich die app pro Version (scheinbaren in iOS 5.1). Die `uuid` ist kein zuverlässiger Wert. - -### Windows Phone 7 und 8 Eigenarten - -Die `uuid` für Windows Phone 7 die Berechtigung erfordert `ID_CAP_IDENTITY_DEVICE` . Microsoft wird diese Eigenschaft wahrscheinlich bald abzuschaffen. Wenn die Funktion nicht verfügbar ist, generiert die Anwendung eine persistente Guid, die für die Dauer der Installation der Anwendung auf dem Gerät gewährleistet ist. - -## device.version - -Version des Betriebssystems zu erhalten. - - var string = device.version; - - -### Unterstützte Plattformen - - * Android 2.1 + - * BlackBerry 10 - * Browser - * iOS - * Tizen - * Windows Phone 7 und 8 - * Windows 8 - -### Kurzes Beispiel - - // Android: Froyo OS would return "2.2" - // Eclair OS would return "2.1", "2.0.1", or "2.0" - // Version can also return update level "2.1-update1" - // - // BlackBerry: Torch 9800 using OS 6.0 would return "6.0.0.600" - // - // Browser: Returns version number for the browser - // - // iPhone: iOS 3.2 returns "3.2" - // - // Windows Phone 7: returns current OS version number, ex. on Mango returns 7.10.7720 - // Tizen: returns "TIZEN_20120425_2" - var deviceVersion = device.version; \ No newline at end of file diff --git a/plugins/cordova-plugin-device/doc/de/index.md b/plugins/cordova-plugin-device/doc/de/index.md deleted file mode 100644 index e3a537e..0000000 --- a/plugins/cordova-plugin-device/doc/de/index.md +++ /dev/null @@ -1,206 +0,0 @@ - - -# cordova-plugin-device - -Dieses Plugin definiert eine globale `device` -Objekt, das des Geräts Hard- und Software beschreibt. Das Objekt im globalen Gültigkeitsbereich ist es zwar nicht verfügbar bis nach dem `deviceready` Ereignis. - - document.addEventListener("deviceready", onDeviceReady, false); - function onDeviceReady() { - console.log(device.cordova); - } - - -## Installation - - cordova plugin add cordova-plugin-device - - -## Eigenschaften - -* device.cordova -* device.model -* device.platform -* device.uuid -* device.version - -## device.cordova - -Rufen Sie die Version von Cordova, die auf dem Gerät ausgeführt. - -### Unterstützte Plattformen - -* Amazon Fire OS -* Android -* BlackBerry 10 -* Browser -* Firefox OS -* iOS -* Tizen -* Windows Phone 7 und 8 -* Windows 8 - -## device.model - -Die `device.model` gibt den Namen der Modell- oder des Geräts zurück. Der Wert wird vom Gerätehersteller festgelegt und kann zwischen den Versionen des gleichen Produkts unterschiedlich sein. - -### Unterstützte Plattformen - -* Android -* BlackBerry 10 -* Browser -* iOS -* Tizen -* Windows Phone 7 und 8 -* Windows 8 - -### Kurzes Beispiel - - // Android: Nexus One returns "Passion" (Nexus One code name) - // Motorola Droid returns "voles" - // BlackBerry: Torch 9800 returns "9800" - // Browser: Google Chrome returns "Chrome" - // Safari returns "Safari" - // iOS: for the iPad Mini, returns iPad2,5; iPhone 5 is iPhone 5,1. Finden Sie unter http://theiphonewiki.com/wiki/index.php?title=Models / / Var-Modell = device.model; - - -### Android Eigenarten - -* Ruft den [Produktname][1] anstelle des [Modellnamens][2], das ist oft der Codename für die Produktion. Beispielsweise das Nexus One gibt `Passion` , und Motorola Droid gibt`voles`. - - [1]: http://developer.android.com/reference/android/os/Build.html#PRODUCT - [2]: http://developer.android.com/reference/android/os/Build.html#MODEL - -### Tizen Macken - -* Gibt z. B. das Gerätemodell von dem Kreditor zugeordnet,`TIZEN` - -### Windows Phone 7 und 8 Eigenarten - -* Gibt das vom Hersteller angegebenen Gerätemodell zurück. Beispielsweise gibt der Samsung-Fokus`SGH-i917`. - -## device.platform - -Name des Betriebssystems des Geräts zu erhalten. - - var string = device.platform; - - -### Unterstützte Plattformen - -* Android -* BlackBerry 10 -* Browser4 -* Firefox OS -* iOS -* Tizen -* Windows Phone 7 und 8 -* Windows 8 - -### Kurzes Beispiel - - // Depending on the device, a few examples are: - // - "Android" - // - "BlackBerry 10" - // - Browser: returns "MacIntel" on Mac - // returns "Win32" on Windows - // - "iOS" - // - "WinCE" - // - "Tizen" - var devicePlatform = device.platform; - - -### Windows Phone 7 Macken - -Windows Phone 7 Geräte melden die Plattform als`WinCE`. - -### Windows Phone 8 Macken - -Windows Phone 8 Geräte melden die Plattform als`Win32NT`. - -## device.uuid - -Des Geräts Universally Unique Identifier ([UUID][3] zu erhalten). - - [3]: http://en.wikipedia.org/wiki/Universally_Unique_Identifier - - var string = device.uuid; - - -### Beschreibung - -Die Details wie eine UUID generiert wird werden vom Gerätehersteller und beziehen sich auf die Plattform oder das Modell des Geräts. - -### Unterstützte Plattformen - -* Android -* BlackBerry 10 -* iOS -* Tizen -* Windows Phone 7 und 8 -* Windows 8 - -### Kurzes Beispiel - - / / Android: wird eine zufällige 64-Bit-Ganzzahl (als Zeichenfolge, wieder!) / / die ganze Zahl wird beim ersten Start des Geräts erzeugt / / / / BlackBerry: gibt die PIN-Nummer des Gerätes / / Dies ist eine neunstellige eindeutige Ganzzahl (als String, obwohl!) / / / / iPhone: (paraphrasiert aus der Dokumentation zur UIDevice-Klasse) / / liefert eine Reihe von Hash-Werte, die aus mehreren Hardware erstellt identifiziert. - / / Es ist gewährleistet, dass für jedes Gerät eindeutig sein und kann nicht gebunden werden / / an den Benutzer weitergeleitet. - / / Windows Phone 7: gibt einen Hash des Gerät + aktueller Benutzer, / / wenn der Benutzer nicht definiert ist, eine Guid generiert und wird weiter bestehen, bis die app deinstalliert wird / / Tizen: gibt das Gerät IMEI (International Mobile Equipment Identity oder IMEI ist eine Zahl / / einzigartig für jedes GSM- und UMTS-Handy. - var deviceID = device.uuid; - - -### iOS Quirk - -Die `uuid` auf iOS ist nicht eindeutig zu einem Gerät, aber für jede Anwendung, für jede Installation variiert. Es ändert sich, wenn Sie löschen und neu die app installieren, und möglicherweise auch beim iOS zu aktualisieren, oder auch ein Upgrade möglich die app pro Version (scheinbaren in iOS 5.1). Die `uuid` ist kein zuverlässiger Wert. - -### Windows Phone 7 und 8 Eigenarten - -Die `uuid` für Windows Phone 7 die Berechtigung erfordert `ID_CAP_IDENTITY_DEVICE` . Microsoft wird diese Eigenschaft wahrscheinlich bald abzuschaffen. Wenn die Funktion nicht verfügbar ist, generiert die Anwendung eine persistente Guid, die für die Dauer der Installation der Anwendung auf dem Gerät gewährleistet ist. - -## device.version - -Version des Betriebssystems zu erhalten. - - var string = device.version; - - -### Unterstützte Plattformen - -* Android 2.1 + -* BlackBerry 10 -* Browser -* iOS -* Tizen -* Windows Phone 7 und 8 -* Windows 8 - -### Kurzes Beispiel - - // Android: Froyo OS would return "2.2" - // Eclair OS would return "2.1", "2.0.1", or "2.0" - // Version can also return update level "2.1-update1" - // - // BlackBerry: Torch 9800 using OS 6.0 would return "6.0.0.600" - // - // Browser: Returns version number for the browser - // - // iPhone: iOS 3.2 returns "3.2" - // - // Windows Phone 7: returns current OS version number, ex. on Mango returns 7.10.7720 - // Tizen: returns "TIZEN_20120425_2" - var deviceVersion = device.version; diff --git a/plugins/cordova-plugin-device/doc/es/README.md b/plugins/cordova-plugin-device/doc/es/README.md deleted file mode 100644 index a27abfb..0000000 --- a/plugins/cordova-plugin-device/doc/es/README.md +++ /dev/null @@ -1,216 +0,0 @@ - - -# cordova-plugin-device - -[![Build Status](https://travis-ci.org/apache/cordova-plugin-device.svg?branch=master)](https://travis-ci.org/apache/cordova-plugin-device) - -Este plugin define un global `device` objeto que describe del dispositivo hardware y software. Aunque el objeto está en el ámbito global, no está disponible hasta después de la `deviceready` evento. - - document.addEventListener("deviceready", onDeviceReady, false); - function onDeviceReady() { - console.log(device.cordova); - } - - -## Instalación - - cordova plugin add cordova-plugin-device - - -## Propiedades - - * device.cordova - * device.model - * device.platform - * device.uuid - * device.version - -## device.cordova - -Obtener la versión de Cordova que se ejecuta en el dispositivo. - -### Plataformas soportadas - - * Amazon fire OS - * Android - * BlackBerry 10 - * Explorador - * Firefox OS - * iOS - * Tizen - * Windows Phone 7 y 8 - * Windows 8 - -## device.model - -El `device.model` devuelve el nombre de modelo del dispositivo o producto. El valor es fijado por el fabricante del dispositivo y puede ser diferente a través de versiones del mismo producto. - -### Plataformas soportadas - - * Android - * BlackBerry 10 - * Explorador - * iOS - * Tizen - * Windows Phone 7 y 8 - * Windows 8 - -### Ejemplo rápido - - // Android: Nexus One returns "Passion" (Nexus One code name) - // Motorola Droid returns "voles" - // BlackBerry: Torch 9800 returns "9800" - // Browser: Google Chrome returns "Chrome" - // Safari returns "Safari" - // iOS: for the iPad Mini, returns iPad2,5; iPhone 5 is iPhone 5,1. See http://theiphonewiki.com/wiki/index.php?title=Models - // - var model = device.model; - - -### Rarezas Android - - * Obtiene el [nombre del producto](http://developer.android.com/reference/android/os/Build.html#PRODUCT) en lugar del [nombre de la modelo](http://developer.android.com/reference/android/os/Build.html#MODEL), que es a menudo el nombre de código de producción. Por ejemplo, el Nexus One devuelve `Passion` y Motorola Droid devuelve `voles`. - -### Rarezas Tizen - - * Devuelve que el modelo de dispositivo asignado por el proveedor, por ejemplo, `TIZEN` - -### Windows Phone 7 y 8 rarezas - - * Devuelve el modelo de dispositivo especificado por el fabricante. Por ejemplo, el Samsung Focus devuelve `SGH-i917`. - -## device.platform - -Obtener el nombre del sistema operativo del dispositivo. - - var string = device.platform; - - -### Plataformas soportadas - - * Android - * BlackBerry 10 - * Browser4 - * Firefox OS - * iOS - * Tizen - * Windows Phone 7 y 8 - * Windows 8 - -### Ejemplo rápido - - // Depending on the device, a few examples are: - // - "Android" - // - "BlackBerry 10" - // - Browser: returns "MacIntel" on Mac - // returns "Win32" on Windows - // - "iOS" - // - "WinCE" - // - "Tizen" - var devicePlatform = device.platform; - - -### Windows Phone 7 rarezas - -Dispositivos Windows Phone 7 informe de la plataforma como `WinCE`. - -### Windows Phone 8 rarezas - -Dispositivos Windows Phone 8 Informe la plataforma como `Win32NT`. - -## device.uuid - -Obtener identificador universalmente única del dispositivo ([UUID](http://en.wikipedia.org/wiki/Universally_Unique_Identifier)). - - var string = device.uuid; - - -### Descripción - -Los detalles de cómo se genera un UUID son determinados por el fabricante del dispositivo y son específicos a la plataforma del dispositivo o modelo. - -### Plataformas soportadas - - * Android - * BlackBerry 10 - * iOS - * Tizen - * Windows Phone 7 y 8 - * Windows 8 - -### Ejemplo rápido - - // Android: Returns a random 64-bit integer (as a string, again!) - // The integer is generated on the device's first boot - // - // BlackBerry: Returns the PIN number of the device - // This is a nine-digit unique integer (as a string, though!) - // - // iPhone: (Paraphrased from the UIDevice Class documentation) - // Returns a string of hash values created from multiple hardware identifies. - // It is guaranteed to be unique for every device and can't be tied - // to the user account. - // Windows Phone 7 : Returns a hash of device+current user, - // if the user is not defined, a guid is generated and will persist until the app is uninstalled - // Tizen: returns the device IMEI (International Mobile Equipment Identity or IMEI is a number - // unique to every GSM and UMTS mobile phone. - var deviceID = device.uuid; - - -### Rarezas de iOS - -El `uuid` en iOS no es exclusiva de un dispositivo, pero varía para cada aplicación, para cada instalación. Cambia si puedes borrar y volver a instalar la aplicación, y posiblemente también cuándo actualizar iOS, o incluso mejorar la aplicación por la versión (evidente en iOS 5.1). El `uuid` no es un valor confiable. - -### Windows Phone 7 y 8 rarezas - -El `uuid` para Windows Phone 7 requiere el permiso `ID_CAP_IDENTITY_DEVICE`. Microsoft pronto probablemente desaprueban esta propiedad. Si la capacidad no está disponible, la aplicación genera un guid persistente que se mantiene durante la duración de la instalación de la aplicación en el dispositivo. - -## device.version - -Obtener la versión del sistema operativo. - - var string = device.version; - - -### Plataformas soportadas - - * Android 2.1 + - * BlackBerry 10 - * Explorador - * iOS - * Tizen - * Windows Phone 7 y 8 - * Windows 8 - -### Ejemplo rápido - - // Android: Froyo OS would return "2.2" - // Eclair OS would return "2.1", "2.0.1", or "2.0" - // Version can also return update level "2.1-update1" - // - // BlackBerry: Torch 9800 using OS 6.0 would return "6.0.0.600" - // - // Browser: Returns version number for the browser - // - // iPhone: iOS 3.2 returns "3.2" - // - // Windows Phone 7: returns current OS version number, ex. on Mango returns 7.10.7720 - // Tizen: returns "TIZEN_20120425_2" - var deviceVersion = device.version; \ No newline at end of file diff --git a/plugins/cordova-plugin-device/doc/es/index.md b/plugins/cordova-plugin-device/doc/es/index.md deleted file mode 100644 index f4a5897..0000000 --- a/plugins/cordova-plugin-device/doc/es/index.md +++ /dev/null @@ -1,220 +0,0 @@ - - -# cordova-plugin-device - -Este plugin define un global `device` objeto que describe del dispositivo hardware y software. Aunque el objeto está en el ámbito global, no está disponible hasta después de la `deviceready` evento. - - document.addEventListener("deviceready", onDeviceReady, false); - function onDeviceReady() { - console.log(device.cordova); - } - - -## Instalación - - cordova plugin add cordova-plugin-device - - -## Propiedades - -* device.cordova -* device.model -* device.platform -* device.uuid -* device.version - -## device.cordova - -Obtener la versión de Cordova que se ejecuta en el dispositivo. - -### Plataformas soportadas - -* Amazon fire OS -* Android -* BlackBerry 10 -* Explorador -* Firefox OS -* iOS -* Tizen -* Windows Phone 7 y 8 -* Windows 8 - -## device.model - -El `device.model` devuelve el nombre de modelo del dispositivo o producto. El valor es fijado por el fabricante del dispositivo y puede ser diferente a través de versiones del mismo producto. - -### Plataformas soportadas - -* Android -* BlackBerry 10 -* Explorador -* iOS -* Tizen -* Windows Phone 7 y 8 -* Windows 8 - -### Ejemplo rápido - - // Android: Nexus One returns "Passion" (Nexus One code name) - // Motorola Droid returns "voles" - // BlackBerry: Torch 9800 returns "9800" - // Browser: Google Chrome returns "Chrome" - // Safari returns "Safari" - // iOS: for the iPad Mini, returns iPad2,5; iPhone 5 is iPhone 5,1. See http://theiphonewiki.com/wiki/index.php?title=Models - // - var model = device.model; - - -### Rarezas Android - -* Obtiene el [nombre del producto][1] en lugar del [nombre de la modelo][2], que es a menudo el nombre de código de producción. Por ejemplo, el Nexus One devuelve `Passion` y Motorola Droid devuelve `voles`. - - [1]: http://developer.android.com/reference/android/os/Build.html#PRODUCT - [2]: http://developer.android.com/reference/android/os/Build.html#MODEL - -### Rarezas Tizen - -* Devuelve que el modelo de dispositivo asignado por el proveedor, por ejemplo, `TIZEN` - -### Windows Phone 7 y 8 rarezas - -* Devuelve el modelo de dispositivo especificado por el fabricante. Por ejemplo, el Samsung Focus devuelve `SGH-i917`. - -## device.platform - -Obtener el nombre del sistema operativo del dispositivo. - - var string = device.platform; - - -### Plataformas soportadas - -* Android -* BlackBerry 10 -* Browser4 -* Firefox OS -* iOS -* Tizen -* Windows Phone 7 y 8 -* Windows 8 - -### Ejemplo rápido - - // Depending on the device, a few examples are: - // - "Android" - // - "BlackBerry 10" - // - Browser: returns "MacIntel" on Mac - // returns "Win32" on Windows - // - "iOS" - // - "WinCE" - // - "Tizen" - var devicePlatform = device.platform; - - -### Windows Phone 7 rarezas - -Dispositivos Windows Phone 7 informe de la plataforma como `WinCE`. - -### Windows Phone 8 rarezas - -Dispositivos Windows Phone 8 Informe la plataforma como `Win32NT`. - -## device.uuid - -Obtener identificador universalmente única del dispositivo ([UUID][3]). - - [3]: http://en.wikipedia.org/wiki/Universally_Unique_Identifier - - var string = device.uuid; - - -### Descripción - -Los detalles de cómo se genera un UUID son determinados por el fabricante del dispositivo y son específicos a la plataforma del dispositivo o modelo. - -### Plataformas soportadas - -* Android -* BlackBerry 10 -* iOS -* Tizen -* Windows Phone 7 y 8 -* Windows 8 - -### Ejemplo rápido - - // Android: devuelve un entero de 64 bits al azar (como una cadena, otra vez!) - // el entero es generado en el primer arranque del dispositivo - // - // BlackBerry: devuelve el número PIN del dispositivo - // este es un entero único de nueve dígitos (como una cadena, aunque!) - // - // iPhone: (parafraseado de la documentación de la clase UIDevice) - // devuelve una cadena de valores hash creado a partir - // de múltiples hardware identifica. - / / Está garantizado para ser único para cada dispositivo y no puede ser atado / / a la cuenta de usuario. - // Windows Phone 7: devuelve un hash de dispositivo + usuario actual, - // si el usuario no está definido, un guid generado y persistirá hasta que se desinstala la aplicación - // - // Tizen: devuelve el dispositivo IMEI (identidad de equipo móvil internacional o IMEI es un número - // único para cada teléfono móvil GSM y UMTS. - var deviceID = device.uuid; - - -### iOS chanfle - -El `uuid` en iOS no es exclusiva de un dispositivo, pero varía para cada aplicación, para cada instalación. Cambia si puedes borrar y volver a instalar la aplicación, y posiblemente también cuándo actualizar iOS, o incluso mejorar la aplicación por la versión (evidente en iOS 5.1). El `uuid` no es un valor confiable. - -### Windows Phone 7 y 8 rarezas - -El `uuid` para Windows Phone 7 requiere el permiso `ID_CAP_IDENTITY_DEVICE`. Microsoft pronto probablemente desaprueban esta propiedad. Si la capacidad no está disponible, la aplicación genera un guid persistente que se mantiene durante la duración de la instalación de la aplicación en el dispositivo. - -## device.version - -Obtener la versión del sistema operativo. - - var string = device.version; - - -### Plataformas soportadas - -* Android 2.1 + -* BlackBerry 10 -* Explorador -* iOS -* Tizen -* Windows Phone 7 y 8 -* Windows 8 - -### Ejemplo rápido - - // Android: Froyo OS would return "2.2" - // Eclair OS would return "2.1", "2.0.1", or "2.0" - // Version can also return update level "2.1-update1" - // - // BlackBerry: Torch 9800 using OS 6.0 would return "6.0.0.600" - // - // Browser: Returns version number for the browser - // - // iPhone: iOS 3.2 returns "3.2" - // - // Windows Phone 7: returns current OS version number, ex. el Mango se vuelve 7.10.7720 - // Tizen: devuelve "TIZEN_20120425_2" - var deviceVersion = device.version; diff --git a/plugins/cordova-plugin-device/doc/fr/README.md b/plugins/cordova-plugin-device/doc/fr/README.md deleted file mode 100644 index 4101fd9..0000000 --- a/plugins/cordova-plugin-device/doc/fr/README.md +++ /dev/null @@ -1,215 +0,0 @@ - - -# cordova-plugin-device - -[![Build Status](https://travis-ci.org/apache/cordova-plugin-device.svg?branch=master)](https://travis-ci.org/apache/cordova-plugin-device) - -Ce plugin définit un global `device` objet qui décrit le matériel et les logiciels de l'appareil. Bien que l'objet est 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(device.cordova); - } - - -## Installation - - cordova plugin add cordova-plugin-device - - -## Propriétés - - * device.cordova - * device.model - * device.platform - * device.uuid - * device.version - -## device.cordova - -Retourne la version de Cordova en cours d'exécution sur l'appareil. - -### Plates-formes supportées - - * Amazon Fire OS - * Android - * BlackBerry 10 - * Navigateur - * Firefox OS - * iOS - * Paciarelli - * Windows Phone 7 et 8 - * Windows 8 - -## device.model - -L'objet `device.model` retourne le nom du modèle de l'appareil/produit. Cette valeur est définie par le fabricant du périphérique et peut varier entre les différentes versions d'un même produit. - -### Plates-formes supportées - - * Android - * BlackBerry 10 - * Navigateur - * iOS - * Paciarelli - * Windows Phone 7 et 8 - * Windows 8 - -### Exemple court - - // Android: Nexus One returns "Passion" (Nexus One code name) - // Motorola Droid returns "voles" - // BlackBerry: Torch 9800 returns "9800" - // Browser: Google Chrome returns "Chrome" - // Safari returns "Safari" - // iOS: for the iPad Mini, returns iPad2,5; iPhone 5 is iPhone 5,1. Voir http://theiphonewiki.com/wiki/index.php?title=Models - // - var model = device.model; - - -### Quirks Android - - * Retourne le [nom du produit](http://developer.android.com/reference/android/os/Build.html#PRODUCT) au lieu du [nom du modèle](http://developer.android.com/reference/android/os/Build.html#MODEL), ce qui équivaut souvent au nom de code de production. Par exemple, `Passion` pour le Nexus One et `voles` pour le Motorola Droid. - -### Bizarreries de paciarelli - - * Retourne le modèle du dispositif, assigné par le vendeur, par exemple `TIZEN` - -### Notes au sujet de Windows Phone 7 et 8 - - * Retourne le modèle de l'appareil spécifié par le fabricant. Par exemple `SGH-i917` pour le Samsung Focus. - -## device.platform - -Obtenir le nom de système d'exploitation de l'appareil. - - var string = device.platform; - - -### Plates-formes supportées - - * Android - * BlackBerry 10 - * Browser4 - * Firefox OS - * iOS - * Paciarelli - * Windows Phone 7 et 8 - * Windows 8 - -### Exemple court - - // Depending on the device, a few examples are: - // - "Android" - // - "BlackBerry 10" - // - Browser: returns "MacIntel" on Mac - // returns "Win32" on Windows - // - "iOS" - // - "WinCE" - // - "Tizen" - var devicePlatform = device.platform; - - -### Windows Phone 7 Quirks - -Appareils Windows Phone 7 rapport de la plate-forme comme`WinCE`. - -### Notes au sujet de Windows Phone 8 - -Appareils Windows Phone 8 rapport de la plate-forme comme`Win32NT`. - -## device.uuid - -Obtenir Universally Unique Identifier de l'appareil ([UUID](http://en.wikipedia.org/wiki/Universally_Unique_Identifier)). - - var string = device.uuid; - - -### Description - -Les détails de comment un UUID généré sont déterminées par le fabricant du périphérique et sont spécifiques à la plate-forme ou le modèle de l'appareil. - -### Plates-formes supportées - - * Android - * BlackBerry 10 - * iOS - * Paciarelli - * Windows Phone 7 et 8 - * Windows 8 - -### Exemple court - - // Android : retourne un nombre entier 64-bit aléatoire (sous la forme d'une chaîne de caractères, encore !) - // Ce nombre entier est généré lors du premier démarrage de l'appareil - // - // BlackBerry : retourne le numéro PIN de l'appareil - // Il s'agit d'un nombre entier unique à neuf chiffres (sous la forme d'une chaîne de caractères cependant !) - // - // iPhone : (copié depuis la documentation de la classe UIDevice) - // Retourne une chaîne de caractères générée à partir de plusieurs caractéristiques matérielles. - / / Il est garanti pour être unique pour chaque appareil et ne peut pas être lié / / pour le compte d'utilisateur. - // Windows Phone 7 : retourne un hashage généré à partir de appareil+utilisateur actuel, - // si aucun utilisateur n'est défini, un guid est généré persistera jusqu'à ce que l'application soit désinstallée - // Tizen : retourne le numéro IMEI (International Mobile Equipment Identity) de l'appareil, ce numéro est - // unique pour chaque téléphone GSM et UMTS. - var deviceID = device.uuid; - - -### Spécificités iOS - -Le `uuid` sur iOS n'est pas propre à un périphérique, mais varie pour chaque application, pour chaque installation. Elle change si vous supprimez, puis réinstallez l'application, et éventuellement aussi quand vous mettre à jour d'iOS, ou même mettre à jour le soft par version (apparent dans iOS 5.1). Le `uuid` n'est pas une valeur fiable. - -### Notes au sujet de Windows Phone 7 et 8 - -Le `uuid` pour Windows Phone 7 requiert l'autorisation `ID_CAP_IDENTITY_DEVICE` . Microsoft va probablement bientôt obsolète de cette propriété. Si la capacité n'est pas disponible, l'application génère un guid persistant qui est maintenu pendant toute la durée de l'installation de l'application sur le périphérique. - -## device.version - -Téléchargez la version de système d'exploitation. - - var string = device.version; - - -### Plates-formes supportées - - * Android 2.1+ - * BlackBerry 10 - * Navigateur - * iOS - * Paciarelli - * Windows Phone 7 et 8 - * Windows 8 - -### Exemple court - - // Android: Froyo OS would return "2.2" - // Eclair OS would return "2.1", "2.0.1", or "2.0" - // Version can also return update level "2.1-update1" - // - // BlackBerry: Torch 9800 using OS 6.0 would return "6.0.0.600" - // - // Browser: Returns version number for the browser - // - // iPhone: iOS 3.2 returns "3.2" - // - // Windows Phone 7: returns current OS version number, ex. on Mango returns 7.10.7720 - // Tizen: returns "TIZEN_20120425_2" - var deviceVersion = device.version; \ No newline at end of file diff --git a/plugins/cordova-plugin-device/doc/fr/index.md b/plugins/cordova-plugin-device/doc/fr/index.md deleted file mode 100644 index 163e498..0000000 --- a/plugins/cordova-plugin-device/doc/fr/index.md +++ /dev/null @@ -1,218 +0,0 @@ - - -# cordova-plugin-device - -Ce plugin définit un global `device` objet qui décrit le matériel et les logiciels de l'appareil. Bien que l'objet est 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(device.cordova); - } - - -## Installation - - cordova plugin add cordova-plugin-device - - -## Propriétés - -* device.cordova -* device.model -* device.platform -* device.uuid -* device.version - -## device.cordova - -Retourne la version de Cordova en cours d'exécution sur l'appareil. - -### Plates-formes prises en charge - -* Amazon Fire OS -* Android -* BlackBerry 10 -* Navigateur -* Firefox OS -* iOS -* Paciarelli -* Windows Phone 7 et 8 -* Windows 8 - -## device.model - -L'objet `device.model` retourne le nom du modèle de l'appareil/produit. Cette valeur est définie par le fabricant du périphérique et peut varier entre les différentes versions d'un même produit. - -### Plates-formes prises en charge - -* Android -* BlackBerry 10 -* Navigateur -* iOS -* Paciarelli -* Windows Phone 7 et 8 -* Windows 8 - -### Petit exemple - - // Android: Nexus One returns "Passion" (Nexus One code name) - // Motorola Droid returns "voles" - // BlackBerry: Torch 9800 returns "9800" - // Browser: Google Chrome returns "Chrome" - // Safari returns "Safari" - // iOS: for the iPad Mini, returns iPad2,5; iPhone 5 is iPhone 5,1. Voir http://theiphonewiki.com/wiki/index.php?title=Models - // - var model = device.model; - - -### Quirks Android - -* Retourne le [nom du produit][1] au lieu du [nom du modèle][2], ce qui équivaut souvent au nom de code de production. Par exemple, `Passion` pour le Nexus One et `voles` pour le Motorola Droid. - - [1]: http://developer.android.com/reference/android/os/Build.html#PRODUCT - [2]: http://developer.android.com/reference/android/os/Build.html#MODEL - -### Bizarreries de paciarelli - -* Retourne le modèle du dispositif, assigné par le vendeur, par exemple `TIZEN` - -### Windows Phone 7 et 8 Quirks - -* Retourne le modèle de l'appareil spécifié par le fabricant. Par exemple `SGH-i917` pour le Samsung Focus. - -## device.platform - -Obtenir le nom de système d'exploitation de l'appareil. - - var string = device.platform; - - -### Plates-formes prises en charge - -* Android -* BlackBerry 10 -* Browser4 -* Firefox OS -* iOS -* Paciarelli -* Windows Phone 7 et 8 -* Windows 8 - -### Petit exemple - - // Depending on the device, a few examples are: - // - "Android" - // - "BlackBerry 10" - // - Browser: returns "MacIntel" on Mac - // returns "Win32" on Windows - // - "iOS" - // - "WinCE" - // - "Tizen" - var devicePlatform = device.platform; - - -### Windows Phone 7 Quirks - -Appareils Windows Phone 7 rapport de la plate-forme comme`WinCE`. - -### Notes au sujet de Windows Phone 8 - -Appareils Windows Phone 8 rapport de la plate-forme comme`Win32NT`. - -## device.uuid - -Obtenir Universally Unique Identifier de l'appareil ([UUID][3]). - - [3]: http://en.wikipedia.org/wiki/Universally_Unique_Identifier - - var string = device.uuid; - - -### Description - -Les détails de comment un UUID généré sont déterminées par le fabricant du périphérique et sont spécifiques à la plate-forme ou le modèle de l'appareil. - -### Plates-formes prises en charge - -* Android -* BlackBerry 10 -* iOS -* Paciarelli -* Windows Phone 7 et 8 -* Windows 8 - -### Petit exemple - - // Android : retourne un nombre entier 64-bit aléatoire (sous la forme d'une chaîne de caractères, encore !) - // Ce nombre entier est généré lors du premier démarrage de l'appareil - // - // BlackBerry : retourne le numéro PIN de l'appareil - // Il s'agit d'un nombre entier unique à neuf chiffres (sous la forme d'une chaîne de caractères cependant !) - // - // iPhone : (copié depuis la documentation de la classe UIDevice) - // Retourne une chaîne de caractères générée à partir de plusieurs caractéristiques matérielles. - / / Il est garanti pour être unique pour chaque appareil et ne peut pas être lié / / pour le compte d'utilisateur. - // Windows Phone 7 : retourne un hashage généré à partir de appareil+utilisateur actuel, - // si aucun utilisateur n'est défini, un guid est généré persistera jusqu'à ce que l'application soit désinstallée - // Tizen : retourne le numéro IMEI (International Mobile Equipment Identity) de l'appareil, ce numéro est - // unique pour chaque téléphone GSM et UMTS. - var deviceID = device.uuid; - - -### Spécificités iOS - -Le `uuid` sur iOS n'est pas propre à un périphérique, mais varie pour chaque application, pour chaque installation. Elle change si vous supprimez, puis réinstallez l'application, et éventuellement aussi quand vous mettre à jour d'iOS, ou même mettre à jour le soft par version (apparent dans iOS 5.1). Le `uuid` n'est pas une valeur fiable. - -### Windows Phone 7 et 8 Quirks - -Le `uuid` pour Windows Phone 7 requiert l'autorisation `ID_CAP_IDENTITY_DEVICE` . Microsoft va probablement bientôt obsolète de cette propriété. Si la capacité n'est pas disponible, l'application génère un guid persistant qui est maintenu pendant toute la durée de l'installation de l'application sur le périphérique. - -## device.version - -Téléchargez la version de système d'exploitation. - - var string = device.version; - - -### Plates-formes prises en charge - -* Android 2.1+ -* BlackBerry 10 -* Navigateur -* iOS -* Paciarelli -* Windows Phone 7 et 8 -* Windows 8 - -### Petit exemple - - // Android: Froyo OS would return "2.2" - // Eclair OS would return "2.1", "2.0.1", or "2.0" - // Version can also return update level "2.1-update1" - // - // BlackBerry: Torch 9800 using OS 6.0 would return "6.0.0.600" - // - // Browser: Returns version number for the browser - // - // iPhone: iOS 3.2 returns "3.2" - // - // Windows Phone 7: returns current OS version number, ex. on Mango returns 7.10.7720 - // Tizen: returns "TIZEN_20120425_2" - var deviceVersion = device.version; diff --git a/plugins/cordova-plugin-device/doc/it/README.md b/plugins/cordova-plugin-device/doc/it/README.md deleted file mode 100644 index 7974962..0000000 --- a/plugins/cordova-plugin-device/doc/it/README.md +++ /dev/null @@ -1,203 +0,0 @@ - - -# cordova-plugin-device - -[![Build Status](https://travis-ci.org/apache/cordova-plugin-device.svg?branch=master)](https://travis-ci.org/apache/cordova-plugin-device) - -Questo plugin definisce un global `device` oggetto che descrive il dispositivo hardware e software. Sebbene l'oggetto sia in ambito globale, non è disponibile fino a dopo il `deviceready` evento. - - document.addEventListener("deviceready", onDeviceReady, false); - function onDeviceReady() { - console.log(device.cordova); - } - - -## Installazione - - cordova plugin add cordova-plugin-device - - -## Proprietà - - * device.cordova - * device.model - * device.platform - * device.uuid - * device.version - -## device.cordova - -Ottenere la versione di Cordova in esecuzione nel dispositivo. - -### Piattaforme supportate - - * Amazon fuoco OS - * Android - * BlackBerry 10 - * Browser - * Firefox OS - * iOS - * Tizen - * Windows Phone 7 e 8 - * Windows 8 - -## device.model - -Il `device.model` restituisce il nome del modello del dispositivo o del prodotto. Il valore viene impostato dal produttore del dispositivo e può essere differente tra le versioni dello stesso prodotto. - -### Piattaforme supportate - - * Android - * BlackBerry 10 - * Browser - * iOS - * Tizen - * Windows Phone 7 e 8 - * Windows 8 - -### Esempio rapido - - // Android: Nexus One returns "Passion" (Nexus One code name) - // Motorola Droid returns "voles" - // BlackBerry: Torch 9800 returns "9800" - // Browser: Google Chrome returns "Chrome" - // Safari returns "Safari" - // iOS: for the iPad Mini, returns iPad2,5; iPhone 5 is iPhone 5,1. Vedi http://theiphonewiki.com/wiki/index.php?title=Models / / modello var = device.model; - - -### Stranezze Android - - * Ottiene il [nome del prodotto](http://developer.android.com/reference/android/os/Build.html#PRODUCT) anziché il [nome del modello](http://developer.android.com/reference/android/os/Build.html#MODEL), che è spesso il nome di codice di produzione. Ad esempio, restituisce il Nexus One `Passion` , e Motorola Droid restituisce`voles`. - -### Tizen stranezze - - * Restituisce il modello di dispositivo assegnato dal fornitore, ad esempio,`TIZEN` - -### Windows Phone 7 e 8 stranezze - - * Restituisce il modello di dispositivo specificato dal produttore. Ad esempio, restituisce il Samsung Focus`SGH-i917`. - -## device.platform - -Ottenere il nome del sistema operativo del dispositivo. - - var string = device.platform; - - -### Piattaforme supportate - - * Android - * BlackBerry 10 - * Browser4 - * Firefox OS - * iOS - * Tizen - * Windows Phone 7 e 8 - * Windows 8 - -### Esempio rapido - - // Depending on the device, a few examples are: - // - "Android" - // - "BlackBerry 10" - // - Browser: returns "MacIntel" on Mac - // returns "Win32" on Windows - // - "iOS" - // - "WinCE" - // - "Tizen" - var devicePlatform = device.platform; - - -### Windows Phone 7 capricci - -Windows Phone 7 dispositivi segnalano la piattaforma come`WinCE`. - -### Windows Phone 8 stranezze - -Dispositivi Windows Phone 8 segnalano la piattaforma come`Win32NT`. - -## device.uuid - -Ottenere identificatore del dispositivo univoco universale ([UUID](http://en.wikipedia.org/wiki/Universally_Unique_Identifier)). - - var string = device.uuid; - - -### Descrizione - -I dettagli di come viene generato un UUID sono determinati dal produttore del dispositivo e sono specifici per la piattaforma o il modello del dispositivo. - -### Piattaforme supportate - - * Android - * BlackBerry 10 - * iOS - * Tizen - * Windows Phone 7 e 8 - * Windows 8 - -### Esempio rapido - - / / Android: restituisce un intero casuale di 64 bit (come stringa, ancora una volta!) / / il numero intero è generato al primo avvio del dispositivo / / / / BlackBerry: restituisce il numero PIN del dispositivo / / questo è un valore integer univoco a nove cifre (come stringa, benchè!) / / / / iPhone: (parafrasato dalla documentazione della classe UIDevice) / / restituisce una stringa di valori hash creata dall'hardware più identifica. - / / È garantito per essere unica per ogni dispositivo e non può essere legato / / per l'account utente. - / / Windows Phone 7: restituisce un hash dell'utente corrente, + dispositivo / / se l'utente non è definito, un guid generato e persisterà fino a quando l'applicazione viene disinstallata / / Tizen: restituisce il dispositivo IMEI (International Mobile Equipment Identity o IMEI è un numero / / unico per ogni cellulare GSM e UMTS. - var deviceID = device.uuid; - - -### iOS Quirk - -Il `uuid` su iOS non è univoco per un dispositivo, ma varia per ogni applicazione, per ogni installazione. Cambia se si elimina e re-installare l'app, e possibilmente anche quando aggiornare iOS o anche aggiornare l'app per ogni versione (apparente in iOS 5.1). Il `uuid` non è un valore affidabile. - -### Windows Phone 7 e 8 stranezze - -Il `uuid` per Windows Phone 7 richiede l'autorizzazione `ID_CAP_IDENTITY_DEVICE` . Microsoft probabilmente sarà presto deprecare questa proprietà. Se la funzionalità non è disponibile, l'applicazione genera un guid persistente che viene mantenuto per la durata dell'installazione dell'applicazione sul dispositivo. - -## device.version - -Ottenere la versione del sistema operativo. - - var string = device.version; - - -### Piattaforme supportate - - * Android 2.1 + - * BlackBerry 10 - * Browser - * iOS - * Tizen - * Windows Phone 7 e 8 - * Windows 8 - -### Esempio rapido - - // Android: Froyo OS would return "2.2" - // Eclair OS would return "2.1", "2.0.1", or "2.0" - // Version can also return update level "2.1-update1" - // - // BlackBerry: Torch 9800 using OS 6.0 would return "6.0.0.600" - // - // Browser: Returns version number for the browser - // - // iPhone: iOS 3.2 returns "3.2" - // - // Windows Phone 7: returns current OS version number, ex. on Mango returns 7.10.7720 - // Tizen: returns "TIZEN_20120425_2" - var deviceVersion = device.version; \ No newline at end of file diff --git a/plugins/cordova-plugin-device/doc/it/index.md b/plugins/cordova-plugin-device/doc/it/index.md deleted file mode 100644 index 98c6200..0000000 --- a/plugins/cordova-plugin-device/doc/it/index.md +++ /dev/null @@ -1,206 +0,0 @@ - - -# cordova-plugin-device - -Questo plugin definisce un global `device` oggetto che descrive il dispositivo hardware e software. Sebbene l'oggetto sia in ambito globale, non è disponibile fino a dopo il `deviceready` evento. - - document.addEventListener("deviceready", onDeviceReady, false); - function onDeviceReady() { - console.log(device.cordova); - } - - -## Installazione - - cordova plugin add cordova-plugin-device - - -## Proprietà - -* device.cordova -* device.model -* device.platform -* device.uuid -* device.version - -## device.cordova - -Ottenere la versione di Cordova in esecuzione nel dispositivo. - -### Piattaforme supportate - -* Amazon fuoco OS -* Android -* BlackBerry 10 -* Browser -* Firefox OS -* iOS -* Tizen -* Windows Phone 7 e 8 -* Windows 8 - -## device.model - -Il `device.model` restituisce il nome del modello del dispositivo o del prodotto. Il valore viene impostato dal produttore del dispositivo e può essere differente tra le versioni dello stesso prodotto. - -### Piattaforme supportate - -* Android -* BlackBerry 10 -* Browser -* iOS -* Tizen -* Windows Phone 7 e 8 -* Windows 8 - -### Esempio rapido - - // Android: Nexus One returns "Passion" (Nexus One code name) - // Motorola Droid returns "voles" - // BlackBerry: Torch 9800 returns "9800" - // Browser: Google Chrome returns "Chrome" - // Safari returns "Safari" - // iOS: for the iPad Mini, returns iPad2,5; iPhone 5 is iPhone 5,1. Vedi http://theiphonewiki.com/wiki/index.php?title=Models / / modello var = device.model; - - -### Stranezze Android - -* Ottiene il [nome del prodotto][1] anziché il [nome del modello][2], che è spesso il nome di codice di produzione. Ad esempio, restituisce il Nexus One `Passion` , e Motorola Droid restituisce`voles`. - - [1]: http://developer.android.com/reference/android/os/Build.html#PRODUCT - [2]: http://developer.android.com/reference/android/os/Build.html#MODEL - -### Tizen stranezze - -* Restituisce il modello di dispositivo assegnato dal fornitore, ad esempio,`TIZEN` - -### Windows Phone 7 e 8 stranezze - -* Restituisce il modello di dispositivo specificato dal produttore. Ad esempio, restituisce il Samsung Focus`SGH-i917`. - -## device.platform - -Ottenere il nome del sistema operativo del dispositivo. - - var string = device.platform; - - -### Piattaforme supportate - -* Android -* BlackBerry 10 -* Browser4 -* Firefox OS -* iOS -* Tizen -* Windows Phone 7 e 8 -* Windows 8 - -### Esempio rapido - - // Depending on the device, a few examples are: - // - "Android" - // - "BlackBerry 10" - // - Browser: returns "MacIntel" on Mac - // returns "Win32" on Windows - // - "iOS" - // - "WinCE" - // - "Tizen" - var devicePlatform = device.platform; - - -### Windows Phone 7 capricci - -Windows Phone 7 dispositivi segnalano la piattaforma come`WinCE`. - -### Windows Phone 8 stranezze - -Dispositivi Windows Phone 8 segnalano la piattaforma come`Win32NT`. - -## device.uuid - -Ottenere identificatore del dispositivo univoco universale ([UUID][3]). - - [3]: http://en.wikipedia.org/wiki/Universally_Unique_Identifier - - var string = device.uuid; - - -### Descrizione - -I dettagli di come viene generato un UUID sono determinati dal produttore del dispositivo e sono specifici per la piattaforma o il modello del dispositivo. - -### Piattaforme supportate - -* Android -* BlackBerry 10 -* iOS -* Tizen -* Windows Phone 7 e 8 -* Windows 8 - -### Esempio rapido - - / / Android: restituisce un intero casuale di 64 bit (come stringa, ancora una volta!) / / il numero intero è generato al primo avvio del dispositivo / / / / BlackBerry: restituisce il numero PIN del dispositivo / / questo è un valore integer univoco a nove cifre (come stringa, benchè!) / / / / iPhone: (parafrasato dalla documentazione della classe UIDevice) / / restituisce una stringa di valori hash creata dall'hardware più identifica. - / / È garantito per essere unica per ogni dispositivo e non può essere legato / / per l'account utente. - / / Windows Phone 7: restituisce un hash dell'utente corrente, + dispositivo / / se l'utente non è definito, un guid generato e persisterà fino a quando l'applicazione viene disinstallata / / Tizen: restituisce il dispositivo IMEI (International Mobile Equipment Identity o IMEI è un numero / / unico per ogni cellulare GSM e UMTS. - var deviceID = device.uuid; - - -### iOS Quirk - -Il `uuid` su iOS non è univoco per un dispositivo, ma varia per ogni applicazione, per ogni installazione. Cambia se si elimina e re-installare l'app, e possibilmente anche quando aggiornare iOS o anche aggiornare l'app per ogni versione (apparente in iOS 5.1). Il `uuid` non è un valore affidabile. - -### Windows Phone 7 e 8 stranezze - -Il `uuid` per Windows Phone 7 richiede l'autorizzazione `ID_CAP_IDENTITY_DEVICE` . Microsoft probabilmente sarà presto deprecare questa proprietà. Se la funzionalità non è disponibile, l'applicazione genera un guid persistente che viene mantenuto per la durata dell'installazione dell'applicazione sul dispositivo. - -## device.version - -Ottenere la versione del sistema operativo. - - var string = device.version; - - -### Piattaforme supportate - -* Android 2.1 + -* BlackBerry 10 -* Browser -* iOS -* Tizen -* Windows Phone 7 e 8 -* Windows 8 - -### Esempio rapido - - // Android: Froyo OS would return "2.2" - // Eclair OS would return "2.1", "2.0.1", or "2.0" - // Version can also return update level "2.1-update1" - // - // BlackBerry: Torch 9800 using OS 6.0 would return "6.0.0.600" - // - // Browser: Returns version number for the browser - // - // iPhone: iOS 3.2 returns "3.2" - // - // Windows Phone 7: returns current OS version number, ex. on Mango returns 7.10.7720 - // Tizen: returns "TIZEN_20120425_2" - var deviceVersion = device.version; diff --git a/plugins/cordova-plugin-device/doc/ja/README.md b/plugins/cordova-plugin-device/doc/ja/README.md deleted file mode 100644 index 5a345f8..0000000 --- a/plugins/cordova-plugin-device/doc/ja/README.md +++ /dev/null @@ -1,203 +0,0 @@ - - -# cordova-plugin-device - -[![Build Status](https://travis-ci.org/apache/cordova-plugin-device.svg?branch=master)](https://travis-ci.org/apache/cordova-plugin-device) - -ã“ã®ãƒ—ラグインをグローãƒãƒ«å®šç¾©ã—ã¾ã™ `device` オブジェクトã¯ã€ãƒ‡ãƒã‚¤ã‚¹ã®ãƒãƒ¼ãƒ‰ã‚¦ã‚§ã‚¢ã¨ã‚½ãƒ•ãƒˆã‚¦ã‚§ã‚¢ã«ã¤ã„ã¦èª¬æ˜Žã—ã¾ã™ã€‚ ãã‚Œã¯å¾Œã¾ã§åˆ©ç”¨å¯èƒ½ãªã‚ªãƒ–ジェクトãŒã‚°ãƒ­ãƒ¼ãƒãƒ« スコープã§ã¯ã€ `deviceready` イベント。 - - document.addEventListener("deviceready", onDeviceReady, false); - function onDeviceReady() { - console.log(device.cordova); - } - - -## インストール - - cordova plugin add cordova-plugin-device - - -## プロパティ - - * device.cordova - * device.model - * device.platform - * device.uuid - * device.version - -## device.cordova - -デãƒã‚¤ã‚¹ã§å®Ÿè¡Œã•ã‚Œã¦ã„るコルドãƒã®ãƒãƒ¼ã‚¸ãƒ§ãƒ³ã‚’å–å¾—ã—ã¾ã™ã€‚ - -### サãƒãƒ¼ãƒˆã•ã‚Œã¦ã„るプラットフォーム - - * ã‚¢ãƒžã‚¾ãƒ³ç« OS - * アンドロイド - * ブラックベリー 10 - * ブラウザー - * Firefox ã® OS - * iOS - * Tizen - * Windows Phone 7 㨠8 - * Windows 8 - -## device.model - -`device.model`ã€ãƒ‡ãƒã‚¤ã‚¹ã®ãƒ¢ãƒ‡ãƒ«ã¾ãŸã¯è£½å“ã®åå‰ã‚’è¿”ã—ã¾ã™ã€‚値ã¯ã€ãƒ‡ãƒã‚¤ã‚¹ã®è£½é€ å…ƒã«ã‚ˆã£ã¦è¨­å®šã•ã‚Œã€åŒã˜è£½å“ã®ãƒãƒ¼ã‚¸ãƒ§ãƒ³é–“ã§ç•°ãªã‚‹å¯èƒ½æ€§ãŒã‚ã‚Šã¾ã™ã€‚ - -### サãƒãƒ¼ãƒˆã•ã‚Œã¦ã„るプラットフォーム - - * アンドロイド - * ブラックベリー 10 - * ブラウザー - * iOS - * Tizen - * Windows Phone 7 㨠8 - * Windows 8 - -### ç°¡å˜ãªä¾‹ - - // Android: Nexus One returns "Passion" (Nexus One code name) - // Motorola Droid returns "voles" - // BlackBerry: Torch 9800 returns "9800" - // Browser: Google Chrome returns "Chrome" - // Safari returns "Safari" - // iOS: for the iPad Mini, returns iPad2,5; iPhone 5 is iPhone 5,1. Http://theiphonewiki.com/wiki/index.php?title=Models ã‚’å‚ç…§ã—ã¦ãã ã•ã„//var モデル = device.model; - - -### Android ã®ç™– - - * 生産コードåã¯[モデルå](http://developer.android.com/reference/android/os/Build.html#MODEL)ã®ä»£ã‚ã‚Šã«[製å“å](http://developer.android.com/reference/android/os/Build.html#PRODUCT)ã‚’å–å¾—ã—ã¾ã™ã€‚ ãŸã¨ãˆã°ã€ãƒã‚¯ã‚µã‚¹ 1 ã¤ã‚’è¿”ã—ã¾ã™ `Passion` ã€Motorola ã®ãƒ‰ãƒ­ã‚¤ãƒ‰ã‚’è¿”ã—ã¾ã™`voles`. - -### Tizen ã®ç™– - - * ãŸã¨ãˆã°ã€ãƒ™ãƒ³ãƒ€ãƒ¼ã«ã‚ˆã£ã¦å‰²ã‚Šå½“ã¦ã‚‰ã‚Œã¦ã„るデãƒã‚¤ã‚¹ã®ãƒ¢ãƒ‡ãƒ«ã‚’è¿”ã—ã¾ã™`TIZEN` - -### Windows Phone 7 㨠8 ç™– - - * 製造元ã«ã‚ˆã£ã¦æŒ‡å®šã•ã‚ŒãŸãƒ‡ãƒã‚¤ã‚¹ã®ãƒ¢ãƒ‡ãƒ«ã‚’è¿”ã—ã¾ã™ã€‚ãŸã¨ãˆã°ã€ä¸‰æ˜Ÿãƒ•ã‚©ãƒ¼ã‚«ã‚¹ã‚’è¿”ã—ã¾ã™`SGH-i917`. - -## device.platform - -デãƒã‚¤ã‚¹ã®ã‚ªãƒšãƒ¬ãƒ¼ãƒ†ã‚£ãƒ³ã‚° システムåã‚’å–å¾—ã—ã¾ã™ã€‚ - - var string = device.platform; - - -### サãƒãƒ¼ãƒˆã•ã‚Œã¦ã„るプラットフォーム - - * アンドロイド - * ブラックベリー 10 - * Browser4 - * Firefox ã® OS - * iOS - * Tizen - * Windows Phone 7 㨠8 - * Windows 8 - -### ç°¡å˜ãªä¾‹ - - // Depending on the device, a few examples are: - // - "Android" - // - "BlackBerry 10" - // - Browser: returns "MacIntel" on Mac - // returns "Win32" on Windows - // - "iOS" - // - "WinCE" - // - "Tizen" - var devicePlatform = device.platform; - - -### Windows Phone 7 ã®ç™– - -Windows Phone 7 デãƒã‚¤ã‚¹ã¨ãƒ—ラットフォームを報告ã—ã¾ã™ã€‚`WinCE`. - -### Windows Phone 8 ç™– - -Windows Phone 8 デãƒã‚¤ã‚¹ã¨ãƒ—ラットフォームを報告ã—ã¾ã™ã€‚`Win32NT`. - -## device.uuid - -デãƒã‚¤ã‚¹ã®ãƒ¦ãƒ‹ãƒãƒ¼ã‚µãƒ« ・ ãƒ¦ãƒ‹ãƒ¼ã‚¯è­˜åˆ¥å­ ([UUID](http://en.wikipedia.org/wiki/Universally_Unique_Identifier)ã‚’å–å¾—ã—ã¾ã™ã€‚). - - var string = device.uuid; - - -### 解説 - -UUID を生æˆã™ã‚‹æ–¹æ³•ã®è©³ç´°ã¯ã€ãƒ‡ãƒã‚¤ã‚¹ã®è£½é€ å…ƒã«ã‚ˆã£ã¦æ±ºå®šã•ã‚Œã€ãƒ‡ãƒã‚¤ã‚¹ã®ãƒ—ラットフォームやモデルã«å›ºæœ‰ã§ã™ã€‚ - -### サãƒãƒ¼ãƒˆã•ã‚Œã¦ã„るプラットフォーム - - * アンドロイド - * ブラックベリー 10 - * iOS - * Tizen - * Windows Phone 7 㨠8 - * Windows 8 - -### ç°¡å˜ãªä¾‹ - - //アンドロイド: ランダム㪠64 ビットã®æ•´æ•° (を文字列ã¨ã—ã¦è¿”ã—ã¾ã™ã€å†ã³ ï¼ï¼‰/デãƒã‚¤ã‚¹ã®æœ€åˆã®èµ·å‹•æ™‚ã«ç”Ÿæˆã•ã‚Œã‚‹æ•´æ•°/////ブラックベリー: デãƒã‚¤ã‚¹ã®ãƒ”ン番å·ã‚’è¿”ã—ã¾ã™//ã“れ㯠9 æ¡ã®ä¸€æ„ãªæ•´æ•° (を文字列ã¨ã—ã¦ã‚‚ ï¼)////iPhone: (UIDevice クラスã®ãƒ‰ã‚­ãƒ¥ãƒ¡ãƒ³ãƒˆã‹ã‚‰è¨€ã„æ›ãˆï¼‰//識別複数ã®ãƒãƒ¼ãƒ‰ã‚¦ã‚§ã‚¢ã‹ã‚‰ä½œæˆã•ã‚ŒãŸãƒãƒƒã‚·ãƒ¥å€¤ã®æ–‡å­—列を返ã—ã¾ã™ã€‚。 - //ãã‚Œã¯ã™ã¹ã¦ã®ãƒ‡ãƒã‚¤ã‚¹ã«å¯¾ã—ã¦ä¸€æ„ã§ã‚ã‚‹ã“ã¨ãŒä¿è¨¼ã•ã‚Œã€æŽ¥ç¶šã™ã‚‹ã“ã¨ã¯ã§ãã¾ã›ã‚“//ユーザー アカウント。 - //Windows Phone 7: デãƒã‚¤ã‚¹ + ç¾åœ¨ã®ãƒ¦ãƒ¼ã‚¶ãƒ¼ã®ãƒãƒƒã‚·ãƒ¥ã‚’è¿”ã—ã¾ã™//ユーザーãŒå®šç¾©ã•ã‚Œã¦ã„ãªã„å ´åˆ guid ãŒç”Ÿæˆã•ã‚Œã€ã‚¢ãƒ—リãŒã‚¢ãƒ³ã‚¤ãƒ³ã‚¹ãƒˆãƒ¼ãƒ«ã•ã‚Œã‚‹ã¾ã§ä¿æŒã•ã‚Œã¾ã™//Tizen: デãƒã‚¤ã‚¹ã® IMEI ã‚’è¿”ã—ã¾ã™ (国際モãƒã‚¤ãƒ«æ©Ÿå™¨ã‚¢ã‚¤ãƒ‡ãƒ³ãƒ†ã‚£ãƒ†ã‚£ã¾ãŸã¯ IMEI ã¯ç•ªå·ã§ã™//ã™ã¹ã¦ã® GSM ãŠã‚ˆã³ UMTS ã®æºå¸¯é›»è©±ã«å›ºæœ‰ã§ã™ã€‚ - var deviceID = device.uuid; - - -### iOS ã®æ°—ã¾ãã‚Œ - -`uuid`IOS ã§ã€ãƒ‡ãƒã‚¤ã‚¹ã«å›ºæœ‰ã§ã¯ãªã„インストールã”ã¨ã€ã‚¢ãƒ—リケーションã”ã¨ã«ç•°ãªã‚Šã¾ã™ã€‚ 削除ã€ã‚¢ãƒ—リをå†ã‚¤ãƒ³ã‚¹ãƒˆãƒ¼ãƒ«ã—ãŸå ´åˆã«å¤‰æ›´ã¨å¤šåˆ†ã¾ãŸã¨ãアップグレード iOS ã®, ã¾ãŸã¯ã‚‚アップグレードã™ã‚‹ã‚¢ãƒ—リ (iOS ã® 5.1 ã§æ˜Žã‚‰ã‹ã«ï¼‰ ãƒãƒ¼ã‚¸ãƒ§ãƒ³ã”ã¨ã€‚ `uuid`ã¯ä¿¡é ¼æ€§ã®é«˜ã„値ã§ã¯ã‚ã‚Šã¾ã›ã‚“。 - -### Windows Phone 7 㨠8 ç™– - -`uuid`ã®ãŸã‚ã« Windows Phone 7 ã«ã¯ã€æ¨©é™ãŒå¿…è¦ã§ã™ `ID_CAP_IDENTITY_DEVICE` 。 Microsoft ã¯ã™ãã«ã“ã®ãƒ—ロパティを廃止ã—ã¦å¯èƒ½æ€§ãŒã‚ã‚Šã¾ã™ã€‚ 機能ãŒåˆ©ç”¨ã§ããªã„å ´åˆã€ã‚¢ãƒ—リケーションã¯ãƒ‡ãƒã‚¤ã‚¹ã¸ã®ã‚¢ãƒ—リケーションã®ã‚¤ãƒ³ã‚¹ãƒˆãƒ¼ãƒ«ã®æŒç¶šæœŸé–“ã®ãŸã‚ã«ä¿æŒã•ã‚Œã¦ã„る永続的㪠guid を生æˆã—ã¾ã™ã€‚ - -## device.version - -オペレーティング システムã®ãƒãƒ¼ã‚¸ãƒ§ãƒ³ã‚’å–å¾—ã—ã¾ã™ã€‚ - - var string = device.version; - - -### サãƒãƒ¼ãƒˆã•ã‚Œã¦ã„るプラットフォーム - - * アンドロイド 2.1 + - * ブラックベリー 10 - * ブラウザー - * iOS - * Tizen - * Windows Phone 7 㨠8 - * Windows 8 - -### ç°¡å˜ãªä¾‹ - - // Android: Froyo OS would return "2.2" - // Eclair OS would return "2.1", "2.0.1", or "2.0" - // Version can also return update level "2.1-update1" - // - // BlackBerry: Torch 9800 using OS 6.0 would return "6.0.0.600" - // - // Browser: Returns version number for the browser - // - // iPhone: iOS 3.2 returns "3.2" - // - // Windows Phone 7: returns current OS version number, ex. on Mango returns 7.10.7720 - // Tizen: returns "TIZEN_20120425_2" - var deviceVersion = device.version; \ No newline at end of file diff --git a/plugins/cordova-plugin-device/doc/ja/index.md b/plugins/cordova-plugin-device/doc/ja/index.md deleted file mode 100644 index b4030fd..0000000 --- a/plugins/cordova-plugin-device/doc/ja/index.md +++ /dev/null @@ -1,206 +0,0 @@ - - -# cordova-plugin-device - -ã“ã®ãƒ—ラグインをグローãƒãƒ«å®šç¾©ã—ã¾ã™ `device` オブジェクトã¯ã€ãƒ‡ãƒã‚¤ã‚¹ã®ãƒãƒ¼ãƒ‰ã‚¦ã‚§ã‚¢ã¨ã‚½ãƒ•ãƒˆã‚¦ã‚§ã‚¢ã«ã¤ã„ã¦èª¬æ˜Žã—ã¾ã™ã€‚ ãã‚Œã¯å¾Œã¾ã§åˆ©ç”¨å¯èƒ½ãªã‚ªãƒ–ジェクトãŒã‚°ãƒ­ãƒ¼ãƒãƒ« スコープã§ã¯ã€ `deviceready` イベント。 - - document.addEventListener("deviceready", onDeviceReady, false); - function onDeviceReady() { - console.log(device.cordova); - } - - -## インストール - - cordova plugin add cordova-plugin-device - - -## プロパティ - -* device.cordova -* device.model -* device.platform -* device.uuid -* device.version - -## device.cordova - -デãƒã‚¤ã‚¹ã§å®Ÿè¡Œã•ã‚Œã¦ã„るコルドãƒã®ãƒãƒ¼ã‚¸ãƒ§ãƒ³ã‚’å–å¾—ã—ã¾ã™ã€‚ - -### サãƒãƒ¼ãƒˆã•ã‚Œã¦ã„るプラットフォーム - -* ã‚¢ãƒžã‚¾ãƒ³ç« OS -* アンドロイド -* ブラックベリー 10 -* ブラウザー -* Firefox ã® OS -* iOS -* Tizen -* Windows Phone 7 㨠8 -* Windows 8 - -## device.model - -`device.model`ã€ãƒ‡ãƒã‚¤ã‚¹ã®ãƒ¢ãƒ‡ãƒ«ã¾ãŸã¯è£½å“ã®åå‰ã‚’è¿”ã—ã¾ã™ã€‚値ã¯ã€ãƒ‡ãƒã‚¤ã‚¹ã®è£½é€ å…ƒã«ã‚ˆã£ã¦è¨­å®šã•ã‚Œã€åŒã˜è£½å“ã®ãƒãƒ¼ã‚¸ãƒ§ãƒ³é–“ã§ç•°ãªã‚‹å¯èƒ½æ€§ãŒã‚ã‚Šã¾ã™ã€‚ - -### サãƒãƒ¼ãƒˆã•ã‚Œã¦ã„るプラットフォーム - -* アンドロイド -* ブラックベリー 10 -* ブラウザー -* iOS -* Tizen -* Windows Phone 7 㨠8 -* Windows 8 - -### ç°¡å˜ãªä¾‹ - - // Android: Nexus One returns "Passion" (Nexus One code name) - // Motorola Droid returns "voles" - // BlackBerry: Torch 9800 returns "9800" - // Browser: Google Chrome returns "Chrome" - // Safari returns "Safari" - // iOS: for the iPad Mini, returns iPad2,5; iPhone 5 is iPhone 5,1. Http://theiphonewiki.com/wiki/index.php?title=Models ã‚’å‚ç…§ã—ã¦ãã ã•ã„//var モデル = device.model; - - -### Android ã®ç™– - -* 生産コードåã¯[モデルå][1]ã®ä»£ã‚ã‚Šã«[製å“å][2]ã‚’å–å¾—ã—ã¾ã™ã€‚ ãŸã¨ãˆã°ã€ãƒã‚¯ã‚µã‚¹ 1 ã¤ã‚’è¿”ã—ã¾ã™ `Passion` ã€Motorola ã®ãƒ‰ãƒ­ã‚¤ãƒ‰ã‚’è¿”ã—ã¾ã™`voles`. - - [1]: http://developer.android.com/reference/android/os/Build.html#MODEL - [2]: http://developer.android.com/reference/android/os/Build.html#PRODUCT - -### Tizen ã®ç™– - -* ãŸã¨ãˆã°ã€ãƒ™ãƒ³ãƒ€ãƒ¼ã«ã‚ˆã£ã¦å‰²ã‚Šå½“ã¦ã‚‰ã‚Œã¦ã„るデãƒã‚¤ã‚¹ã®ãƒ¢ãƒ‡ãƒ«ã‚’è¿”ã—ã¾ã™`TIZEN` - -### Windows Phone 7 㨠8 ç™– - -* 製造元ã«ã‚ˆã£ã¦æŒ‡å®šã•ã‚ŒãŸãƒ‡ãƒã‚¤ã‚¹ã®ãƒ¢ãƒ‡ãƒ«ã‚’è¿”ã—ã¾ã™ã€‚ãŸã¨ãˆã°ã€ä¸‰æ˜Ÿãƒ•ã‚©ãƒ¼ã‚«ã‚¹ã‚’è¿”ã—ã¾ã™`SGH-i917`. - -## device.platform - -デãƒã‚¤ã‚¹ã®ã‚ªãƒšãƒ¬ãƒ¼ãƒ†ã‚£ãƒ³ã‚° システムåã‚’å–å¾—ã—ã¾ã™ã€‚ - - var string = device.platform; - - -### サãƒãƒ¼ãƒˆã•ã‚Œã¦ã„るプラットフォーム - -* アンドロイド -* ブラックベリー 10 -* Browser4 -* Firefox ã® OS -* iOS -* Tizen -* Windows Phone 7 㨠8 -* Windows 8 - -### ç°¡å˜ãªä¾‹ - - // Depending on the device, a few examples are: - // - "Android" - // - "BlackBerry 10" - // - Browser: returns "MacIntel" on Mac - // returns "Win32" on Windows - // - "iOS" - // - "WinCE" - // - "Tizen" - var devicePlatform = device.platform; - - -### Windows Phone 7 ã®ç™– - -Windows Phone 7 デãƒã‚¤ã‚¹ã¨ãƒ—ラットフォームを報告ã—ã¾ã™ã€‚`WinCE`. - -### Windows Phone 8 ç™– - -Windows Phone 8 デãƒã‚¤ã‚¹ã¨ãƒ—ラットフォームを報告ã—ã¾ã™ã€‚`Win32NT`. - -## device.uuid - -デãƒã‚¤ã‚¹ã®ãƒ¦ãƒ‹ãƒãƒ¼ã‚µãƒ« ・ ãƒ¦ãƒ‹ãƒ¼ã‚¯è­˜åˆ¥å­ ([UUID][3]ã‚’å–å¾—ã—ã¾ã™ã€‚). - - [3]: http://en.wikipedia.org/wiki/Universally_Unique_Identifier - - var string = device.uuid; - - -### 説明 - -UUID を生æˆã™ã‚‹æ–¹æ³•ã®è©³ç´°ã¯ã€ãƒ‡ãƒã‚¤ã‚¹ã®è£½é€ å…ƒã«ã‚ˆã£ã¦æ±ºå®šã•ã‚Œã€ãƒ‡ãƒã‚¤ã‚¹ã®ãƒ—ラットフォームやモデルã«å›ºæœ‰ã§ã™ã€‚ - -### サãƒãƒ¼ãƒˆã•ã‚Œã¦ã„るプラットフォーム - -* アンドロイド -* ブラックベリー 10 -* iOS -* Tizen -* Windows Phone 7 㨠8 -* Windows 8 - -### ç°¡å˜ãªä¾‹ - - //アンドロイド: ランダム㪠64 ビットã®æ•´æ•° (を文字列ã¨ã—ã¦è¿”ã—ã¾ã™ã€å†ã³ ï¼ï¼‰/デãƒã‚¤ã‚¹ã®æœ€åˆã®èµ·å‹•æ™‚ã«ç”Ÿæˆã•ã‚Œã‚‹æ•´æ•°/////ブラックベリー: デãƒã‚¤ã‚¹ã®ãƒ”ン番å·ã‚’è¿”ã—ã¾ã™//ã“れ㯠9 æ¡ã®ä¸€æ„ãªæ•´æ•° (を文字列ã¨ã—ã¦ã‚‚ ï¼)////iPhone: (UIDevice クラスã®ãƒ‰ã‚­ãƒ¥ãƒ¡ãƒ³ãƒˆã‹ã‚‰è¨€ã„æ›ãˆï¼‰//識別複数ã®ãƒãƒ¼ãƒ‰ã‚¦ã‚§ã‚¢ã‹ã‚‰ä½œæˆã•ã‚ŒãŸãƒãƒƒã‚·ãƒ¥å€¤ã®æ–‡å­—列を返ã—ã¾ã™ã€‚。 - //ãã‚Œã¯ã™ã¹ã¦ã®ãƒ‡ãƒã‚¤ã‚¹ã«å¯¾ã—ã¦ä¸€æ„ã§ã‚ã‚‹ã“ã¨ãŒä¿è¨¼ã•ã‚Œã€æŽ¥ç¶šã™ã‚‹ã“ã¨ã¯ã§ãã¾ã›ã‚“//ユーザー アカウント。 - //Windows Phone 7: デãƒã‚¤ã‚¹ + ç¾åœ¨ã®ãƒ¦ãƒ¼ã‚¶ãƒ¼ã®ãƒãƒƒã‚·ãƒ¥ã‚’è¿”ã—ã¾ã™//ユーザーãŒå®šç¾©ã•ã‚Œã¦ã„ãªã„å ´åˆ guid ãŒç”Ÿæˆã•ã‚Œã€ã‚¢ãƒ—リãŒã‚¢ãƒ³ã‚¤ãƒ³ã‚¹ãƒˆãƒ¼ãƒ«ã•ã‚Œã‚‹ã¾ã§ä¿æŒã•ã‚Œã¾ã™//Tizen: デãƒã‚¤ã‚¹ã® IMEI ã‚’è¿”ã—ã¾ã™ (国際モãƒã‚¤ãƒ«æ©Ÿå™¨ã‚¢ã‚¤ãƒ‡ãƒ³ãƒ†ã‚£ãƒ†ã‚£ã¾ãŸã¯ IMEI ã¯ç•ªå·ã§ã™//ã™ã¹ã¦ã® GSM ãŠã‚ˆã³ UMTS ã®æºå¸¯é›»è©±ã«å›ºæœ‰ã§ã™ã€‚ - var deviceID = device.uuid; - - -### iOS ã®æ°—ã¾ãã‚Œ - -`uuid`IOS ã§ã€ãƒ‡ãƒã‚¤ã‚¹ã«å›ºæœ‰ã§ã¯ãªã„インストールã”ã¨ã€ã‚¢ãƒ—リケーションã”ã¨ã«ç•°ãªã‚Šã¾ã™ã€‚ 削除ã€ã‚¢ãƒ—リをå†ã‚¤ãƒ³ã‚¹ãƒˆãƒ¼ãƒ«ã—ãŸå ´åˆã«å¤‰æ›´ã¨å¤šåˆ†ã¾ãŸã¨ãアップグレード iOS ã®, ã¾ãŸã¯ã‚‚アップグレードã™ã‚‹ã‚¢ãƒ—リ (iOS ã® 5.1 ã§æ˜Žã‚‰ã‹ã«ï¼‰ ãƒãƒ¼ã‚¸ãƒ§ãƒ³ã”ã¨ã€‚ `uuid`ã¯ä¿¡é ¼æ€§ã®é«˜ã„値ã§ã¯ã‚ã‚Šã¾ã›ã‚“。 - -### Windows Phone 7 㨠8 ç™– - -`uuid`ã®ãŸã‚ã« Windows Phone 7 ã«ã¯ã€æ¨©é™ãŒå¿…è¦ã§ã™ `ID_CAP_IDENTITY_DEVICE` 。 Microsoft ã¯ã™ãã«ã“ã®ãƒ—ロパティを廃止ã—ã¦å¯èƒ½æ€§ãŒã‚ã‚Šã¾ã™ã€‚ 機能ãŒåˆ©ç”¨ã§ããªã„å ´åˆã€ã‚¢ãƒ—リケーションã¯ãƒ‡ãƒã‚¤ã‚¹ã¸ã®ã‚¢ãƒ—リケーションã®ã‚¤ãƒ³ã‚¹ãƒˆãƒ¼ãƒ«ã®æŒç¶šæœŸé–“ã®ãŸã‚ã«ä¿æŒã•ã‚Œã¦ã„る永続的㪠guid を生æˆã—ã¾ã™ã€‚ - -## device.version - -オペレーティング システムã®ãƒãƒ¼ã‚¸ãƒ§ãƒ³ã‚’å–å¾—ã—ã¾ã™ã€‚ - - var string = device.version; - - -### サãƒãƒ¼ãƒˆã•ã‚Œã¦ã„るプラットフォーム - -* アンドロイド 2.1 + -* ブラックベリー 10 -* ブラウザー -* iOS -* Tizen -* Windows Phone 7 㨠8 -* Windows 8 - -### ç°¡å˜ãªä¾‹ - - // Android: Froyo OS would return "2.2" - // Eclair OS would return "2.1", "2.0.1", or "2.0" - // Version can also return update level "2.1-update1" - // - // BlackBerry: Torch 9800 using OS 6.0 would return "6.0.0.600" - // - // Browser: Returns version number for the browser - // - // iPhone: iOS 3.2 returns "3.2" - // - // Windows Phone 7: returns current OS version number, ex. on Mango returns 7.10.7720 - // Tizen: returns "TIZEN_20120425_2" - var deviceVersion = device.version; diff --git a/plugins/cordova-plugin-device/doc/ko/README.md b/plugins/cordova-plugin-device/doc/ko/README.md deleted file mode 100644 index a818aac..0000000 --- a/plugins/cordova-plugin-device/doc/ko/README.md +++ /dev/null @@ -1,203 +0,0 @@ - - -# cordova-plugin-device - -[![Build Status](https://travis-ci.org/apache/cordova-plugin-device.svg?branch=master)](https://travis-ci.org/apache/cordova-plugin-device) - -ì´ í”ŒëŸ¬ê·¸ì¸ ì •ì˜ ì „ì—­ `device` 개체, 디바ì´ìŠ¤ì˜ 하드웨어 ë° ì†Œí”„íŠ¸ì›¨ì–´ì— ì„¤ëª… 합니다. 개체는 ì „ì—­ 범위ì—ì„œ ë¹„ë¡ ê·¸ê²ƒì€ í›„ê¹Œì§€ 사용할 수 있는 `deviceready` ì´ë²¤íŠ¸. - - document.addEventListener("deviceready", onDeviceReady, false); - function onDeviceReady() { - console.log(device.cordova); - } - - -## 설치 - - cordova plugin add cordova-plugin-device - - -## ì†ì„± - - * device.cordova - * device.model - * device.platform - * device.uuid - * device.version - -## device.cordova - -코르ë„바는 장치ì—ì„œ 실행 ì¤‘ì¸ ë²„ì „ì„ ì–»ì„. - -### ì§€ì› ë˜ëŠ” í”Œëž«í¼ - - * 아마존 화재 ìš´ì˜ ì²´ì œ - * 안 ë“œ ë¡œì´ë“œ - * 블랙베리 10 - * 브ë¼ìš°ì € - * Firefox ìš´ì˜ ì²´ì œ - * iOS - * Tizen - * Windows Phone 7ê³¼ 8 - * 윈ë„ìš° 8 - -## device.model - -`device.model`소ìžì˜ ëª¨ë¸ ë˜ëŠ” ì œí’ˆì˜ ì´ë¦„ì„ ë°˜í™˜ 합니다. ê°’ 장치 제조업체ì—ì„œ 설정 ë˜ ê³  ë™ì¼ ì œí’ˆì˜ ë²„ì „ ê°„ì— ë‹¤ë¥¼ 수 있습니다. - -### ì§€ì› ë˜ëŠ” í”Œëž«í¼ - - * 안 ë“œ ë¡œì´ë“œ - * 블랙베리 10 - * 브ë¼ìš°ì € - * iOS - * Tizen - * Windows Phone 7ê³¼ 8 - * 윈ë„ìš° 8 - -### 빠른 예제 - - // Android: Nexus One returns "Passion" (Nexus One code name) - // Motorola Droid returns "voles" - // BlackBerry: Torch 9800 returns "9800" - // Browser: Google Chrome returns "Chrome" - // Safari returns "Safari" - // iOS: for the iPad Mini, returns iPad2,5; iPhone 5 is iPhone 5,1. Http://theiphonewiki.com/wiki/index.php?title=Models 참조 / / var ëª¨ë¸ = device.model; - - -### 안 ë“œ ë¡œì´ë“œ ë‹¨ì  - - * ì–´ë–¤ì€ ì¢…ì¢… 프로ë•ì…˜ 코드 ì´ë¦„ 대신 [제품 ëª¨ë¸ ì´ë¦„](http://developer.android.com/reference/android/os/Build.html#MODEL), [제품 ì´ë¦„](http://developer.android.com/reference/android/os/Build.html#PRODUCT) ì„ ê°€ì ¸ì˜µë‹ˆë‹¤. 예를 들어 넥서스 하나 반환 합니다 `Passion` , ëª¨í† ë¡œë¼ Droid를 반환 합니다`voles`. - -### Tizen 특수 - - * 예를 들어, 공급 ì—…ì²´ì— ì˜í•´ 할당 ëœ ë””ë°”ì´ìŠ¤ 모ë¸ì„ 반환 합니다.`TIZEN` - -### Windows Phone 7, 8 특수 - - * 제조업체ì—ì„œ 지정 하는 장치 모ë¸ì„ 반환 합니다. 예를 들어 삼성 í¬ì»¤ìŠ¤ë¥¼ 반환 합니다.`SGH-i917`. - -## device.platform - -ìž¥ì¹˜ì˜ ìš´ì˜ ì²´ì œ ì´ë¦„ì„ ì–»ì„. - - var string = device.platform; - - -### ì§€ì› ë˜ëŠ” í”Œëž«í¼ - - * 안 ë“œ ë¡œì´ë“œ - * 블랙베리 10 - * Browser4 - * Firefox ìš´ì˜ ì²´ì œ - * iOS - * Tizen - * Windows Phone 7ê³¼ 8 - * 윈ë„ìš° 8 - -### 빠른 예제 - - // Depending on the device, a few examples are: - // - "Android" - // - "BlackBerry 10" - // - Browser: returns "MacIntel" on Mac - // returns "Win32" on Windows - // - "iOS" - // - "WinCE" - // - "Tizen" - var devicePlatform = device.platform; - - -### Windows Phone 7 ë‹¨ì  - -Windows Phone 7 장치 ë³´ê³  플랫í¼ìœ¼ë¡œ`WinCE`. - -### Windows Phone 8 ë‹¨ì  - -Windows Phone 8 장치 ë³´ê³  플랫í¼ìœ¼ë¡œ`Win32NT`. - -## device.uuid - -소ìžì˜ 보편ì ìœ¼ë¡œ 고유 ì‹ë³„ìž ([UUID](http://en.wikipedia.org/wiki/Universally_Unique_Identifier) 를 ì–»ì„합니다). - - var string = device.uuid; - - -### 설명 - -UUID ìƒì„± ë°©ë²•ì˜ ìžì„¸í•œ ë‚´ìš©ì€ ìž¥ì¹˜ ì œì¡°ì—…ì²´ì— ì˜í•´ ê²°ì • ë©ë‹ˆë‹¤ ë° ì†Œìžì˜ í”Œëž«í¼ ì´ë‚˜ 모ë¸. - -### ì§€ì› ë˜ëŠ” í”Œëž«í¼ - - * 안 ë“œ ë¡œì´ë“œ - * 블랙베리 10 - * iOS - * Tizen - * Windows Phone 7ê³¼ 8 - * 윈ë„ìš° 8 - -### 빠른 예제 - - / / 안 ë“œ ë¡œì´ë“œ: (문ìžì—´ë¡œ 다시!) ìž„ì˜ì˜ 64 비트 정수를 반환 합니다 / / 정수 ìž¥ì¹˜ì˜ ì²« 번째 부팅ì—ì„œ ìƒì„± / / / / 블랙베리: 디바ì´ìŠ¤ì˜ í•€ 번호를 반환 합니다 / / ì´ê²ƒì€ 9 ìžë¦¬ 고유 정수 (문ìžì—´ë¡œ 비ë¡!) / / / / ì•„ì´í°: (UIDevice í´ëž˜ìŠ¤ 설명서ì—ì„œ ìŠ ì—ˆ) / / 문ìžì—´ 여러 하드웨어ì—ì„œ ìƒì„± 하는 í•´ì‹œ ê°’ì„ ì‹ë³„ 하는 반환 합니다. - / ê·¸ê²ƒì€ ëª¨ë“  ìž¥ì¹˜ì— ëŒ€ í•œ 고유 해야 보장 ë˜ ê³  ë¬¶ì¼ ìˆ˜ 없습니다 / / / ì‚¬ìš©ìž ê³„ì •ì—. - / / Windows Phone 7: 장치 + 현재 사용ìžì˜ 해시를 반환 합니다 / / ì‚¬ìš©ìž ì •ì˜ ë˜ì§€ ì•Šì€ ê²½ìš° guid ìƒì„± ë˜ ê³  ì‘ìš© í”„ë¡œê·¸ëž¨ì„ ì œê±°í•  때까지 유지 ë©ë‹ˆë‹¤ / / Tizen: 반환 장치 IMEI (êµ­ì œ ëª¨ë°”ì¼ ê¸°ê¸° ì‹ë³„ ë˜ëŠ” IMEI 숫ìžìž…니다 / / 모든 GSM와 UMTS 휴대 ì „í™” 고유. - var deviceID = device.uuid; - - -### iOS 특질 - -`uuid`ios ìž¥ì¹˜ì— ê³ ìœ  하지 않습니다 하지만 ê° ì„¤ì¹˜ì— ëŒ€ í•œ ì‘ìš© 프로그램 마다 다릅니다. ì‚­ì œ 하 ê³  다시 애플 리 ì¼€ì´ ì…˜ì„ ì„¤ì¹˜ 하는 경우 변경 가능 하 게 ë˜í•œ iOS를 업그레ì´ë“œ 하거나 ë•Œ 버전 (iOS 5.1ì—ì—ì„œ 명백한) 당 ì‘ìš© 프로그램 업그레ì´ë“œë„ 하 ê³ . `uuid`ì€ ì‹ ë¢°í•  수 있는 ê°’ì´ ì•„ë‹™ë‹ˆë‹¤. - -### Windows Phone 7, 8 특수 - -`uuid`Windows Phone 7 í•„ìš” 허가 `ID_CAP_IDENTITY_DEVICE` . Microsoft는 ê³§ì´ ì†ì„±ì„ 세ì›ë‹ˆë‹¤ ê°€ëŠ¥ì„±ì´ ê²ƒìž…ë‹ˆë‹¤. ê¸°ëŠ¥ì„ ì‚¬ìš©í•  수 없는 경우 ì‘ìš© 프로그램 ìž¥ì¹˜ì— ì‘ìš© í”„ë¡œê·¸ëž¨ì˜ ì„¤ì¹˜ 하는 ë™ì•ˆ 유지 하는 ì˜êµ¬ guid를 ìƒì„± 합니다. - -## device.version - -ìš´ì˜ ì²´ì œ ë²„ì „ì„ ì–»ì„. - - var string = device.version; - - -### ì§€ì› ë˜ëŠ” í”Œëž«í¼ - - * 안 ë“œ ë¡œì´ë“œ 2.1 + - * 블랙베리 10 - * 브ë¼ìš°ì € - * iOS - * Tizen - * Windows Phone 7ê³¼ 8 - * 윈ë„ìš° 8 - -### 빠른 예제 - - // Android: Froyo OS would return "2.2" - // Eclair OS would return "2.1", "2.0.1", or "2.0" - // Version can also return update level "2.1-update1" - // - // BlackBerry: Torch 9800 using OS 6.0 would return "6.0.0.600" - // - // Browser: Returns version number for the browser - // - // iPhone: iOS 3.2 returns "3.2" - // - // Windows Phone 7: returns current OS version number, ex. on Mango returns 7.10.7720 - // Tizen: returns "TIZEN_20120425_2" - var deviceVersion = device.version; \ No newline at end of file diff --git a/plugins/cordova-plugin-device/doc/ko/index.md b/plugins/cordova-plugin-device/doc/ko/index.md deleted file mode 100644 index 0fe38a7..0000000 --- a/plugins/cordova-plugin-device/doc/ko/index.md +++ /dev/null @@ -1,206 +0,0 @@ - - -# cordova-plugin-device - -ì´ í”ŒëŸ¬ê·¸ì¸ ì •ì˜ ì „ì—­ `device` 개체, 디바ì´ìŠ¤ì˜ 하드웨어 ë° ì†Œí”„íŠ¸ì›¨ì–´ì— ì„¤ëª… 합니다. 개체는 ì „ì—­ 범위ì—ì„œ ë¹„ë¡ ê·¸ê²ƒì€ í›„ê¹Œì§€ 사용할 수 있는 `deviceready` ì´ë²¤íŠ¸. - - document.addEventListener("deviceready", onDeviceReady, false); - function onDeviceReady() { - console.log(device.cordova); - } - - -## 설치 - - cordova plugin add cordova-plugin-device - - -## ì†ì„± - -* device.cordova -* device.model -* device.platform -* device.uuid -* device.version - -## device.cordova - -코르ë„바는 장치ì—ì„œ 실행 ì¤‘ì¸ ë²„ì „ì„ ì–»ì„. - -### ì§€ì› ë˜ëŠ” í”Œëž«í¼ - -* 아마존 화재 ìš´ì˜ ì²´ì œ -* 안 ë“œ ë¡œì´ë“œ -* 블랙베리 10 -* 브ë¼ìš°ì € -* Firefox ìš´ì˜ ì²´ì œ -* iOS -* Tizen -* Windows Phone 7ê³¼ 8 -* 윈ë„ìš° 8 - -## device.model - -`device.model`소ìžì˜ ëª¨ë¸ ë˜ëŠ” ì œí’ˆì˜ ì´ë¦„ì„ ë°˜í™˜ 합니다. ê°’ 장치 제조업체ì—ì„œ 설정 ë˜ ê³  ë™ì¼ ì œí’ˆì˜ ë²„ì „ ê°„ì— ë‹¤ë¥¼ 수 있습니다. - -### ì§€ì› ë˜ëŠ” í”Œëž«í¼ - -* 안 ë“œ ë¡œì´ë“œ -* 블랙베리 10 -* 브ë¼ìš°ì € -* iOS -* Tizen -* Windows Phone 7ê³¼ 8 -* 윈ë„ìš° 8 - -### 빠른 예제 - - // Android: Nexus One returns "Passion" (Nexus One code name) - // Motorola Droid returns "voles" - // BlackBerry: Torch 9800 returns "9800" - // Browser: Google Chrome returns "Chrome" - // Safari returns "Safari" - // iOS: for the iPad Mini, returns iPad2,5; iPhone 5 is iPhone 5,1. Http://theiphonewiki.com/wiki/index.php?title=Models 참조 / / var ëª¨ë¸ = device.model; - - -### 안 ë“œ ë¡œì´ë“œ ë‹¨ì  - -* ì–´ë–¤ì€ ì¢…ì¢… 프로ë•ì…˜ 코드 ì´ë¦„ 대신 [제품 ëª¨ë¸ ì´ë¦„][1], [제품 ì´ë¦„][2] ì„ ê°€ì ¸ì˜µë‹ˆë‹¤. 예를 들어 넥서스 하나 반환 합니다 `Passion` , ëª¨í† ë¡œë¼ Droid를 반환 합니다`voles`. - - [1]: http://developer.android.com/reference/android/os/Build.html#MODEL - [2]: http://developer.android.com/reference/android/os/Build.html#PRODUCT - -### Tizen 특수 - -* 예를 들어, 공급 ì—…ì²´ì— ì˜í•´ 할당 ëœ ë””ë°”ì´ìŠ¤ 모ë¸ì„ 반환 합니다.`TIZEN` - -### Windows Phone 7, 8 특수 - -* 제조업체ì—ì„œ 지정 하는 장치 모ë¸ì„ 반환 합니다. 예를 들어 삼성 í¬ì»¤ìŠ¤ë¥¼ 반환 합니다.`SGH-i917`. - -## device.platform - -ìž¥ì¹˜ì˜ ìš´ì˜ ì²´ì œ ì´ë¦„ì„ ì–»ì„. - - var string = device.platform; - - -### ì§€ì› ë˜ëŠ” í”Œëž«í¼ - -* 안 ë“œ ë¡œì´ë“œ -* 블랙베리 10 -* Browser4 -* Firefox ìš´ì˜ ì²´ì œ -* iOS -* Tizen -* Windows Phone 7ê³¼ 8 -* 윈ë„ìš° 8 - -### 빠른 예제 - - // Depending on the device, a few examples are: - // - "Android" - // - "BlackBerry 10" - // - Browser: returns "MacIntel" on Mac - // returns "Win32" on Windows - // - "iOS" - // - "WinCE" - // - "Tizen" - var devicePlatform = device.platform; - - -### Windows Phone 7 ë‹¨ì  - -Windows Phone 7 장치 ë³´ê³  플랫í¼ìœ¼ë¡œ`WinCE`. - -### Windows Phone 8 ë‹¨ì  - -Windows Phone 8 장치 ë³´ê³  플랫í¼ìœ¼ë¡œ`Win32NT`. - -## device.uuid - -소ìžì˜ 보편ì ìœ¼ë¡œ 고유 ì‹ë³„ìž ([UUID][3] 를 ì–»ì„합니다). - - [3]: http://en.wikipedia.org/wiki/Universally_Unique_Identifier - - var string = device.uuid; - - -### 설명 - -UUID ìƒì„± ë°©ë²•ì˜ ìžì„¸í•œ ë‚´ìš©ì€ ìž¥ì¹˜ ì œì¡°ì—…ì²´ì— ì˜í•´ ê²°ì • ë©ë‹ˆë‹¤ ë° ì†Œìžì˜ í”Œëž«í¼ ì´ë‚˜ 모ë¸. - -### ì§€ì› ë˜ëŠ” í”Œëž«í¼ - -* 안 ë“œ ë¡œì´ë“œ -* 블랙베리 10 -* iOS -* Tizen -* Windows Phone 7ê³¼ 8 -* 윈ë„ìš° 8 - -### 빠른 예제 - - / / 안 ë“œ ë¡œì´ë“œ: (문ìžì—´ë¡œ 다시!) ìž„ì˜ì˜ 64 비트 정수를 반환 합니다 / / 정수 ìž¥ì¹˜ì˜ ì²« 번째 부팅ì—ì„œ ìƒì„± / / / / 블랙베리: 디바ì´ìŠ¤ì˜ í•€ 번호를 반환 합니다 / / ì´ê²ƒì€ 9 ìžë¦¬ 고유 정수 (문ìžì—´ë¡œ 비ë¡!) / / / / ì•„ì´í°: (UIDevice í´ëž˜ìŠ¤ 설명서ì—ì„œ ìŠ ì—ˆ) / / 문ìžì—´ 여러 하드웨어ì—ì„œ ìƒì„± 하는 í•´ì‹œ ê°’ì„ ì‹ë³„ 하는 반환 합니다. - / ê·¸ê²ƒì€ ëª¨ë“  ìž¥ì¹˜ì— ëŒ€ í•œ 고유 해야 보장 ë˜ ê³  ë¬¶ì¼ ìˆ˜ 없습니다 / / / ì‚¬ìš©ìž ê³„ì •ì—. - / / Windows Phone 7: 장치 + 현재 사용ìžì˜ 해시를 반환 합니다 / / ì‚¬ìš©ìž ì •ì˜ ë˜ì§€ ì•Šì€ ê²½ìš° guid ìƒì„± ë˜ ê³  ì‘ìš© í”„ë¡œê·¸ëž¨ì„ ì œê±°í•  때까지 유지 ë©ë‹ˆë‹¤ / / Tizen: 반환 장치 IMEI (êµ­ì œ ëª¨ë°”ì¼ ê¸°ê¸° ì‹ë³„ ë˜ëŠ” IMEI 숫ìžìž…니다 / / 모든 GSM와 UMTS 휴대 ì „í™” 고유. - var deviceID = device.uuid; - - -### iOS 특질 - -`uuid`ios ìž¥ì¹˜ì— ê³ ìœ  하지 않습니다 하지만 ê° ì„¤ì¹˜ì— ëŒ€ í•œ ì‘ìš© 프로그램 마다 다릅니다. ì‚­ì œ 하 ê³  다시 애플 리 ì¼€ì´ ì…˜ì„ ì„¤ì¹˜ 하는 경우 변경 가능 하 게 ë˜í•œ iOS를 업그레ì´ë“œ 하거나 ë•Œ 버전 (iOS 5.1ì—ì—ì„œ 명백한) 당 ì‘ìš© 프로그램 업그레ì´ë“œë„ 하 ê³ . `uuid`ì€ ì‹ ë¢°í•  수 있는 ê°’ì´ ì•„ë‹™ë‹ˆë‹¤. - -### Windows Phone 7, 8 특수 - -`uuid`Windows Phone 7 í•„ìš” 허가 `ID_CAP_IDENTITY_DEVICE` . Microsoft는 ê³§ì´ ì†ì„±ì„ 세ì›ë‹ˆë‹¤ ê°€ëŠ¥ì„±ì´ ê²ƒìž…ë‹ˆë‹¤. ê¸°ëŠ¥ì„ ì‚¬ìš©í•  수 없는 경우 ì‘ìš© 프로그램 ìž¥ì¹˜ì— ì‘ìš© í”„ë¡œê·¸ëž¨ì˜ ì„¤ì¹˜ 하는 ë™ì•ˆ 유지 하는 ì˜êµ¬ guid를 ìƒì„± 합니다. - -## device.version - -ìš´ì˜ ì²´ì œ ë²„ì „ì„ ì–»ì„. - - var string = device.version; - - -### ì§€ì› ë˜ëŠ” í”Œëž«í¼ - -* 안 ë“œ ë¡œì´ë“œ 2.1 + -* 블랙베리 10 -* 브ë¼ìš°ì € -* iOS -* Tizen -* Windows Phone 7ê³¼ 8 -* 윈ë„ìš° 8 - -### 빠른 예제 - - // Android: Froyo OS would return "2.2" - // Eclair OS would return "2.1", "2.0.1", or "2.0" - // Version can also return update level "2.1-update1" - // - // BlackBerry: Torch 9800 using OS 6.0 would return "6.0.0.600" - // - // Browser: Returns version number for the browser - // - // iPhone: iOS 3.2 returns "3.2" - // - // Windows Phone 7: returns current OS version number, ex. on Mango returns 7.10.7720 - // Tizen: returns "TIZEN_20120425_2" - var deviceVersion = device.version; diff --git a/plugins/cordova-plugin-device/doc/pl/README.md b/plugins/cordova-plugin-device/doc/pl/README.md deleted file mode 100644 index c38832d..0000000 --- a/plugins/cordova-plugin-device/doc/pl/README.md +++ /dev/null @@ -1,214 +0,0 @@ - - -# cordova-plugin-device - -[![Build Status](https://travis-ci.org/apache/cordova-plugin-device.svg?branch=master)](https://travis-ci.org/apache/cordova-plugin-device) - -Ten plugin okreÅ›la globalne `device` obiekt, który opisuje urzÄ…dzenia sprzÄ™towe i programowe. Mimo, że obiekt jest w globalnym zasiÄ™gu, nie jest dostÄ™pne dopiero po `deviceready` zdarzenie. - - document.addEventListener("deviceready", onDeviceReady, false); - function onDeviceReady() { - console.log(device.cordova); - } - - -## Instalacja - - cordova plugin add cordova-plugin-device - - -## WÅ‚aÅ›ciwoÅ›ci - - * device.cordova - * device.model - * device.platform - * device.uuid - * device.version - -## device.cordova - -Pobierz wersjÄ™ Cordova dziaÅ‚a na urzÄ…dzeniu. - -### ObsÅ‚ugiwane platformy - - * Amazon Fire OS - * Android - * BlackBerry 10 - * PrzeglÄ…darka - * Firefox OS - * iOS - * Tizen - * Windows Phone 7 i 8 - * Windows 8 - -## device.model - -`device.model`Zwraca nazwÄ™ modelu lub produktu. Wartość jest zestaw przez producenta urzÄ…dzenia i mogÄ… siÄ™ różnić miÄ™dzy wersjami tego samego produktu. - -### ObsÅ‚ugiwane platformy - - * Android - * BlackBerry 10 - * PrzeglÄ…darka - * iOS - * Tizen - * Windows Phone 7 i 8 - * Windows 8 - -### Szybki przykÅ‚ad - - // Android: Nexus One returns "Passion" (Nexus One code name) - // Motorola Droid returns "voles" - // BlackBerry: Torch 9800 returns "9800" - // Browser: Google Chrome returns "Chrome" - // Safari returns "Safari" - // iOS: for the iPad Mini, returns iPad2,5; iPhone 5 is iPhone 5,1. Zobacz http://theiphonewiki.com/wiki/index.php?title=Models / / modelu var = device.model; - - -### Dziwactwa Androida - - * Pobiera [nazwÄ™ produktu](http://developer.android.com/reference/android/os/Build.html#PRODUCT) zamiast [nazwy modelu](http://developer.android.com/reference/android/os/Build.html#MODEL), który czÄ™sto jest nazwÄ… kod produkcji. Na przykÅ‚ad, Nexus One zwraca `Passion` , i zwraca Motorola Droid`voles`. - -### Dziwactwa Tizen - - * Zwraca modelu urzÄ…dzenia przypisane przez dostawcÄ™, na przykÅ‚ad,`TIZEN` - -### Windows Phone 7 i 8 dziwactwa - - * Zwraca modelu urzÄ…dzenia, okreÅ›lonej przez producenta. Na przykÅ‚ad Samsung ostroÅ›ci zwraca`SGH-i917`. - -## device.platform - -Uzyskać nazwÄ™ systemu operacyjnego urzÄ…dzenia. - - var string = device.platform; - - -### ObsÅ‚ugiwane platformy - - * Android - * BlackBerry 10 - * Browser4 - * Firefox OS - * iOS - * Tizen - * Windows Phone 7 i 8 - * Windows 8 - -### Szybki przykÅ‚ad - - // Depending on the device, a few examples are: - // - "Android" - // - "BlackBerry 10" - // - Browser: returns "MacIntel" on Mac - // returns "Win32" on Windows - // - "iOS" - // - "WinCE" - // - "Tizen" - var devicePlatform = device.platform; - - -### Dziwactwa Windows Phone 7 - -UrzÄ…dzenia Windows Phone 7 raport platformy jako`WinCE`. - -### Windows Phone 8 dziwactwa - -UrzÄ…dzenia Windows Phone 8 raport platformy jako`Win32NT`. - -## device.uuid - -SiÄ™ urzÄ…dzenia uniwersalnie unikatowy identyfikator ([UUID](http://en.wikipedia.org/wiki/Universally_Unique_Identifier)). - - var string = device.uuid; - - -### Opis - -Szczegóły jak UUID jest generowane sÄ… okreÅ›lane przez producenta urzÄ…dzenia i sÄ… specyficzne dla platformy lub modelu urzÄ…dzenia. - -### ObsÅ‚ugiwane platformy - - * Android - * BlackBerry 10 - * iOS - * Tizen - * Windows Phone 7 i 8 - * Windows 8 - -### Szybki przykÅ‚ad - - // Android: Returns a random 64-bit integer (as a string, again!) - // The integer is generated on the device's first boot - // - // BlackBerry: Returns the PIN number of the device - // This is a nine-digit unique integer (as a string, though!) - // - // iPhone: (Paraphrased from the UIDevice Class documentation) - // Returns a string of hash values created from multiple hardware identifies. - // It is guaranteed to be unique for every device and can't be tied - // to the user account. - // Windows Phone 7 : Returns a hash of device+current user, - // if the user is not defined, a guid is generated and will persist until the app is uninstalled - // Tizen: returns the device IMEI (International Mobile Equipment Identity or IMEI is a number - // unique to every GSM and UMTS mobile phone. - var deviceID = device.uuid; - - -### iOS dziwactwo - -`uuid`Na iOS nie jest przypisany do urzÄ…dzenia, ale różni siÄ™ dla każdej aplikacji, dla każdej instalacji. Zmienia siÄ™ jeÅ›li możesz usunąć i ponownie zainstalować aplikacjÄ™, a ewentualnie także po aktualizacji iOS czy nawet uaktualnienia aplikacji dla wersji (widoczny w iOS 5.1). `uuid`Jest nie wiarygodne wartoÅ›ci. - -### Windows Phone 7 i 8 dziwactwa - -`uuid`Dla Windows Phone 7 wymaga uprawnieÅ„ `ID_CAP_IDENTITY_DEVICE` . Microsoft bÄ™dzie prawdopodobnie potÄ™piać ten wkrótce. JeÅ›li funkcja nie jest dostÄ™pna, aplikacja generuje trwaÅ‚e identyfikator guid, który jest utrzymywany przez czas trwania instalacji aplikacji na urzÄ…dzeniu. - -## device.version - -Pobierz wersjÄ™ systemu operacyjnego. - - var string = device.version; - - -### ObsÅ‚ugiwane platformy - - * Android 2.1 + - * BlackBerry 10 - * PrzeglÄ…darka - * iOS - * Tizen - * Windows Phone 7 i 8 - * Windows 8 - -### Szybki przykÅ‚ad - - // Android: Froyo OS would return "2.2" - // Eclair OS would return "2.1", "2.0.1", or "2.0" - // Version can also return update level "2.1-update1" - // - // BlackBerry: Torch 9800 using OS 6.0 would return "6.0.0.600" - // - // Browser: Returns version number for the browser - // - // iPhone: iOS 3.2 returns "3.2" - // - // Windows Phone 7: returns current OS version number, ex. on Mango returns 7.10.7720 - // Tizen: returns "TIZEN_20120425_2" - var deviceVersion = device.version; \ No newline at end of file diff --git a/plugins/cordova-plugin-device/doc/pl/index.md b/plugins/cordova-plugin-device/doc/pl/index.md deleted file mode 100644 index acc8f9c..0000000 --- a/plugins/cordova-plugin-device/doc/pl/index.md +++ /dev/null @@ -1,206 +0,0 @@ - - -# cordova-plugin-device - -Ten plugin okreÅ›la globalne `device` obiekt, który opisuje urzÄ…dzenia sprzÄ™towe i programowe. Mimo, że obiekt jest w globalnym zasiÄ™gu, nie jest dostÄ™pne dopiero po `deviceready` zdarzenie. - - document.addEventListener("deviceready", onDeviceReady, false); - function onDeviceReady() { - console.log(device.cordova); - } - - -## Instalacja - - cordova plugin add cordova-plugin-device - - -## WÅ‚aÅ›ciwoÅ›ci - -* device.cordova -* device.model -* device.platform -* device.uuid -* device.version - -## device.cordova - -Pobierz wersjÄ™ Cordova dziaÅ‚a na urzÄ…dzeniu. - -### ObsÅ‚ugiwane platformy - -* Amazon Fire OS -* Android -* BlackBerry 10 -* PrzeglÄ…darka -* Firefox OS -* iOS -* Tizen -* Windows Phone 7 i 8 -* Windows 8 - -## device.model - -`device.model`Zwraca nazwÄ™ modelu lub produktu. Wartość jest zestaw przez producenta urzÄ…dzenia i mogÄ… siÄ™ różnić miÄ™dzy wersjami tego samego produktu. - -### ObsÅ‚ugiwane platformy - -* Android -* BlackBerry 10 -* PrzeglÄ…darka -* iOS -* Tizen -* Windows Phone 7 i 8 -* Windows 8 - -### Szybki przykÅ‚ad - - // Android: Nexus One returns "Passion" (Nexus One code name) - // Motorola Droid returns "voles" - // BlackBerry: Torch 9800 returns "9800" - // Browser: Google Chrome returns "Chrome" - // Safari returns "Safari" - // iOS: for the iPad Mini, returns iPad2,5; iPhone 5 is iPhone 5,1. Zobacz http://theiphonewiki.com/wiki/index.php?title=Models / / modelu var = device.model; - - -### Dziwactwa Androida - -* Pobiera [nazwÄ™ produktu][1] zamiast [nazwy modelu][2], który czÄ™sto jest nazwÄ… kod produkcji. Na przykÅ‚ad, Nexus One zwraca `Passion` , i zwraca Motorola Droid`voles`. - - [1]: http://developer.android.com/reference/android/os/Build.html#PRODUCT - [2]: http://developer.android.com/reference/android/os/Build.html#MODEL - -### Dziwactwa Tizen - -* Zwraca modelu urzÄ…dzenia przypisane przez dostawcÄ™, na przykÅ‚ad,`TIZEN` - -### Windows Phone 7 i 8 dziwactwa - -* Zwraca modelu urzÄ…dzenia, okreÅ›lonej przez producenta. Na przykÅ‚ad Samsung ostroÅ›ci zwraca`SGH-i917`. - -## device.platform - -Uzyskać nazwÄ™ systemu operacyjnego urzÄ…dzenia. - - var string = device.platform; - - -### ObsÅ‚ugiwane platformy - -* Android -* BlackBerry 10 -* Browser4 -* Firefox OS -* iOS -* Tizen -* Windows Phone 7 i 8 -* Windows 8 - -### Szybki przykÅ‚ad - - // Depending on the device, a few examples are: - // - "Android" - // - "BlackBerry 10" - // - Browser: returns "MacIntel" on Mac - // returns "Win32" on Windows - // - "iOS" - // - "WinCE" - // - "Tizen" - var devicePlatform = device.platform; - - -### Dziwactwa Windows Phone 7 - -UrzÄ…dzenia Windows Phone 7 raport platformy jako`WinCE`. - -### Windows Phone 8 dziwactwa - -UrzÄ…dzenia Windows Phone 8 raport platformy jako`Win32NT`. - -## device.uuid - -SiÄ™ urzÄ…dzenia uniwersalnie unikatowy identyfikator ([UUID][3]). - - [3]: http://en.wikipedia.org/wiki/Universally_Unique_Identifier - - var string = device.uuid; - - -### Opis - -Szczegóły jak UUID jest generowane sÄ… okreÅ›lane przez producenta urzÄ…dzenia i sÄ… specyficzne dla platformy lub modelu urzÄ…dzenia. - -### ObsÅ‚ugiwane platformy - -* Android -* BlackBerry 10 -* iOS -* Tizen -* Windows Phone 7 i 8 -* Windows 8 - -### Szybki przykÅ‚ad - - / / Android: zwraca losowe 64-bitowa liczba caÅ‚kowita (jako ciÄ…g, znowu!) / / liczba caÅ‚kowita jest generowany na pierwszego uruchomienia urzÄ…dzenia / / / / BlackBerry: zwraca numer PIN urzÄ…dzenia / / to jest unikatowÄ… liczbÄ… caÅ‚kowitÄ… dziewiÄ™ciu cyfr (jako ciÄ…g, choć!) / / / / iPhone: (zacytowana w dokumentacji klasy UIDevice) / / zwraca ciÄ…g wartoÅ›ci mieszania utworzone z wielu sprzÄ™tu identyfikuje. - Zapewniona jest unikatowy dla każdego urzÄ…dzenia i nie może być zwiÄ…zane z / do konta użytkownika. - / / Windows Phone 7: zwraca wartość mieszania urzÄ…dzenia + bieżący użytkownik, / / jeÅ›li nie zdefiniowane przez użytkownika, identyfikator guid jest generowany i bÄ™dzie trwać do czasu odinstalowania aplikacji / / Tizen: zwraca urzÄ…dzenia IMEI (International Mobile Equipment Identity lub IMEI jest liczbÄ… / / unikatowe dla każdego telefonu komórkowego GSM i UMTS. - var deviceID = device.uuid; - - -### iOS dziwactwo - -`uuid`Na iOS nie jest przypisany do urzÄ…dzenia, ale różni siÄ™ dla każdej aplikacji, dla każdej instalacji. Zmienia siÄ™ jeÅ›li możesz usunąć i ponownie zainstalować aplikacjÄ™, a ewentualnie także po aktualizacji iOS czy nawet uaktualnienia aplikacji dla wersji (widoczny w iOS 5.1). `uuid`Jest nie wiarygodne wartoÅ›ci. - -### Windows Phone 7 i 8 dziwactwa - -`uuid`Dla Windows Phone 7 wymaga uprawnieÅ„ `ID_CAP_IDENTITY_DEVICE` . Microsoft bÄ™dzie prawdopodobnie potÄ™piać ten wkrótce. JeÅ›li funkcja nie jest dostÄ™pna, aplikacja generuje trwaÅ‚e identyfikator guid, który jest utrzymywany przez czas trwania instalacji aplikacji na urzÄ…dzeniu. - -## device.version - -Pobierz wersjÄ™ systemu operacyjnego. - - var string = device.version; - - -### ObsÅ‚ugiwane platformy - -* Android 2.1 + -* BlackBerry 10 -* PrzeglÄ…darka -* iOS -* Tizen -* Windows Phone 7 i 8 -* Windows 8 - -### Szybki przykÅ‚ad - - // Android: Froyo OS would return "2.2" - // Eclair OS would return "2.1", "2.0.1", or "2.0" - // Version can also return update level "2.1-update1" - // - // BlackBerry: Torch 9800 using OS 6.0 would return "6.0.0.600" - // - // Browser: Returns version number for the browser - // - // iPhone: iOS 3.2 returns "3.2" - // - // Windows Phone 7: returns current OS version number, ex. on Mango returns 7.10.7720 - // Tizen: returns "TIZEN_20120425_2" - var deviceVersion = device.version; diff --git a/plugins/cordova-plugin-device/doc/ru/index.md b/plugins/cordova-plugin-device/doc/ru/index.md deleted file mode 100644 index 263b1cd..0000000 --- a/plugins/cordova-plugin-device/doc/ru/index.md +++ /dev/null @@ -1,219 +0,0 @@ - - -# cordova-plugin-device - -Этот плагин определÑет глобальный объект `device`, который опиÑывает оборудование и программное обеÑпечение уÑтройÑтва. ÐеÑÐ¼Ð¾Ñ‚Ñ€Ñ Ð½Ð° то что объект в глобальной облаÑти видимоÑти, он не доÑтупен до того момента пока не произойдет Ñобытие `deviceready`. - - document.addEventListener("deviceready", onDeviceReady, false); - function onDeviceReady() { - console.log(device.cordova); - } - - -## УÑтановка - - cordova plugin add cordova-plugin-device - - -## Параметры - -* device.cordova -* device.model -* device.platform -* device.uuid -* device.version - -## device.cordova - -Возвращает верÑию Cordova, работающую на уÑтройÑтве. - -### Поддерживаемые платформы - -* Amazon Fire OS -* Android -* BlackBerry 10 -* Обозреватель -* Firefox OS -* iOS -* Tizen -* Windows Phone 7 и 8 -* Windows 8 - -## device.model - -СвойÑтво `device.model` возвращает Ð¸Ð¼Ñ ÑƒÑтройÑтва модели или продукта. Значение уÑтанавливаетÑÑ Ð¿Ñ€Ð¾Ð¸Ð·Ð²Ð¾Ð´Ð¸Ñ‚ÐµÐ»ÐµÐ¼ уÑтройÑтва и могут отличатьÑÑ Ð² разных верÑиÑÑ… одного и того же продукта. - -### Поддерживаемые платформы - -* Android -* BlackBerry 10 -* Обозреватель -* iOS -* Tizen -* Windows Phone 7 и 8 -* Windows 8 - -### Краткий пример - - // Android: Nexus One returns "Passion" (Nexus One code name) - // Motorola Droid returns "voles" - // BlackBerry: Torch 9800 returns "9800" - // Browser: Google Chrome returns "Chrome" - // Safari returns "Safari" - // iOS: for the iPad Mini, returns iPad2,5; iPhone 5 is iPhone 5,1. See http://theiphonewiki.com/wiki/index.php?title=Models - // - var model = device.model; - - -### ОÑобенноÑти Android - -* Возвращает [Ð¸Ð¼Ñ Ð¿Ñ€Ð¾Ð´ÑƒÐºÑ‚Ð°][1] , а не [Ð¸Ð¼Ñ Ð¼Ð¾Ð´ÐµÐ»Ð¸][2], которое чаÑто ÑвлÑетÑÑ Ð¿Ñ€Ð¾Ð¸Ð·Ð²Ð¾Ð´Ñтвенным кодом. Ðапример, Nexus One из них возвращает `Passion` , и Motorola Droid возвращает `voles`. - - [1]: http://developer.android.com/reference/android/os/Build.html#PRODUCT - [2]: http://developer.android.com/reference/android/os/Build.html#MODEL - -### ОÑобенноÑти Tizen - -* Возвращает модель уÑтройÑтва, назначенного вендором, например,`TIZEN` - -### ОÑобенноÑти Windows Phone 7 и 8 - -* Возвращает модель уÑтройÑтва, указанной заводом-изготовителем. Ðапример Samsung Focus возвращает `SGH-i917`. - -## device.platform - -Получите Ð¸Ð¼Ñ Ð¾Ð¿ÐµÑ€Ð°Ñ†Ð¸Ð¾Ð½Ð½Ð¾Ð¹ ÑиÑтемы уÑтройÑтва. - - var string = device.platform; - - -### Поддерживаемые платформы - -* Android -* BlackBerry 10 -* Браузером4 -* Firefox OS -* iOS -* Tizen -* Windows Phone 7 и 8 -* Windows 8 - -### Краткий пример - - // Depending on the device, a few examples are: - // - "Android" - // - "BlackBerry 10" - // - Browser: returns "MacIntel" on Mac - // returns "Win32" on Windows - // - "iOS" - // - "WinCE" - // - "Tizen" - var devicePlatform = device.platform; - - -### ОÑобенноÑти Windows Phone 7 - -Windows Phone 7 уÑтройÑтва Ñообщают платформу как `WinCE`. - -### ОÑобенноÑти Windows Phone 8 - -УÑтройÑтва Windows Phone 8 Ñообщают платформу как `Win32NT`. - -## device.uuid - -Возвращает универÑальный уникального идентификатора ([UUID][3] уÑтройÑтва). - - [3]: http://en.wikipedia.org/wiki/Universally_Unique_Identifier - - var string = device.uuid; - - -### ОпиÑание - -ÐŸÐ¾Ð´Ñ€Ð¾Ð±Ð½Ð°Ñ Ð¸Ð½Ñ„Ð¾Ñ€Ð¼Ð°Ñ†Ð¸Ñ Ð¾ том как UUID генерируетÑÑ, определÑÑŽÑ‚ÑÑ Ð¸Ð·Ð³Ð¾Ñ‚Ð¾Ð²Ð¸Ñ‚ÐµÐ»ÐµÐ¼ уÑтройÑтва и ÑвлÑÑŽÑ‚ÑÑ ÑпецифичеÑкими Ð´Ð»Ñ Ð¿Ð»Ð°Ñ‚Ñ„Ð¾Ñ€Ð¼Ñ‹ или модели уÑтройÑтва. - -### Поддерживаемые платформы - -* Android -* BlackBerry 10 -* iOS -* Tizen -* Windows Phone 7 и 8 -* Windows 8 - -### Краткий пример - - // Android: Возвращает Ñлучайное 64-разрÑдное целое чиÑло (в виде Ñтроки, опÑÑ‚ÑŒ!) - // целое чиÑло генерируетÑÑ Ð¿Ñ€Ð¸ первой загрузке уÑтройÑтва - // - // BlackBerry: Возвращает номер PIN уÑтройÑтва - // Ñто 9 значный уникальный целочиÑленный (как Ñтрока, хотÑ!) - // - // iPhone: (Перефразировано из документации клаÑÑа UIDevice) - // возвращает Ñтроку Ñ…Ñш-значениÑ, Ñозданные из неÑкольких аппаратных определÑет. - // Это значение гарантированно ÑвлÑетÑÑ ÑƒÐ½Ð¸ÐºÐ°Ð»ÑŒÐ½Ñ‹Ð¼ Ð´Ð»Ñ ÐºÐ°Ð¶Ð´Ð¾Ð³Ð¾ уÑтройÑтва и не может быть привÑзано - // к учетной запиÑи пользователÑ. - // Windows Phone 7: Возвращает Ñ…Ñш уÑтройÑтво + текущего пользователÑ, - // еÑли пользователь не определен, формируетÑÑ guid который и будет ÑохранÑÑ‚ÑŒÑÑ Ð´Ð¾ тех пор, пока приложение не удалитьÑÑ - // Tizen: возвращает IMEI уÑтройÑтва (Международный идентификатор мобильного Ð¾Ð±Ð¾Ñ€ÑƒÐ´Ð¾Ð²Ð°Ð½Ð¸Ñ Ð¸Ð»Ð¸ IMEI Ñто чиÑло - // уникальное Ð´Ð»Ñ ÐºÐ°Ð¶Ð´Ð¾Ð³Ð¾ мобильного телефона GSM и UMTS. - var deviceID = device.uuid; - - -### ОÑобенноÑти iOS - -Ðа iOS `uuid` не ÑвлÑетÑÑ ÑƒÐ½Ð¸ÐºÐ°Ð»ÑŒÐ½Ñ‹Ð¼ Ð´Ð»Ñ ÑƒÑтройÑтва, но варьируетÑÑ Ð´Ð»Ñ ÐºÐ°Ð¶Ð´Ð¾Ð³Ð¾ приложениÑ, и Ð´Ð»Ñ ÐºÐ°Ð¶Ð´Ð¾Ð¹ уÑтановки. Значение менÑетÑÑ, еÑли удалить и повторно уÑтановить приложение, и возможно также когда вы обновите iOS, или даже обновить приложение до Ñледующей верÑии (очевидно в iOS 5.1). Значение `uuid` не ÑвлÑетÑÑ Ð½Ð°Ð´ÐµÐ¶Ð½Ñ‹Ð¼. - -### ОÑобенноÑти Windows Phone 7 и 8 - -Ð”Ð»Ñ Windows Phone 7 `uuid` требует Ñ€Ð°Ð·Ñ€ÐµÑˆÐµÐ½Ð¸Ñ `ID_CAP_IDENTITY_DEVICE` . Microsoft Ñкорее вÑего Ñкоро Ñделает Ñто ÑвойÑтво уÑтаревшим. ЕÑли возможноÑÑ‚ÑŒ недоÑтупна, приложение Ñоздает поÑтоÑнные guid, который ÑохранÑетÑÑ Ð½Ð° вÑе Ð²Ñ€ÐµÐ¼Ñ ÑƒÑтановки Ð¿Ñ€Ð¸Ð»Ð¾Ð¶ÐµÐ½Ð¸Ñ Ð½Ð° уÑтройÑтве. - -## device.version - -Возвращает верÑию операционной ÑиÑтемы. - - var string = device.version; - - -### Поддерживаемые платформы - -* Android 2.1 + -* BlackBerry 10 -* Обозреватель -* iOS -* Tizen -* Windows Phone 7 и 8 -* Windows 8 - -### Краткий пример - - // Android: Froyo OS would return "2.2" - // Eclair OS would return "2.1", "2.0.1", or "2.0" - // Version can also return update level "2.1-update1" - // - // BlackBerry: Torch 9800 using OS 6.0 would return "6.0.0.600" - // - // Browser: Returns version number for the browser - // - // iPhone: iOS 3.2 returns "3.2" - // - // Windows Phone 7: returns current OS version number, ex. on Mango returns 7.10.7720 - // Tizen: returns "TIZEN_20120425_2" - var deviceVersion = device.version; diff --git a/plugins/cordova-plugin-device/doc/zh/README.md b/plugins/cordova-plugin-device/doc/zh/README.md deleted file mode 100644 index 9a18a55..0000000 --- a/plugins/cordova-plugin-device/doc/zh/README.md +++ /dev/null @@ -1,203 +0,0 @@ - - -# cordova-plugin-device - -[![Build Status](https://travis-ci.org/apache/cordova-plugin-device.svg?branch=master)](https://travis-ci.org/apache/cordova-plugin-device) - -這個外掛程å¼å®šç¾©å…¨çƒ `device` 物件,æ述該設備的硬體和軟體。 雖然物件是在全çƒç¯„åœå…§ï¼Œä½†ä¸æ˜¯å¯ç”¨ï¼Œç›´åˆ°å¾Œ `deviceready` 事件。 - - document.addEventListener("deviceready", onDeviceReady, false); - function onDeviceReady() { - console.log(device.cordova); - } - - -## å®‰è£ - - cordova plugin add cordova-plugin-device - - -## 屬性 - - * device.cordova - * device.model - * device.platform - * device.uuid - * device.version - -## device.cordova - -ç²å–科爾多瓦在設備上é‹è¡Œçš„版本。 - -### 支æ´çš„平臺 - - * 亞馬éœç« OS - * Android 系統 - * 黑莓 10 - * ç€è¦½å™¨ - * ç«ç‹ç€è¦½å™¨ä½œæ¥­ç³»çµ± - * iOS - * Tizen - * Windows Phone 7 å’Œ 8 - * Windows 8 - -## device.model - -`device.model`返回設備的模型或產å“çš„å稱。值由設備製造商設置和åŒä¸€ç”¢å“çš„ä¸åŒç‰ˆæœ¬å¯èƒ½ä¸åŒã€‚ - -### 支æ´çš„平臺 - - * Android 系統 - * 黑莓 10 - * ç€è¦½å™¨ - * iOS - * Tizen - * Windows Phone 7 å’Œ 8 - * Windows 8 - -### 快速的示例 - - // Android: Nexus One returns "Passion" (Nexus One code name) - // Motorola Droid returns "voles" - // BlackBerry: Torch 9800 returns "9800" - // Browser: Google Chrome returns "Chrome" - // Safari returns "Safari" - // iOS: for the iPad Mini, returns iPad2,5; iPhone 5 is iPhone 5,1. è«‹åƒé–± HTTP://theiphonewiki.com/wiki/index.php?title=Models / / var 模型 = device.model ï¼› - - -### Android 的怪癖 - - * ç²å–[產å“å稱](http://developer.android.com/reference/android/os/Build.html#PRODUCT)而ä¸æ˜¯[產å“型號å稱](http://developer.android.com/reference/android/os/Build.html#MODEL),這往往是生產代碼å稱。 例如,Nexus One 返回 `Passion` ,和摩托羅拉 Droid 返回`voles`. - -### Tizen 怪癖 - - * 例如,返回與供應商指派的設備模型`TIZEN` - -### Windows Phone 7 å’Œ 8 怪癖 - - * 返回由製造商指定的設備模型。例如,三星焦點返回`SGH-i917`. - -## device.platform - -ç²å–設備的作業系統å稱。 - - var string = device.platform; - - -### 支æ´çš„平臺 - - * Android 系統 - * 黑莓 10 - * Browser4 - * ç«ç‹ç€è¦½å™¨ä½œæ¥­ç³»çµ± - * iOS - * Tizen - * Windows Phone 7 å’Œ 8 - * Windows 8 - -### 快速的示例 - - // Depending on the device, a few examples are: - // - "Android" - // - "BlackBerry 10" - // - Browser: returns "MacIntel" on Mac - // returns "Win32" on Windows - // - "iOS" - // - "WinCE" - // - "Tizen" - var devicePlatform = device.platform; - - -### Windows Phone 7 的怪癖 - -Windows Phone 7 設備報告作為平臺`WinCE`. - -### Windows Phone 8 怪癖 - -Windows Phone 8 設備報告作為平臺`Win32NT`. - -## device.uuid - -ç²å–設備的通用唯一識別碼 ([UUID](http://en.wikipedia.org/wiki/Universally_Unique_Identifier)). - - var string = device.uuid; - - -### 說明 - -如何生æˆä¸€å€‹ UUID 的細節由設備製造商和特定于設備的平臺或模型。 - -### 支æ´çš„平臺 - - * Android 系統 - * 黑莓 10 - * iOS - * Tizen - * Windows Phone 7 å’Œ 8 - * Windows 8 - -### 快速的示例 - - / / Android: 一個隨機的 64 ä½æ•´æ•¸ (作為字串返回,å†æ¬¡!) / / 上設備的第一次啟動生æˆçš„整數 / / / / 黑莓手機: 返回設備的 PIN 號碼 / / 這是ä¹å€‹æ•¸å­—的唯一整數 (作為字串,雖然!) / / / / iPhone: (從 UIDevice 類文檔解釋) / / 返回一個字串的雜湊值創建的多個硬體標識。 - / / 它ä¿è­‰æ˜¯å”¯ä¸€çš„æ¯å€‹è¨­å‚™ä¸¦ä¸èƒ½ç¶ / / 到使用者帳戶。 - / / Windows Phone 7: 返回的雜湊代碼的設備 + 當å‰ä½¿ç”¨è€…,/ / 如果未定義使用者,則一個 guid 生æˆçš„並且將會ä¿ç•™ç›´åˆ°å¸è¼‰è©²æ‡‰ç”¨ç¨‹å¼ / / Tizen: 返回設備 IMEI (國際行動è£ç½®èº«ä»½æˆ– IMEI æ˜¯ä¸€å€‹æ•¸ä½ / / ç¨æœ‰çš„æ¯ä¸€å€‹ UMTS å’Œ GSM 行動電話。 - var deviceID = device.uuid; - - -### iOS 怪癖 - -`uuid`在 iOS ä¸æ˜¯å”¯ä¸€çš„一種è£ç½®ï¼Œä½†å°æ–¼æ¯å€‹æ‡‰ç”¨ç¨‹å¼ï¼Œç‚ºæ¯å€‹å®‰è£è€Œç•°ã€‚ 如果您刪除並é‡æ–°å®‰è£è©²æ‡‰ç”¨ç¨‹å¼ï¼Œå®ƒæ›´æ”¹å’Œå¯èƒ½é‚„當你å‡ç´š iOS,或甚至å‡ç´šæ¯å€‹ç‰ˆæœ¬ (iOS 5.1 中存在明顯的) 的應用程å¼ã€‚ `uuid`ä¸æ˜¯ä¸€å€‹å¯é çš„值。 - -### Windows Phone 7 å’Œ 8 怪癖 - -`uuid`為 Windows Phone 7 é ˆç¶“è¨±å¯ `ID_CAP_IDENTITY_DEVICE` 。 Microsoft å¯èƒ½æœƒå¾ˆå¿«æ£„用此屬性。 如果沒有å¯ç”¨çš„能力,應用程å¼å°‡ç”Ÿæˆè¨­å‚™ä¸Šæ‡‰ç”¨ç¨‹å¼çš„安è£éŽç¨‹ä¸­ä¿æŒæŒçºŒçš„ guid。 - -## device.version - -ç²å–作業系統版本。 - - var string = device.version; - - -### 支æ´çš„平臺 - - * Android 2.1 + - * 黑莓 10 - * ç€è¦½å™¨ - * iOS - * Tizen - * Windows Phone 7 å’Œ 8 - * Windows 8 - -### 快速的示例 - - // Android: Froyo OS would return "2.2" - // Eclair OS would return "2.1", "2.0.1", or "2.0" - // Version can also return update level "2.1-update1" - // - // BlackBerry: Torch 9800 using OS 6.0 would return "6.0.0.600" - // - // Browser: Returns version number for the browser - // - // iPhone: iOS 3.2 returns "3.2" - // - // Windows Phone 7: returns current OS version number, ex. on Mango returns 7.10.7720 - // Tizen: returns "TIZEN_20120425_2" - var deviceVersion = device.version; \ No newline at end of file diff --git a/plugins/cordova-plugin-device/doc/zh/index.md b/plugins/cordova-plugin-device/doc/zh/index.md deleted file mode 100644 index 5626d69..0000000 --- a/plugins/cordova-plugin-device/doc/zh/index.md +++ /dev/null @@ -1,206 +0,0 @@ - - -# cordova-plugin-device - -這個外掛程å¼å®šç¾©å…¨çƒ `device` 物件,æ述該設備的硬體和軟體。 雖然物件是在全çƒç¯„åœå…§ï¼Œä½†ä¸æ˜¯å¯ç”¨ï¼Œç›´åˆ°å¾Œ `deviceready` 事件。 - - document.addEventListener("deviceready", onDeviceReady, false); - function onDeviceReady() { - console.log(device.cordova); - } - - -## å®‰è£ - - cordova plugin add cordova-plugin-device - - -## 屬性 - -* device.cordova -* device.model -* device.platform -* device.uuid -* device.version - -## device.cordova - -ç²å–科爾多瓦在設備上é‹è¡Œçš„版本。 - -### 支æ´çš„平臺 - -* 亞馬éœç« OS -* Android 系統 -* 黑莓 10 -* ç€è¦½å™¨ -* ç«ç‹ç€è¦½å™¨çš„作業系統 -* iOS -* æ³° -* Windows Phone 7 å’Œ 8 -* Windows 8 - -## device.model - -`device.model`返回設備的模型或產å“çš„å稱。值由設備製造商設置和åŒä¸€ç”¢å“çš„ä¸åŒç‰ˆæœ¬å¯èƒ½ä¸åŒã€‚ - -### 支æ´çš„平臺 - -* Android 系統 -* 黑莓 10 -* ç€è¦½å™¨ -* iOS -* æ³° -* Windows Phone 7 å’Œ 8 -* Windows 8 - -### 快速的示例 - - // Android: Nexus One returns "Passion" (Nexus One code name) - // Motorola Droid returns "voles" - // BlackBerry: Torch 9800 returns "9800" - // Browser: Google Chrome returns "Chrome" - // Safari returns "Safari" - // iOS: for the iPad Mini, returns iPad2,5; iPhone 5 is iPhone 5,1. è«‹åƒé–± HTTP://theiphonewiki.com/wiki/index.php?title=Models / / var 模型 = device.model ï¼› - - -### Android 的怪癖 - -* ç²å–[產å“å稱][1]而ä¸æ˜¯[產å“型號å稱][2],這往往是生產代碼å稱。 例如,Nexus One 返回 `Passion` ,和摩托羅拉 Droid 返回`voles`. - - [1]: http://developer.android.com/reference/android/os/Build.html#PRODUCT - [2]: http://developer.android.com/reference/android/os/Build.html#MODEL - -### Tizen 怪癖 - -* 例如,返回與供應商指派的設備模型`TIZEN` - -### Windows Phone 7 å’Œ 8 怪癖 - -* 返回由製造商指定的設備模型。例如,三星焦點返回`SGH-i917`. - -## device.platform - -ç²å–設備的作業系統å稱。 - - var string = device.platform; - - -### 支æ´çš„平臺 - -* Android 系統 -* 黑莓 10 -* Browser4 -* ç«ç‹ç€è¦½å™¨çš„作業系統 -* iOS -* æ³° -* Windows Phone 7 å’Œ 8 -* Windows 8 - -### 快速的示例 - - // Depending on the device, a few examples are: - // - "Android" - // - "BlackBerry 10" - // - Browser: returns "MacIntel" on Mac - // returns "Win32" on Windows - // - "iOS" - // - "WinCE" - // - "Tizen" - var devicePlatform = device.platform; - - -### Windows Phone 7 的怪癖 - -Windows Phone 7 設備報告作為平臺`WinCE`. - -### Windows Phone 8 怪癖 - -Windows Phone 8 設備報告作為平臺`Win32NT`. - -## device.uuid - -ç²å–設備的通用唯一識別碼 ([UUID][3]). - - [3]: http://en.wikipedia.org/wiki/Universally_Unique_Identifier - - var string = device.uuid; - - -### 說明 - -如何生æˆä¸€å€‹ UUID 的細節由設備製造商和特定于設備的平臺或模型。 - -### 支æ´çš„平臺 - -* Android 系統 -* 黑莓 10 -* iOS -* Tizen -* Windows Phone 7 å’Œ 8 -* Windows 8 - -### 快速的示例 - - / / Android: 一個隨機的 64 ä½æ•´æ•¸ (作為字串返回,å†æ¬¡!) / / 上設備的第一次啟動生æˆçš„整數 / / / / 黑莓手機: 返回設備的 PIN 號碼 / / 這是ä¹å€‹æ•¸å­—的唯一整數 (作為字串,雖然!) / / / / iPhone: (從 UIDevice 類文檔解釋) / / 返回一個字串的雜湊值創建的多個硬體標識。 - / / 它ä¿è­‰æ˜¯å”¯ä¸€çš„æ¯å€‹è¨­å‚™ä¸¦ä¸èƒ½ç¶ / / 到使用者帳戶。 - / / Windows Phone 7: 返回的雜湊代碼的設備 + 當å‰ä½¿ç”¨è€…,/ / 如果未定義使用者,則一個 guid 生æˆçš„並且將會ä¿ç•™ç›´åˆ°å¸è¼‰è©²æ‡‰ç”¨ç¨‹å¼ / / Tizen: 返回設備 IMEI (國際行動è£ç½®èº«ä»½æˆ– IMEI æ˜¯ä¸€å€‹æ•¸ä½ / / ç¨æœ‰çš„æ¯ä¸€å€‹ UMTS å’Œ GSM 行動電話。 - var deviceID = device.uuid; - - -### iOS 怪癖 - -`uuid`在 iOS ä¸æ˜¯å”¯ä¸€çš„一種è£ç½®ï¼Œä½†å°æ–¼æ¯å€‹æ‡‰ç”¨ç¨‹å¼ï¼Œç‚ºæ¯å€‹å®‰è£è€Œç•°ã€‚ 如果您刪除並é‡æ–°å®‰è£è©²æ‡‰ç”¨ç¨‹å¼ï¼Œå®ƒæ›´æ”¹å’Œå¯èƒ½é‚„當你å‡ç´š iOS,或甚至å‡ç´šæ¯å€‹ç‰ˆæœ¬ (iOS 5.1 中存在明顯的) 的應用程å¼ã€‚ `uuid`ä¸æ˜¯ä¸€å€‹å¯é çš„值。 - -### Windows Phone 7 å’Œ 8 怪癖 - -`uuid`為 Windows Phone 7 é ˆç¶“è¨±å¯ `ID_CAP_IDENTITY_DEVICE` 。 Microsoft å¯èƒ½æœƒå¾ˆå¿«æ£„用此屬性。 如果沒有å¯ç”¨çš„能力,應用程å¼å°‡ç”Ÿæˆè¨­å‚™ä¸Šæ‡‰ç”¨ç¨‹å¼çš„安è£éŽç¨‹ä¸­ä¿æŒæŒçºŒçš„ guid。 - -## device.version - -ç²å–作業系統版本。 - - var string = device.version; - - -### 支æ´çš„平臺 - -* Android 2.1 + -* 黑莓 10 -* ç€è¦½å™¨ -* iOS -* æ³° -* Windows Phone 7 å’Œ 8 -* Windows 8 - -### 快速的示例 - - // Android: Froyo OS would return "2.2" - // Eclair OS would return "2.1", "2.0.1", or "2.0" - // Version can also return update level "2.1-update1" - // - // BlackBerry: Torch 9800 using OS 6.0 would return "6.0.0.600" - // - // Browser: Returns version number for the browser - // - // iPhone: iOS 3.2 returns "3.2" - // - // Windows Phone 7: returns current OS version number, ex. on Mango returns 7.10.7720 - // Tizen: returns "TIZEN_20120425_2" - var deviceVersion = device.version; diff --git a/plugins/cordova-plugin-device/package.json b/plugins/cordova-plugin-device/package.json deleted file mode 100644 index 5c465ad..0000000 --- a/plugins/cordova-plugin-device/package.json +++ /dev/null @@ -1,84 +0,0 @@ -{ - "_from": "cordova-plugin-device@^2.0.2", - "_id": "cordova-plugin-device@2.0.2", - "_inBundle": false, - "_integrity": "sha1-/Ajzci5n7ve2xnv8mag99q3Quro=", - "_location": "/cordova-plugin-device", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "cordova-plugin-device@^2.0.2", - "name": "cordova-plugin-device", - "escapedName": "cordova-plugin-device", - "rawSpec": "^2.0.2", - "saveSpec": null, - "fetchSpec": "^2.0.2" - }, - "_requiredBy": [ - "#USER", - "/" - ], - "_resolved": "https://registry.npmjs.org/cordova-plugin-device/-/cordova-plugin-device-2.0.2.tgz", - "_shasum": "fc08f3722e67eef7b6c67bfc99a83df6add0baba", - "_spec": "cordova-plugin-device@^2.0.2", - "_where": "/home/thrrgilag/workspace/cordova/Goober", - "author": { - "name": "Apache Software Foundation" - }, - "bugs": { - "url": "https://issues.apache.org/jira/browse/CB" - }, - "bundleDependencies": false, - "cordova": { - "id": "cordova-plugin-device", - "platforms": [ - "android", - "ios", - "windows", - "browser", - "osx" - ] - }, - "deprecated": false, - "description": "Cordova Device Plugin", - "devDependencies": { - "eslint": "^3.19.0", - "eslint-config-semistandard": "^11.0.0", - "eslint-config-standard": "^10.2.1", - "eslint-plugin-import": "^2.3.0", - "eslint-plugin-node": "^5.0.0", - "eslint-plugin-promise": "^3.5.0", - "eslint-plugin-standard": "^3.0.1" - }, - "engines": { - "cordovaDependencies": { - "3.0.0": { - "cordova": ">100" - } - } - }, - "homepage": "https://github.com/apache/cordova-plugin-device#readme", - "keywords": [ - "cordova", - "device", - "ecosystem:cordova", - "cordova-android", - "cordova-ios", - "cordova-windows", - "cordova-browser", - "cordova-osx" - ], - "license": "Apache-2.0", - "name": "cordova-plugin-device", - "repository": { - "type": "git", - "url": "git+https://github.com/apache/cordova-plugin-device.git" - }, - "scripts": { - "eslint": "node node_modules/eslint/bin/eslint www && node node_modules/eslint/bin/eslint src && node node_modules/eslint/bin/eslint tests", - "test": "npm run eslint" - }, - "types": "./types/index.d.ts", - "version": "2.0.2" -} diff --git a/plugins/cordova-plugin-device/plugin.xml b/plugins/cordova-plugin-device/plugin.xml deleted file mode 100644 index 7f60024..0000000 --- a/plugins/cordova-plugin-device/plugin.xml +++ /dev/null @@ -1,93 +0,0 @@ - - - - - Device - Cordova Device Plugin - Apache 2.0 - cordova,device - https://git-wip-us.apache.org/repos/asf/cordova-plugin-device.git - https://issues.apache.org/jira/browse/CB/component/12320648 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/plugins/cordova-plugin-device/src/android/Device.java b/plugins/cordova-plugin-device/src/android/Device.java deleted file mode 100644 index e9efcb4..0000000 --- a/plugins/cordova-plugin-device/src/android/Device.java +++ /dev/null @@ -1,174 +0,0 @@ -/* - 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.device; - -import java.util.TimeZone; - -import org.apache.cordova.CordovaWebView; -import org.apache.cordova.CallbackContext; -import org.apache.cordova.CordovaPlugin; -import org.apache.cordova.CordovaInterface; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import android.provider.Settings; - -public class Device extends CordovaPlugin { - public static final String TAG = "Device"; - - public static String platform; // Device OS - public static String uuid; // Device UUID - - private static final String ANDROID_PLATFORM = "Android"; - private static final String AMAZON_PLATFORM = "amazon-fireos"; - private static final String AMAZON_DEVICE = "Amazon"; - - /** - * Constructor. - */ - public Device() { - } - - /** - * Sets the context of the Command. This can then be used to do things like - * get file paths associated with the Activity. - * - * @param cordova The context of the main Activity. - * @param webView The CordovaWebView Cordova is running in. - */ - public void initialize(CordovaInterface cordova, CordovaWebView webView) { - super.initialize(cordova, webView); - Device.uuid = getUuid(); - } - - /** - * 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 True if the action was valid, false if not. - */ - public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { - if ("getDeviceInfo".equals(action)) { - JSONObject r = new JSONObject(); - r.put("uuid", Device.uuid); - r.put("version", this.getOSVersion()); - r.put("platform", this.getPlatform()); - r.put("model", this.getModel()); - r.put("manufacturer", this.getManufacturer()); - r.put("isVirtual", this.isVirtual()); - r.put("serial", this.getSerialNumber()); - callbackContext.success(r); - } - else { - return false; - } - return true; - } - - //-------------------------------------------------------------------------- - // LOCAL METHODS - //-------------------------------------------------------------------------- - - /** - * Get the OS name. - * - * @return - */ - public String getPlatform() { - String platform; - if (isAmazonDevice()) { - platform = AMAZON_PLATFORM; - } else { - platform = ANDROID_PLATFORM; - } - return platform; - } - - /** - * Get the device's Universally Unique Identifier (UUID). - * - * @return - */ - public String getUuid() { - String uuid = Settings.Secure.getString(this.cordova.getActivity().getContentResolver(), android.provider.Settings.Secure.ANDROID_ID); - return uuid; - } - - public String getModel() { - String model = android.os.Build.MODEL; - return model; - } - - public String getProductName() { - String productname = android.os.Build.PRODUCT; - return productname; - } - - public String getManufacturer() { - String manufacturer = android.os.Build.MANUFACTURER; - return manufacturer; - } - - public String getSerialNumber() { - String serial = android.os.Build.SERIAL; - return serial; - } - - /** - * Get the OS version. - * - * @return - */ - public String getOSVersion() { - String osversion = android.os.Build.VERSION.RELEASE; - return osversion; - } - - public String getSDKVersion() { - @SuppressWarnings("deprecation") - String sdkversion = android.os.Build.VERSION.SDK; - return sdkversion; - } - - public String getTimeZoneID() { - TimeZone tz = TimeZone.getDefault(); - return (tz.getID()); - } - - /** - * Function to check if the device is manufactured by Amazon - * - * @return - */ - public boolean isAmazonDevice() { - if (android.os.Build.MANUFACTURER.equals(AMAZON_DEVICE)) { - return true; - } - return false; - } - - public boolean isVirtual() { - return android.os.Build.FINGERPRINT.contains("generic") || - android.os.Build.PRODUCT.contains("sdk"); - } - -} diff --git a/plugins/cordova-plugin-device/src/browser/DeviceProxy.js b/plugins/cordova-plugin-device/src/browser/DeviceProxy.js deleted file mode 100644 index 4dc80ec..0000000 --- a/plugins/cordova-plugin-device/src/browser/DeviceProxy.js +++ /dev/null @@ -1,84 +0,0 @@ -/* - * - * 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 browser = require('cordova/platform'); - -function getPlatform () { - return 'browser'; -} - -function getModel () { - return getBrowserInfo(true); -} - -function getVersion () { - return getBrowserInfo(false); -} - -function getBrowserInfo (getModel) { - var userAgent = navigator.userAgent; - var returnVal = ''; - var offset; - - if ((offset = userAgent.indexOf('Edge')) !== -1) { - returnVal = (getModel) ? 'Edge' : userAgent.substring(offset + 5); - } else if ((offset = userAgent.indexOf('Chrome')) !== -1) { - returnVal = (getModel) ? 'Chrome' : userAgent.substring(offset + 7); - } else if ((offset = userAgent.indexOf('Safari')) !== -1) { - if (getModel) { - returnVal = 'Safari'; - } else { - returnVal = userAgent.substring(offset + 7); - - if ((offset = userAgent.indexOf('Version')) !== -1) { - returnVal = userAgent.substring(offset + 8); - } - } - } else if ((offset = userAgent.indexOf('Firefox')) !== -1) { - returnVal = (getModel) ? 'Firefox' : userAgent.substring(offset + 8); - } else if ((offset = userAgent.indexOf('MSIE')) !== -1) { - returnVal = (getModel) ? 'MSIE' : userAgent.substring(offset + 5); - } else if ((offset = userAgent.indexOf('Trident')) !== -1) { - returnVal = (getModel) ? 'MSIE' : '11'; - } - - if ((offset = returnVal.indexOf(';')) !== -1 || (offset = returnVal.indexOf(' ')) !== -1) { - returnVal = returnVal.substring(0, offset); - } - - return returnVal; -} - -module.exports = { - getDeviceInfo: function (success, error) { - setTimeout(function () { - success({ - cordova: browser.cordovaVersion, - platform: getPlatform(), - model: getModel(), - version: getVersion(), - uuid: null, - isVirtual: false - }); - }, 0); - } -}; - -require('cordova/exec/proxy').add('Device', module.exports); diff --git a/plugins/cordova-plugin-device/src/ios/CDVDevice.h b/plugins/cordova-plugin-device/src/ios/CDVDevice.h deleted file mode 100644 index a146d88..0000000 --- a/plugins/cordova-plugin-device/src/ios/CDVDevice.h +++ /dev/null @@ -1,30 +0,0 @@ -/* - 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 - -@interface CDVDevice : CDVPlugin -{} - -+ (NSString*)cordovaVersion; - -- (void)getDeviceInfo:(CDVInvokedUrlCommand*)command; - -@end diff --git a/plugins/cordova-plugin-device/src/ios/CDVDevice.m b/plugins/cordova-plugin-device/src/ios/CDVDevice.m deleted file mode 100644 index 4d75a57..0000000 --- a/plugins/cordova-plugin-device/src/ios/CDVDevice.m +++ /dev/null @@ -1,112 +0,0 @@ -/* - 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 -#include -#include "TargetConditionals.h" - -#import -#import "CDVDevice.h" - -@implementation UIDevice (ModelVersion) - -- (NSString*)modelVersion -{ - size_t size; - - sysctlbyname("hw.machine", NULL, &size, NULL, 0); - char* machine = malloc(size); - sysctlbyname("hw.machine", machine, &size, NULL, 0); - NSString* platform = [NSString stringWithUTF8String:machine]; - free(machine); - - return platform; -} - -@end - -@interface CDVDevice () {} -@end - -@implementation CDVDevice - -- (NSString*)uniqueAppInstanceIdentifier:(UIDevice*)device -{ - NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults]; - static NSString* UUID_KEY = @"CDVUUID"; - - // Check user defaults first to maintain backwards compaitibility with previous versions - // which didn't user identifierForVendor - NSString* app_uuid = [userDefaults stringForKey:UUID_KEY]; - if (app_uuid == nil) { - if ([device respondsToSelector:@selector(identifierForVendor)]) { - app_uuid = [[device identifierForVendor] UUIDString]; - } else { - CFUUIDRef uuid = CFUUIDCreate(NULL); - app_uuid = (__bridge_transfer NSString *)CFUUIDCreateString(NULL, uuid); - CFRelease(uuid); - } - - [userDefaults setObject:app_uuid forKey:UUID_KEY]; - [userDefaults synchronize]; - } - - return app_uuid; -} - -- (void)getDeviceInfo:(CDVInvokedUrlCommand*)command -{ - NSDictionary* deviceProperties = [self deviceProperties]; - CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:deviceProperties]; - - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; -} - -- (NSDictionary*)deviceProperties -{ - UIDevice* device = [UIDevice currentDevice]; - - return @{ - @"manufacturer": @"Apple", - @"model": [device modelVersion], - @"platform": @"iOS", - @"version": [device systemVersion], - @"uuid": [self uniqueAppInstanceIdentifier:device], - @"cordova": [[self class] cordovaVersion], - @"isVirtual": @([self isVirtual]) - }; -} - -+ (NSString*)cordovaVersion -{ - return CDV_VERSION; -} - -- (BOOL)isVirtual -{ - #if TARGET_OS_SIMULATOR - return true; - #elif TARGET_IPHONE_SIMULATOR - return true; - #else - return false; - #endif -} - -@end diff --git a/plugins/cordova-plugin-device/src/osx/CDVDevice.h b/plugins/cordova-plugin-device/src/osx/CDVDevice.h deleted file mode 100644 index 9def254..0000000 --- a/plugins/cordova-plugin-device/src/osx/CDVDevice.h +++ /dev/null @@ -1,28 +0,0 @@ -/* - 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 CDVDevice : CDVPlugin - -+ (NSString*) cordovaVersion; - -- (void) getDeviceInfo:(CDVInvokedUrlCommand*)command; - -@end diff --git a/plugins/cordova-plugin-device/src/osx/CDVDevice.m b/plugins/cordova-plugin-device/src/osx/CDVDevice.m deleted file mode 100644 index 3a63588..0000000 --- a/plugins/cordova-plugin-device/src/osx/CDVDevice.m +++ /dev/null @@ -1,113 +0,0 @@ -/* - 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 - -#import "CDVDevice.h" - -#define SYSTEM_VERSION_PLIST @"/System/Library/CoreServices/SystemVersion.plist" - -@implementation CDVDevice - -- (NSString*) modelVersion { - size_t size; - - sysctlbyname("hw.machine", NULL, &size, NULL, 0); - char* machine = malloc(size); - sysctlbyname("hw.machine", machine, &size, NULL, 0); - NSString* modelVersion = [NSString stringWithUTF8String:machine]; - free(machine); - - return modelVersion; -} - - -- (NSString*) getSerialNr { - NSString* serialNr; - io_service_t platformExpert = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("IOPlatformExpertDevice")); - if (platformExpert) { - CFTypeRef serialNumberAsCFString = - IORegistryEntryCreateCFProperty(platformExpert, - CFSTR(kIOPlatformSerialNumberKey), - kCFAllocatorDefault, 0); - if (serialNumberAsCFString) { - serialNr = (__bridge NSString*) serialNumberAsCFString; - } - IOObjectRelease(platformExpert); - } - return serialNr; -} - -- (NSString*) uniqueAppInstanceIdentifier { - NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults]; - static NSString* UUID_KEY = @"CDVUUID"; - - NSString* app_uuid = [userDefaults stringForKey:UUID_KEY]; - - if (app_uuid == nil) { - CFUUIDRef uuidRef = CFUUIDCreate(kCFAllocatorDefault); - CFStringRef uuidString = CFUUIDCreateString(kCFAllocatorDefault, uuidRef); - - app_uuid = [NSString stringWithString:(__bridge NSString*) uuidString]; - [userDefaults setObject:app_uuid forKey:UUID_KEY]; - [userDefaults synchronize]; - - CFRelease(uuidString); - CFRelease(uuidRef); - } - - return app_uuid; -} - -- (NSString*) platform { - return [NSDictionary dictionaryWithContentsOfFile:SYSTEM_VERSION_PLIST][@"ProductName"]; -} - -- (NSString*) systemVersion { - return [NSDictionary dictionaryWithContentsOfFile:SYSTEM_VERSION_PLIST][@"ProductVersion"]; -} - -- (void) getDeviceInfo:(CDVInvokedUrlCommand*) command { - NSDictionary* deviceProperties = [self deviceProperties]; - CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:deviceProperties]; - - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; -} - -- (NSDictionary*) deviceProperties { - NSMutableDictionary* devProps = [NSMutableDictionary dictionaryWithCapacity:4]; - - devProps[@"manufacturer"] = @"Apple"; - devProps[@"model"] = [self modelVersion]; - devProps[@"platform"] = [self platform]; - devProps[@"version"] = [self systemVersion]; - devProps[@"uuid"] = [self uniqueAppInstanceIdentifier]; - devProps[@"cordova"] = [[self class] cordovaVersion]; - devProps[@"serial"] = [self getSerialNr]; - devProps[@"isVirtual"] = @NO; - - NSDictionary* devReturn = [NSDictionary dictionaryWithDictionary:devProps]; - return devReturn; -} - -+ (NSString*) cordovaVersion { - return CDV_VERSION; -} - -@end diff --git a/plugins/cordova-plugin-device/src/windows/DeviceProxy.js b/plugins/cordova-plugin-device/src/windows/DeviceProxy.js deleted file mode 100644 index ccaaaee..0000000 --- a/plugins/cordova-plugin-device/src/windows/DeviceProxy.js +++ /dev/null @@ -1,96 +0,0 @@ -/* - * - * 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, createUUID */ - -var ROOT_CONTAINER = '{00000000-0000-0000-FFFF-FFFFFFFFFFFF}'; -var DEVICE_CLASS_KEY = '{A45C254E-DF1C-4EFD-8020-67D146A850E0},10'; -var DEVICE_CLASS_KEY_NO_SEMICOLON = '{A45C254E-DF1C-4EFD-8020-67D146A850E0}10'; -var ROOT_CONTAINER_QUERY = 'System.Devices.ContainerId:="' + ROOT_CONTAINER + '"'; -var HAL_DEVICE_CLASS = '4d36e966-e325-11ce-bfc1-08002be10318'; -var DEVICE_DRIVER_VERSION_KEY = '{A8B865DD-2E3D-4094-AD97-E593A70C75D6},3'; - -module.exports = { - - getDeviceInfo: function (win, fail, args) { - - // deviceId aka uuid, stored in Windows.Storage.ApplicationData.current.localSettings.values.deviceId - var deviceId; - // get deviceId, or create and store one - var localSettings = Windows.Storage.ApplicationData.current.localSettings; - if (localSettings.values.deviceId) { - deviceId = localSettings.values.deviceId; - } else { - // App-specific hardware id could be used as uuid, but it changes if the hardware changes... - try { - var ASHWID = Windows.System.Profile.HardwareIdentification.getPackageSpecificToken(null).id; - deviceId = Windows.Storage.Streams.DataReader.fromBuffer(ASHWID).readGuid(); - } catch (e) { - // Couldn't get the hardware UUID - deviceId = createUUID(); - } - // ...so cache it per-install - localSettings.values.deviceId = deviceId; - } - - var userAgent = window.clientInformation.userAgent; - // this will report "windows" in windows8.1 and windows phone 8.1 apps - // and "windows8" in windows 8.0 apps similar to cordova.js - // See https://github.com/apache/cordova-js/blob/master/src/windows/platform.js#L25 - var devicePlatform = userAgent.indexOf('MSAppHost/1.0') === -1 ? 'windows' : 'windows8'; - var versionString = userAgent.match(/Windows (?:Phone |NT )?([0-9.]+)/)[1]; - - var deviceInfo = new Windows.Security.ExchangeActiveSyncProvisioning.EasClientDeviceInformation(); - // Running in the Windows Simulator is a remote session. - // Running in the Windows Phone Emulator has the systemProductName set to "Virtual" - var isVirtual = Windows.System.RemoteDesktop.InteractiveSession.isRemote || deviceInfo.systemProductName === 'Virtual'; - var manufacturer = deviceInfo.systemManufacturer; - var model = deviceInfo.systemProductName; - - var Pnp = Windows.Devices.Enumeration.Pnp; - - Pnp.PnpObject.findAllAsync(Pnp.PnpObjectType.device, - [DEVICE_DRIVER_VERSION_KEY, DEVICE_CLASS_KEY], - ROOT_CONTAINER_QUERY) - .then(function (rootDevices) { - for (var i = 0; i < rootDevices.length; i++) { - var rootDevice = rootDevices[i]; - if (!rootDevice.properties) continue; - if (rootDevice.properties[DEVICE_CLASS_KEY_NO_SEMICOLON] === HAL_DEVICE_CLASS) { - versionString = rootDevice.properties[DEVICE_DRIVER_VERSION_KEY]; - break; - } - } - - setTimeout(function () { - win({ platform: devicePlatform, - version: versionString, - uuid: deviceId, - isVirtual: isVirtual, - model: model, - manufacturer: manufacturer}); - }, 0); - }); - } - -}; // exports - -require('cordova/exec/proxy').add('Device', module.exports); diff --git a/plugins/cordova-plugin-device/tests/package.json b/plugins/cordova-plugin-device/tests/package.json deleted file mode 100644 index 0fa9978..0000000 --- a/plugins/cordova-plugin-device/tests/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "cordova-plugin-device-tests", - "version": "1.1.6-dev", - "description": "", - "cordova": { - "id": "cordova-plugin-device-tests", - "platforms": [] - }, - "keywords": [ - "ecosystem:cordova" - ], - "author": "", - "license": "Apache 2.0" -} diff --git a/plugins/cordova-plugin-device/tests/plugin.xml b/plugins/cordova-plugin-device/tests/plugin.xml deleted file mode 100644 index afb700b..0000000 --- a/plugins/cordova-plugin-device/tests/plugin.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - - Cordova Device Plugin Tests - Apache 2.0 - - - - diff --git a/plugins/cordova-plugin-device/tests/tests.js b/plugins/cordova-plugin-device/tests/tests.js deleted file mode 100644 index 03e1fc7..0000000 --- a/plugins/cordova-plugin-device/tests/tests.js +++ /dev/null @@ -1,113 +0,0 @@ -/* - * - * 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. - * -*/ - -/* eslint-env jasmine */ - -exports.defineAutoTests = function () { - describe('Device Information (window.device)', function () { - it('should exist', function () { - expect(window.device).toBeDefined(); - }); - - it('should contain a platform specification that is a string', function () { - expect(window.device.platform).toBeDefined(); - expect((String(window.device.platform)).length > 0).toBe(true); - }); - - it('should contain a version specification that is a string', function () { - expect(window.device.version).toBeDefined(); - expect((String(window.device.version)).length > 0).toBe(true); - }); - - it('should contain a UUID specification that is a string or a number', function () { - expect(window.device.uuid).toBeDefined(); - if (typeof window.device.uuid === 'string' || typeof window.device.uuid === 'object') { - expect((String(window.device.uuid)).length > 0).toBe(true); - } else { - expect(window.device.uuid > 0).toBe(true); - } - }); - - it('should contain a cordova specification that is a string', function () { - expect(window.device.cordova).toBeDefined(); - expect((String(window.device.cordova)).length > 0).toBe(true); - }); - - it('should depend on the presence of cordova.version string', function () { - expect(window.cordova.version).toBeDefined(); - expect((String(window.cordova.version)).length > 0).toBe(true); - }); - - it('should contain device.cordova equal to cordova.version', function () { - expect(window.device.cordova).toBe(window.cordova.version); - }); - - it('should contain a model specification that is a string', function () { - expect(window.device.model).toBeDefined(); - expect((String(window.device.model)).length > 0).toBe(true); - }); - - it('should contain a manufacturer property that is a string', function () { - expect(window.device.manufacturer).toBeDefined(); - expect((String(window.device.manufacturer)).length > 0).toBe(true); - }); - - it('should contain an isVirtual property that is a boolean', function () { - expect(window.device.isVirtual).toBeDefined(); - expect(typeof window.device.isVirtual).toBe('boolean'); - }); - - it('should contain a serial number specification that is a string', function () { - expect(window.device.serial).toBeDefined(); - expect((String(window.device.serial)).length > 0).toBe(true); - - }); - - }); -}; - -exports.defineManualTests = function (contentEl, createActionButton) { - var logMessage = function (message, color) { - var log = document.getElementById('info'); - var logLine = document.createElement('div'); - if (color) { - logLine.style.color = color; - } - logLine.innerHTML = message; - log.appendChild(logLine); - }; - - var clearLog = function () { - var log = document.getElementById('info'); - log.innerHTML = ''; - }; - - var device_tests = '

Press Dump Device button to get device information

' + - '
' + - 'Expected result: Status box will get updated with device info. (i.e. platform, version, uuid, model, etc)'; - - contentEl.innerHTML = '
' + device_tests; - - createActionButton('Dump device', function () { - clearLog(); - logMessage(JSON.stringify(window.device, null, '\t')); - }, 'dump_device'); -}; diff --git a/plugins/cordova-plugin-device/types/index.d.ts b/plugins/cordova-plugin-device/types/index.d.ts deleted file mode 100644 index d4450b4..0000000 --- a/plugins/cordova-plugin-device/types/index.d.ts +++ /dev/null @@ -1,36 +0,0 @@ -// Type definitions for Apache Cordova Device plugin -// Project: https://github.com/apache/cordova-plugin-device -// Definitions by: Microsoft Open Technologies Inc -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// -// Copyright (c) Microsoft Open Technologies Inc -// Licensed under the MIT license - -/** - * This plugin defines a global device object, which describes the device's hardware and software. - * Although the object is in the global scope, it is not available until after the deviceready event. - */ -interface Device { - /** Get the version of Cordova running on the device. */ - cordova: string; - /** Indicates that Cordova initialize successfully. */ - available: boolean; - /** - * The device.model returns the name of the device's model or product. The value is set - * by the device manufacturer and may be different across versions of the same product. - */ - model: string; - /** Get the device's operating system name. */ - platform: string; - /** Get the device's Universally Unique Identifier (UUID). */ - uuid: string; - /** Get the operating system version. */ - version: string; - /** Get the device's manufacturer. */ - manufacturer: string; - /** Whether the device is running on a simulator. */ - isVirtual: boolean; - /** Get the device hardware serial number. */ - serial: string;} - -declare var device: Device; \ No newline at end of file diff --git a/plugins/cordova-plugin-file-transfer/CONTRIBUTING.md b/plugins/cordova-plugin-file-transfer/CONTRIBUTING.md deleted file mode 100644 index 4c8e6a5..0000000 --- a/plugins/cordova-plugin-file-transfer/CONTRIBUTING.md +++ /dev/null @@ -1,37 +0,0 @@ - - -# 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-transfer/LICENSE b/plugins/cordova-plugin-file-transfer/LICENSE deleted file mode 100644 index 7a4a3ea..0000000 --- a/plugins/cordova-plugin-file-transfer/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - 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-transfer/NOTICE b/plugins/cordova-plugin-file-transfer/NOTICE deleted file mode 100644 index 46fed23..0000000 --- a/plugins/cordova-plugin-file-transfer/NOTICE +++ /dev/null @@ -1,8 +0,0 @@ -Apache Cordova -Copyright 2012 The Apache Software Foundation - -This product includes software developed at -The Apache Software Foundation (http://www.apache.org/). - -This product includes a copy of OkHttp from: -https://github.com/square/okhttp diff --git a/plugins/cordova-plugin-file-transfer/README.md b/plugins/cordova-plugin-file-transfer/README.md deleted file mode 100644 index b637446..0000000 --- a/plugins/cordova-plugin-file-transfer/README.md +++ /dev/null @@ -1,598 +0,0 @@ ---- -title: File Transfer -description: Upload and download files. ---- - - -|AppVeyor|Travis CI| -|:-:|:-:| -|[![Build status](https://ci.appveyor.com/api/projects/status/github/apache/cordova-plugin-file-transfer?branch=master)](https://ci.appveyor.com/project/ApacheSoftwareFoundation/cordova-plugin-file-transfer)|[![Build Status](https://travis-ci.org/apache/cordova-plugin-file-transfer.svg?branch=master)](https://travis-ci.org/apache/cordova-plugin-file-transfer)| - -# cordova-plugin-file-transfer - -This plugin allows you to upload and download files. - -This plugin defines global `FileTransfer`, `FileUploadOptions` constructors. Although in the global scope, they are not available until after the `deviceready` event. - -```js -document.addEventListener("deviceready", onDeviceReady, false); -function onDeviceReady() { - console.log(FileTransfer); -} -``` - -> To get a few ideas, check out the [sample](#sample) at the bottom of this page. - -Report issues with this plugin 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%20Transfer%22%20ORDER%20BY%20priority%20DESC%2C%20summary%20ASC%2C%20updatedDate%20DESC) - -## Deprecated - -With the new features introduced in [XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest), this plugin is not needed any more. Migrating from this plugin to using the new features of [XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest), is explained in this [Cordova blog post](https://cordova.apache.org/blog/2017/10/18/from-filetransfer-to-xhr2.html). - -## Installation - -```bash -cordova plugin add cordova-plugin-file-transfer -``` - -## Supported Platforms - -- Amazon Fire OS -- Android -- BlackBerry 10 -- Browser -- Firefox OS** -- iOS -- Windows Phone 7 and 8* -- Windows - -\* _Do not support `onprogress` nor `abort()`_ - -\** _Do not support `onprogress`_ - -# FileTransfer - -The `FileTransfer` object provides a way to upload files using an HTTP -multi-part POST or PUT request, and to download files. - -## Properties - -- __onprogress__: Called with a `ProgressEvent` whenever a new chunk of data is transferred. _(Function)_ - -## Methods - -- __upload__: Sends a file to a server. - -- __download__: Downloads a file from server. - -- __abort__: Aborts an in-progress transfer. - - -## upload - -__Parameters__: - -- __fileURL__: Filesystem URL representing the file on the device or a [data URI](https://en.wikipedia.org/wiki/Data_URI_scheme). For backwards compatibility, this can also be the full path of the file on the device. (See [Backwards Compatibility Notes](#backwards-compatibility-notes) below) - -- __server__: URL of the server to receive the file, as encoded by `encodeURI()`. - -- __successCallback__: A callback that is passed a `FileUploadResult` object. _(Function)_ - -- __errorCallback__: A callback that executes if an error occurs retrieving the `FileUploadResult`. Invoked with a `FileTransferError` object. _(Function)_ - -- __options__: Optional parameters _(Object)_. Valid keys: - - __fileKey__: The name of the form element. Defaults to `file`. (DOMString) - - __fileName__: The file name to use when saving the file on the server. Defaults to `image.jpg`. (DOMString) - - __httpMethod__: The HTTP method to use - either `PUT` or `POST`. Defaults to `POST`. (DOMString) - - __mimeType__: The mime type of the data to upload. Defaults to `image/jpeg`. (DOMString) - - __params__: A set of optional key/value pairs to pass in the HTTP request. (Object, key/value - DOMString) - - __chunkedMode__: Whether to upload the data in chunked streaming mode. Defaults to `true`. (Boolean) - - __headers__: A map of header name/header values. Use a hash to specify one or more than one value. On iOS, FireOS, and Android, if a header named Content-Type is present, multipart form data will NOT be used. (Object) - -- __trustAllHosts__: Optional parameter, defaults to `false`. If set to `true`, it accepts all security certificates. Not recommended for production use. Supported on iOS. _(boolean)_ - -### Example - -```js -// !! Assumes variable fileURL contains a valid URL to a text file on the device, -// for example, cdvfile://localhost/persistent/path/to/file.txt - -var win = function (r) { - console.log("Code = " + r.responseCode); - console.log("Response = " + r.response); - console.log("Sent = " + r.bytesSent); -} - -var fail = function (error) { - alert("An error has occurred: Code = " + error.code); - console.log("upload error source " + error.source); - console.log("upload error target " + error.target); -} - -var options = new FileUploadOptions(); -options.fileKey = "file"; -options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1); -options.mimeType = "text/plain"; - -var params = {}; -params.value1 = "test"; -params.value2 = "param"; - -options.params = params; - -var ft = new FileTransfer(); -ft.upload(fileURL, encodeURI("http://some.server.com/upload.php"), win, fail, options); -``` - -### Example with Upload Headers and Progress Events (Android and iOS only) - -```js -function win(r) { - console.log("Code = " + r.responseCode); - console.log("Response = " + r.response); - console.log("Sent = " + r.bytesSent); -} - -function fail(error) { - alert("An error has occurred: Code = " + error.code); - console.log("upload error source " + error.source); - console.log("upload error target " + error.target); -} - -var uri = encodeURI("http://some.server.com/upload.php"); - -var options = new FileUploadOptions(); -options.fileKey="file"; -options.fileName=fileURL.substr(fileURL.lastIndexOf('/')+1); -options.mimeType="text/plain"; - -var headers={'headerParam':'headerValue', 'headerParam2':'headerValue2'}; - -options.headers = headers; - -var ft = new FileTransfer(); -ft.onprogress = function(progressEvent) { - if (progressEvent.lengthComputable) { - loadingStatus.setPercentage(progressEvent.loaded / progressEvent.total); - } else { - loadingStatus.increment(); - } -}; -ft.upload(fileURL, uri, win, fail, options); -``` - -## FileUploadResult - -A `FileUploadResult` object is passed to the success callback of the -`FileTransfer` object's `upload()` method. - -### Properties - -- __bytesSent__: The number of bytes sent to the server as part of the upload. (long) - -- __responseCode__: The HTTP response code returned by the server. (long) - -- __response__: The HTTP response returned by the server. (DOMString) - -- __headers__: The HTTP response headers by the server. (Object) - - Currently supported on iOS only. - -### iOS Quirks - -- Does not support `responseCode` or `bytesSent`. - -- Does not support uploads of an empty file with __chunkedMode=true__ and `multipartMode=false`. - -### Browser Quirks - -- __withCredentials__: _boolean_ that tells the browser to set the withCredentials flag on the XMLHttpRequest - -### Windows Quirks - -- An option parameter with empty/null value is excluded in the upload operation due to the Windows API design. - -- __chunkedMode__ is not supported and all uploads are set to non-chunked mode. - -## download - -__Parameters__: - -- __source__: URL of the server to download the file, as encoded by `encodeURI()`. - -- __target__: Filesystem url representing the file on the device. For backwards compatibility, this can also be the full path of the file on the device. (See [Backwards Compatibility Notes](#backwards-compatibility-notes) below) - -- __successCallback__: A callback that is passed a `FileEntry` object. _(Function)_ - -- __errorCallback__: A callback that executes if an error occurs when retrieving the `FileEntry`. Invoked with a `FileTransferError` object. _(Function)_ - -- __trustAllHosts__: Optional parameter, defaults to `false`. If set to `true`, it accepts all security certificates. Not recommended for production use. Supported on iOS. _(boolean)_ - -- __options__: Optional parameters, currently only supports headers (such as Authorization (Basic Authentication), etc). - -### Example - -```js -// !! Assumes variable fileURL contains a valid URL to a path on the device, -// for example, cdvfile://localhost/persistent/path/to/downloads/ - -var fileTransfer = new FileTransfer(); -var uri = encodeURI("http://some.server.com/download.php"); - -fileTransfer.download( - uri, - fileURL, - function(entry) { - console.log("download complete: " + entry.toURL()); - }, - function(error) { - console.log("download error source " + error.source); - console.log("download error target " + error.target); - console.log("download error code" + error.code); - }, - false, - { - headers: { - "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA==" - } - } -); -``` - -### WP8 Quirks - -- Download requests is being cached by native implementation. To avoid caching, pass `if-Modified-Since` header to download method. - -### Browser Quirks - -- __withCredentials__: _boolean_ that tells the browser to set the withCredentials flag on the XMLHttpRequest - -## abort - -Aborts an in-progress transfer. The onerror callback is passed a FileTransferError object which has an error code of `FileTransferError.ABORT_ERR`. - -### Example - -```js -// !! Assumes variable fileURL contains a valid URL to a text file on the device, -// for example, cdvfile://localhost/persistent/path/to/file.txt - -var win = function(r) { - console.log("Should not be called."); -} - -var fail = function(error) { - // error.code == FileTransferError.ABORT_ERR - alert("An error has occurred: Code = " + error.code); - console.log("upload error source " + error.source); - console.log("upload error target " + error.target); -} - -var options = new FileUploadOptions(); -options.fileKey="file"; -options.fileName="myphoto.jpg"; -options.mimeType="image/jpeg"; - -var ft = new FileTransfer(); -ft.upload(fileURL, encodeURI("http://some.server.com/upload.php"), win, fail, options); -ft.abort(); -``` - -## FileTransferError - -A `FileTransferError` object is passed to an error callback when an error occurs. - -### Properties - -- __code__: One of the predefined error codes listed below. (Number) - -- __source__: URL to the source. (String) - -- __target__: URL to the target. (String) - -- __http_status__: HTTP status code. This attribute is only available when a response code is received from the HTTP connection. (Number) - -- __body__ Response body. This attribute is only available when a response is received from the HTTP connection. (String) - -- __exception__: Either e.getMessage or e.toString (String) - -### iOS Quirks - -__exception__ is never defined. - -### Constants - -- 1 = `FileTransferError.FILE_NOT_FOUND_ERR` -- 2 = `FileTransferError.INVALID_URL_ERR` -- 3 = `FileTransferError.CONNECTION_ERR` -- 4 = `FileTransferError.ABORT_ERR` -- 5 = `FileTransferError.NOT_MODIFIED_ERR` - -## Windows Quirks - -- The plugin implementation is based on [BackgroundDownloader](https://msdn.microsoft.com/en-us/library/windows/apps/windows.networking.backgroundtransfer.backgrounddownloader.aspx)/[BackgroundUploader](https://msdn.microsoft.com/en-us/library/windows/apps/windows.networking.backgroundtransfer.backgrounduploader.aspx), which entails the latency issues on Windows devices (creation/starting of an operation can take up to a few seconds). You can use XHR or [HttpClient](https://msdn.microsoft.com/en-us/library/windows/apps/windows.web.http.httpclient.aspx) as a quicker alternative for small downloads. - -## Backwards Compatibility Notes - -Previous versions of this plugin would only accept device-absolute-file-paths as the source for uploads, or as the target for downloads. These paths would typically be of the form: - - /var/mobile/Applications//Documents/path/to/file (iOS) - /storage/emulated/0/path/to/file (Android) - -For backwards compatibility, these paths are still accepted, and if your application has recorded paths like these in persistent storage, then they can continue to be used. - -These paths were previously exposed in the `fullPath` property of `FileEntry` and `DirectoryEntry` objects returned by the File plugin. New versions of the File plugin however, no longer expose these paths to JavaScript. - -If you are upgrading to a new (1.0.0 or newer) version of File, and you have previously been using `entry.fullPath` as arguments to `download()` or `upload()`, then you will need to change your code to use filesystem URLs instead. - -`FileEntry.toURL()` and `DirectoryEntry.toURL()` return a filesystem URL of the form: - - cdvfile://localhost/persistent/path/to/file - -which can be used in place of the absolute file path in both `download()` and `upload()` methods. - -## Sample: Download and Upload Files - -Use the File-Transfer plugin to upload and download files. In these examples, we demonstrate several tasks like: - -* [Downloading a binary file to the application cache](#binaryFile) -* [Uploading a file created in your application's root](#uploadFile) -* [Downloading the uploaded file](#downloadFile) - -## Download a Binary File to the application cache - -Use the File plugin with the File-Transfer plugin to provide a target for the files that you download (the target must be a FileEntry object). Before you download the file, create a DirectoryEntry object by using `resolveLocalFileSystemURL` and calling `fs.root` in the success callback. Use the `getFile` method of DirectoryEntry to create the target file. - -```js -window.requestFileSystem(window.TEMPORARY, 5 * 1024 * 1024, function (fs) { - - console.log('file system open: ' + fs.name); - - // Make sure you add the domain name to the Content-Security-Policy element. - var url = 'http://cordova.apache.org/static/img/cordova_bot.png'; - // Parameters passed to getFile create a new file or return the file if it already exists. - fs.root.getFile('downloaded-image.png', { create: true, exclusive: false }, function (fileEntry) { - download(fileEntry, url, true); - - }, onErrorCreateFile); - -}, onErrorLoadFs); -``` - ->*Note* For persistent storage, pass LocalFileSystem.PERSISTENT to requestFileSystem. - -When you have the FileEntry object, download the file using the `download` method of the FileTransfer object. The 3rd argument to the `download` function of FileTransfer is the success callback, which you can use to call the app's `readBinaryFile` function. In this code example, the `entry` variable is a new FileEntry object that receives the result of the download operation. - -```js -function download(fileEntry, uri, readBinaryData) { - - var fileTransfer = new FileTransfer(); - var fileURL = fileEntry.toURL(); - - fileTransfer.download( - uri, - fileURL, - function (entry) { - console.log("Successful download..."); - console.log("download complete: " + entry.toURL()); - if (readBinaryData) { - // Read the file... - readBinaryFile(entry); - } - else { - // Or just display it. - displayImageByFileURL(entry); - } - }, - function (error) { - console.log("download error source " + error.source); - console.log("download error target " + error.target); - console.log("upload error code" + error.code); - }, - null, // or, pass false - { - //headers: { - // "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA==" - //} - } - ); -} -``` - -If you just need to display the image, take the FileEntry to call its toURL() function. - -```js -function displayImageByFileURL(fileEntry) { - var elem = document.getElementById('imageElement'); - elem.src = fileEntry.toURL(); -} -``` - -Depending on your app requirements, you may want to read the file. To support operations with binary files, FileReader supports two methods, `readAsBinaryString` and `readAsArrayBuffer`. In this example, use `readAsArrayBuffer` and pass the FileEntry object to the method. Once you read the file successfully, construct a Blob object using the result of the read. - -```js -function readBinaryFile(fileEntry) { - fileEntry.file(function (file) { - var reader = new FileReader(); - - reader.onloadend = function() { - - console.log("Successful file read: " + this.result); - // displayFileData(fileEntry.fullPath + ": " + this.result); - - var blob = new Blob([new Uint8Array(this.result)], { type: "image/png" }); - displayImage(blob); - }; - - reader.readAsArrayBuffer(file); - - }, onErrorReadFile); -} -``` - -Once you read the file successfully, you can create a DOM URL string using `createObjectURL`, and then display the image. - -```js -function displayImage(blob) { - - // Note: Use window.URL.revokeObjectURL when finished with image. - var objURL = window.URL.createObjectURL(blob); - - // Displays image if result is a valid DOM string for an image. - var elem = document.getElementById('imageElement'); - elem.src = objURL; -} -``` - -As you saw previously, you can call FileEntry.toURL() instead to just display the downloaded image (skip the file read). - -## Upload a File - -When you upload a File using the File-Transfer plugin, use the File plugin to provide files for upload (again, they must be FileEntry objects). Before you can upload anything, create a file for upload using the `getFile` method of DirectoryEntry. In this example, create the file in the application's cache (fs.root). Then call the app's writeFile function so you have some content to upload. - -```js -function onUploadFile() { - window.requestFileSystem(window.TEMPORARY, 5 * 1024 * 1024, function (fs) { - - console.log('file system open: ' + fs.name); - var fileName = "uploadSource.txt"; - var dirEntry = fs.root; - dirEntry.getFile(fileName, { create: true, exclusive: false }, function (fileEntry) { - - // Write something to the file before uploading it. - writeFile(fileEntry); - - }, onErrorCreateFile); - - }, onErrorLoadFs); -} -``` - -In this example, create some simple content, and then call the app's upload function. - -```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..."); - upload(fileEntry); - }; - - fileWriter.onerror = function (e) { - console.log("Failed file write: " + e.toString()); - }; - - if (!dataObj) { - dataObj = new Blob(['file data to upload'], { type: 'text/plain' }); - } - - fileWriter.write(dataObj); - }); -} -``` - -Forward the FileEntry object to the upload function. To perform the actual upload, use the upload function of the FileTransfer object. - -```js -function upload(fileEntry) { - // !! Assumes variable fileURL contains a valid URL to a text file on the device, - var fileURL = fileEntry.toURL(); - - var success = function (r) { - console.log("Successful upload..."); - console.log("Code = " + r.responseCode); - // displayFileData(fileEntry.fullPath + " (content uploaded to server)"); - } - - var fail = function (error) { - alert("An error has occurred: Code = " + error.code); - } - - var options = new FileUploadOptions(); - options.fileKey = "file"; - options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1); - options.mimeType = "text/plain"; - - var params = {}; - params.value1 = "test"; - params.value2 = "param"; - - options.params = params; - - var ft = new FileTransfer(); - // SERVER must be a URL that can handle the request, like - // http://some.server.com/upload.php - ft.upload(fileURL, encodeURI(SERVER), success, fail, options); -}; -``` - -## Download the uploaded file - -To download the image you just uploaded, you will need a valid URL that can handle the request, for example, http://some.server.com/download.php. Again, the success handler for the FileTransfer.download method receives a FileEntry object. The main difference here from previous examples is that we call FileReader.readAsText to read the result of the download operation, because we uploaded a file with text content. - -```js -function download(fileEntry, uri) { - - var fileTransfer = new FileTransfer(); - var fileURL = fileEntry.toURL(); - - fileTransfer.download( - uri, - fileURL, - function (entry) { - console.log("Successful download..."); - console.log("download complete: " + entry.toURL()); - readFile(entry); - }, - function (error) { - console.log("download error source " + error.source); - console.log("download error target " + error.target); - console.log("upload error code" + error.code); - }, - null, // or, pass false - { - //headers: { - // "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA==" - //} - } - ); -} -``` - -In the readFile function, call the `readAsText` method of the FileReader object. - -```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); -} -``` diff --git a/plugins/cordova-plugin-file-transfer/RELEASENOTES.md b/plugins/cordova-plugin-file-transfer/RELEASENOTES.md deleted file mode 100644 index bcb4fce..0000000 --- a/plugins/cordova-plugin-file-transfer/RELEASENOTES.md +++ /dev/null @@ -1,319 +0,0 @@ - -# Release Notes - -### 1.7.1 (Jan 24, 2018) -* [CB-13749](https://issues.apache.org/jira/browse/CB-13749) Add build-tools-26.0.2 to travis - -### 1.7.0 (Nov 06, 2017) -* Updated `README` with Deprecated Status -* [CB-13472](https://issues.apache.org/jira/browse/CB-13472) (CI) Fixed Travis **Android** builds again -* [CB-12809](https://issues.apache.org/jira/browse/CB-12809) Google Play Blocker: Unsafe SSL TrustManager Defined -* [CB-7995](https://issues.apache.org/jira/browse/CB-7995) document that `FileTransferError.exception` on **iOS** is never defined. -* [CB-13000](https://issues.apache.org/jira/browse/CB-13000) (CI) Speed up **Android** builds -* [CB-12847](https://issues.apache.org/jira/browse/CB-12847) added `bugs` entry to `package.json`. - -### 1.6.3 (Apr 27, 2017) -* [CB-12685](https://issues.apache.org/jira/browse/CB-12685) added `package.json` to tests folder -* [CB-10696](https://issues.apache.org/jira/browse/CB-10696) **iOS**: Encode target path with spaces - -### 1.6.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 - -### 1.6.1 (Dec 07, 2016) -* [CB-12224](https://issues.apache.org/jira/browse/CB-12224) Updated version and RELEASENOTES.md for release 1.6.1 -* [CB-12154](https://issues.apache.org/jira/browse/CB-12154) file-transfer progressEvent.total = -1 on iOS -* [CB-10974](https://issues.apache.org/jira/browse/CB-10974) Cordova file transfer Content-Length header problem -* Don't crash on low memory devices -* [CB-12100](https://issues.apache.org/jira/browse/CB-12100) (ios) Fixed test plugin install at platform add on cordova@6.3.1 -* [CB-11959](https://issues.apache.org/jira/browse/CB-11959) Fixed the jshint issues -* [CB-11959](https://issues.apache.org/jira/browse/CB-11959) Increased the array length for ios and winstore even more -* [CB-11959](https://issues.apache.org/jira/browse/CB-11959) Fixed filetransfer.spec.21 test failure on iOS and Windows Store when using local server -* [CB-11917](https://issues.apache.org/jira/browse/CB-11917) - Remove pull request template checklist item: "iCLA has been submitted…" -* [CB-11926](https://issues.apache.org/jira/browse/CB-11926) Tests can use local server -* [CB-11832](https://issues.apache.org/jira/browse/CB-11832) Incremented plugin version. - -### 1.6.0 (Sep 08, 2016) -* [CB-11795](https://issues.apache.org/jira/browse/CB-11795) Add 'protective' entry to cordovaDependencies -* [CB-9022](https://issues.apache.org/jira/browse/CB-9022) Fix exception thrown by call to `remapApi` on main thread -* Plugin uses `Android Log class` and not `Cordova LOG class` -* [CB-9022](https://issues.apache.org/jira/browse/CB-9022) Resolve source URI on background thread -* [CB-11316](https://issues.apache.org/jira/browse/CB-11316) **windows**: Added `content-type` for files -* Close invalid PRs -* [CB-11497](https://issues.apache.org/jira/browse/CB-11497) Use `cordova-vm` for testing 304 errors -* Add badges for paramedic builds on Jenkins -* documentation with a wrong log message in `fileTransfer.download` function -* added link to sample -* Add pull request template. -* [CB-10974](https://issues.apache.org/jira/browse/CB-10974) Cordova file transfer `Content-Length` header problem -* Add fenced code blocks to help code formatting -* [CB-11165](https://issues.apache.org/jira/browse/CB-11165) removed peer dependency -* [CB-11003](https://issues.apache.org/jira/browse/CB-11003) Adding sample section to documentation. -* [CB-10996](https://issues.apache.org/jira/browse/CB-10996) Adding front matter to README.md - -### 1.5.1 (Apr 15, 2016) -* [CB-10536](https://issues.apache.org/jira/browse/CB-10536) Removing flaky test assertions about abort callback latency -* Removing the expectation in `spec.34` for the transfer method to be called. -* [CB-10978](https://issues.apache.org/jira/browse/CB-10978) Fix `file-transfer.tests` JSHint issues -* [CB-10782](https://issues.apache.org/jira/browse/CB-10782) Occasional failure in file transfer tests causing mobilespec crash -* [CB-10771](https://issues.apache.org/jira/browse/CB-10771) Fixing failure when empty string passed as a value for option parameter in upload function -* [CB-10636](https://issues.apache.org/jira/browse/CB-10636) Add `JSHint` for plugins - -### 1.5.0 (Jan 15, 2016) -* [CB-10208](https://issues.apache.org/jira/browse/CB-10208) Fix `file-transfer` multipart form data upload format on **Windows** -* [CB-9837](https://issues.apache.org/jira/browse/CB-9837) Add data `URI` support to `file-transfer` upload on **iOS** -* [CB-9600](https://issues.apache.org/jira/browse/CB-9600) `FileUploadOptions` params not posted on **iOS** -* [CB-9840](https://issues.apache.org/jira/browse/CB-9840) Fallback `file-transfer` `uploadResponse` encoding to `latin1` in case not encoded with `UTF-8` on **iOS** -* [CB-9840](https://issues.apache.org/jira/browse/CB-9840) Fallback `file-transfer` upload/download response encoding to `latin1` in case not encoded with `UTF-8` on **iOS** -* [CB-8641](https://issues.apache.org/jira/browse/CB-8641) **Windows Phone 8.1** Some `file-transfer` plugin tests occasionally fail in `mobilespec` -* Adding linting and fixing linter warnings. Reducing timeouts to 7 seconds. -* [CB-10100](https://issues.apache.org/jira/browse/CB-10100) updated file dependency to not grab new majors -* [CB-7006](https://issues.apache.org/jira/browse/CB-7006) Empty file is created on file transfer if server response is 304 -* [CB-10098](https://issues.apache.org/jira/browse/CB-10098) `filetransfer.spec.33` is faulty -* [CB-9969](https://issues.apache.org/jira/browse/CB-9969) Filetransfer upload error deletes original file -* [CB-10088](https://issues.apache.org/jira/browse/CB-10088) `filetransfer spec.10` and `spec.11` test is faulty -* [CB-9969](https://issues.apache.org/jira/browse/CB-9969) Filetransfer upload error deletes original file -* [CB-10086](https://issues.apache.org/jira/browse/CB-10086) There are two `spec.31` tests for `file-transfer` tests -* [CB-10037](https://issues.apache.org/jira/browse/CB-10037) Add progress indicator to file-transfer manual tests -* [CB-9563](https://issues.apache.org/jira/browse/CB-9563) Mulptipart form data is used even a header named `Content-Type` is present -* [CB-8863](https://issues.apache.org/jira/browse/CB-8863) fix block usage of self - -### 1.4.0 (Nov 18, 2015) -* [CB-10035](https://issues.apache.org/jira/browse/CB-10035) Updated `RELEASENOTES` to be newest to oldest -* [CB-9879](https://issues.apache.org/jira/browse/CB-9879) `getCookie`s can cause unhandled `NullPointerException` -* [CB-6928](https://issues.apache.org/jira/browse/CB-6928) Wrong behaviour transferring cacheable content -* [CB-51](https://issues.apache.org/jira/browse/CB-51) FileTransfer - Support `PUT` Method -* [CB-9906](https://issues.apache.org/jira/browse/CB-9906) cleanup duplicate code, removed 2nd `isWP8` declaration. -* [CB-9950](https://issues.apache.org/jira/browse/CB-9950) Unpend Filetransfer spec.27 on **wp8** as custom headers are now supported -* [CB-9843](https://issues.apache.org/jira/browse/CB-9843) Added **wp8** quirk to test spec 12 -* Fixing contribute link. -* [CB-8431](https://issues.apache.org/jira/browse/CB-8431) File Transfer tests crash on **Android Lolipop** -* [CB-9790](https://issues.apache.org/jira/browse/CB-9790) Align `FileUploadOptions` `fileName` and `mimeType` default parameter values to the docs on **iOS** -* [CB-9385](https://issues.apache.org/jira/browse/CB-9385) Return `FILE_NOT_FOUND_ERR` when receiving `404` code on **iOS** -* [CB-9791](https://issues.apache.org/jira/browse/CB-9791) Decreased download and upload tests timeout - -### 1.3.0 (Sep 18, 2015) -* Found issue where : is accepted as a valid header, this is obviously wrong -* [CB-9562](https://issues.apache.org/jira/browse/CB-9562) Fixed incorrect headers handling on Android -* Fixing headers so they don't accept non-ASCII -* updated tests to use cordova apache vm -* [CB-9493](https://issues.apache.org/jira/browse/CB-9493) Fix file paths in file-transfer manual tests -* [CB-8816](https://issues.apache.org/jira/browse/CB-8816) Add cdvfile:// support on windows -* [CB-9376](https://issues.apache.org/jira/browse/CB-9376) Fix FileTransfer plugin manual tests issue - 'undefined' in paths - -### 1.2.1 (Jul 7, 2015) -* [CB-9275](https://issues.apache.org/jira/browse/CB-9275) [WP8] Fix build failure on WP8 by using reflection to detect presence of JSON.NET based serialization -* Updated code per code review. -* Updated documentation for browser -* Added option to allow for passing cookies automatically in the browser - -### 1.2.0 (Jun 17, 2015) -* [CB-9128](https://issues.apache.org/jira/browse/CB-9128) cordova-plugin-file-transfer documentation translation: cordova-plugin-file-transfer -* [CB-6503](https://issues.apache.org/jira/browse/CB-6503): Null pointer check for headers in upload (This closes #27) -* [CB-6503](https://issues.apache.org/jira/browse/CB-6503): Allow payload content-types other than multipart/form-data to be used for upload -* Fix NoSuchMethodException looking up cookies. -* fix npm md issue -* [CB-8951](https://issues.apache.org/jira/browse/CB-8951) (wp8) Handle exceptions in download() and upload() again -* [wp8] Relaxed engine version requirement, using reflection to see if methods are available -* Check for the existence of Json.net assembly to determin how we deserialize our headers. -* relax engine requirement to allow -dev versions -* Remove verbose console log messages -* fix bad commit (mine) for cordova-wp8@4.0.0 engine req -* bump required cordova-wp8 version to 4.0.0 -* This closes #80, This closes #12 -* fix failing test resulting from overlapping async calls -* [CB-8721](https://issues.apache.org/jira/browse/CB-8721) Fixes incorrect headers and upload params parsing on wp8 -* Replace all slashes in windows path - -### 1.1.0 (May 06, 2015) -* [CB-8951](https://issues.apache.org/jira/browse/CB-8951) Fixed crash related to headers parsing on **wp8** -* [CB-8933](https://issues.apache.org/jira/browse/CB-8933) Increased download and upload test timeout -* [CB-6313](https://issues.apache.org/jira/browse/CB-6313) **wp8**: Extra boundary in upload -* [CB-8761](https://issues.apache.org/jira/browse/CB-8761) **wp8**: Copy cookies from WebBrowser - -### 1.0.0 (Apr 15, 2015) -* [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-8641](https://issues.apache.org/jira/browse/CB-8641) Fixed tests to pass on windows and wp8 -* [CB-8583](https://issues.apache.org/jira/browse/CB-8583) Forces download to overwrite existing target file -* [CB-8589](https://issues.apache.org/jira/browse/CB-8589) Fixes upload failure when server's response doesn't contain any data -* [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) 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 -* [CB-8653](https://issues.apache.org/jira/browse/CB-8653) Updated Readme -* [CB-8654](https://issues.apache.org/jira/browse/CB-8654) Note WP8 download requests caching in docs -* [CB-8590](https://issues.apache.org/jira/browse/CB-8590) (Windows) Fixed download.onprogress.lengthComputable -* [CB-8566](https://issues.apache.org/jira/browse/CB-8566) Integrate TravisCI -* [CB-8438](https://issues.apache.org/jira/browse/CB-8438) cordova-plugin-file-transfer documentation translation: cordova-plugin-file-transfer -* [CB-8538](https://issues.apache.org/jira/browse/CB-8538) Added package.json file -* [CB-8495](https://issues.apache.org/jira/browse/CB-8495) Fixed wp8 and wp81 test failures -* [CB-7957](https://issues.apache.org/jira/browse/CB-7957) Adds support for `browser` platform -* [CB-8429](https://issues.apache.org/jira/browse/CB-8429) Updated version and RELEASENOTES.md for release 0.5.0 (take 2) -* Fixes typo, introduced in https://github.com/apache/cordova-plugin-file-transfer/commit/bc43b46 -* [CB-8407](https://issues.apache.org/jira/browse/CB-8407) Use File proxy to construct valid FileEntry for download success callback -* [CB-8407](https://issues.apache.org/jira/browse/CB-8407) Removes excess path to native path conversion in download method -* [CB-8429](https://issues.apache.org/jira/browse/CB-8429) Updated version and RELEASENOTES.md for release 0.5.0 -* [CB-7957](https://issues.apache.org/jira/browse/CB-7957) Adds support for `browser` platform -* [CB-8095](https://issues.apache.org/jira/browse/CB-8095) Fixes JSHint and formatting issues -* [CB-8095](https://issues.apache.org/jira/browse/CB-8095) Updates tests and documentation -* [CB-8095](https://issues.apache.org/jira/browse/CB-8095) Rewrite upload method to support progress events properly -* android: Fix error reporting for unknown uri type on sourceUri instead of targetUri - -### 0.5.0 (Feb 04, 2015) -* [CB-8407](https://issues.apache.org/jira/browse/CB-8407) windows: Fix download of `ms-appdata:///` URIs -* [CB-8095](https://issues.apache.org/jira/browse/CB-8095) windows: Rewrite upload method to support progress events properly -* [CB-5059](https://issues.apache.org/jira/browse/CB-5059) android: Add a CookieManager abstraction for pluggable webviews -* ios: Fix compile warning about implicity int conversion -* [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 DLog macro rather than CordovaLib version -* [CB-8296](https://issues.apache.org/jira/browse/CB-8296) ios: Fix crash when upload fails and file is not yet created (close #57) -* Document "body" property on FileTransferError -* [CB-7912](https://issues.apache.org/jira/browse/CB-7912) ios, android: Update to work with whitelist plugins in Cordova 4.x -* Error callback should always be called with the FileTransferError object, and not just the code -* windows: alias appData to Windows.Storage.ApplicationData.current -* [CB-8093](https://issues.apache.org/jira/browse/CB-8093) Fixes incorrect FileTransferError returned in case of download failure - -### 0.4.8 (Dec 02, 2014) -* [CB-8021](https://issues.apache.org/jira/browse/CB-8021) - adds documentation for `httpMethod` to `doc/index.md`. However, translations still need to be addressed. -* [CB-7223](https://issues.apache.org/jira/browse/CB-7223) spec.27 marked pending for **wp8** -* [CB-6900](https://issues.apache.org/jira/browse/CB-6900) fixed `spec.7` for **wp8** -* [CB-7944](https://issues.apache.org/jira/browse/CB-7944) Pended unsupported auto tests for *Windows* -* [CB-7977](https://issues.apache.org/jira/browse/CB-7977) Mention `deviceready` in plugin docs -* [CB-7700](https://issues.apache.org/jira/browse/CB-7700) cordova-plugin-file-transfer documentation translation: cordova-plugin-file-transfer - -### 0.4.7 (Oct 03, 2014) -* Construct proper FileEntry with nativeURL property set -* [CB-7532](https://issues.apache.org/jira/browse/CB-7532) Handle non-existent download dirs properly -* [CB-7529](https://issues.apache.org/jira/browse/CB-7529) Adds support for 'ms-appdata' URIs for windows - -### 0.4.6 (Sep 17, 2014) -* [CB-7471](https://issues.apache.org/jira/browse/CB-7471) cordova-plugin-file-transfer documentation translation -* [CB-7249](https://issues.apache.org/jira/browse/CB-7249) cordova-plugin-file-transfer documentation translation -* [CB-7423](https://issues.apache.org/jira/browse/CB-7423) fix spec28,29 lastProgressEvent not visible to afterEach function -* Amazon related changes. -* Remove dupe file windows+windows8 both use the same one -* [CB-7316](https://issues.apache.org/jira/browse/CB-7316) Updates docs with actual information. -* [CB-7316](https://issues.apache.org/jira/browse/CB-7316) Adds support for Windows platform, moves \*Proxy files to proper directory. -* [CB-7316](https://issues.apache.org/jira/browse/CB-7316) Improves current specs compatibility: -* added documentation for new test -* [CB-6466](https://issues.apache.org/jira/browse/CB-6466) Fix failing test due to recent url change -* [CB-6466](https://issues.apache.org/jira/browse/CB-6466) created mobile-spec test -* Renamed test dir, added nested plugin.xml and test -* Fixed failing spec.19 on wp8 -* added documentation to manual tests -* [CB-6961](https://issues.apache.org/jira/browse/CB-6961) port file-transfer tests to framework - -### 0.4.5 (Aug 06, 2014) -* Upload parameters out of order -* **FirefoxOS** initial implementation -* [CB-6781](https://issues.apache.org/jira/browse/CB-6781): Expose FileTransferError.exception to application -* [CB-6928](https://issues.apache.org/jira/browse/CB-6928): Add new error code to documentation -* [CB-6928](https://issues.apache.org/jira/browse/CB-6928): Handle 304 status code -* [CB-6928](https://issues.apache.org/jira/browse/CB-6928): Open output stream only if it's necessary. -* [BlackBerry10] Minor doc correction -* [CB-6127](https://issues.apache.org/jira/browse/CB-6127) Updated translations for docs -* [Windows8] upload uses the provided fileName or the actual fileName -* [CB-2420](https://issues.apache.org/jira/browse/CB-2420) [Windows8] honor fileKey and param options. This closes #15 -* [CB-6781](https://issues.apache.org/jira/browse/CB-6781): Update new docs to match AlexNennker's changes in PR30 -* [CB-6781](https://issues.apache.org/jira/browse/CB-6781): Continue previous commit with one new instance (This closes #30) -* [CB-6781](https://issues.apache.org/jira/browse/CB-6781): add the exception text to the error object -* [CB-6890](https://issues.apache.org/jira/browse/CB-6890): Fix pluginManager access for 4.0.x branch - -### 0.4.4 (Jun 05, 2014) -* [CB-6127](https://issues.apache.org/jira/browse/CB-6127) Spanish and French Translations added. Github close #21 -* ubuntu: support 'cdvfile' URI -* [CB-6802](https://issues.apache.org/jira/browse/CB-6802) Add license -* Upload progress now works also for second file -* [CB-6706](https://issues.apache.org/jira/browse/CB-6706): Relax dependency on file plugin -* [CB-3440](https://issues.apache.org/jira/browse/CB-3440) [BlackBerry10] Update implementation to use modules from file plugin -* [CB-6378](https://issues.apache.org/jira/browse/CB-6378) Use connection.disconnect() instead of stream.close() for thread-safety -* [CB-6491](https://issues.apache.org/jira/browse/CB-6491) add CONTRIBUTING.md -* [CB-6466](https://issues.apache.org/jira/browse/CB-6466) Auto-create directories in download -* [CB-6494](https://issues.apache.org/jira/browse/CB-6494) android: Fix upload of KitKat content URIs -* Upleveled from android port with following commits: 3c1ff16 Andrew Grieve - [CB-5762](https://issues.apache.org/jira/browse/CB-5762) android: Fix lengthComputable set wrong for gzip downloads 8374b3d Colin Mahoney - [CB-5631](https://issues.apache.org/jira/browse/CB-5631) Removed SimpleTrackingInputStream.read(byte[] buffer) 6f91ac3 Bas Bosman - [CB-4907](https://issues.apache.org/jira/browse/CB-4907) Close stream when we're finished with it 651460f Christoph Neumann - [CB-6000](https://issues.apache.org/jira/browse/CB-6000) Nginx rejects Content-Type without a space before "boundary". 35f80e4 Ian Clelland - [CB-6050](https://issues.apache.org/jira/browse/CB-6050): Use instance method on actual file plugin object to get FileEntry to return on download -* [CB-5980](https://issues.apache.org/jira/browse/CB-5980) Updated version and RELEASENOTES.md for release 0.4.1 - -### 0.4.3 (Apr 17, 2014) -* [CB-6422](https://issues.apache.org/jira/browse/CB-6422) [windows8] use cordova/exec/proxy -* iOS: Fix error where files were not removed on abort -* [CB-5175](https://issues.apache.org/jira/browse/CB-5175): [ios] CDVFileTransfer asynchronous download (Fixes #24) -* [ios] Cast id references to NSURL to avoid compiler warnings (Fixes: apache/cordova-plugin-file-transfer#18) -* [CB-6212](https://issues.apache.org/jira/browse/CB-6212): [iOS] fix warnings compiled under arm64 64-bit -* [CB-5762](https://issues.apache.org/jira/browse/CB-5762): [FireOS] android: Fix lengthComputable set wrong for gzip downloads -* [CB-5631](https://issues.apache.org/jira/browse/CB-5631): [FireOS] Removed SimpleTrackingInputStream.read(byte[] buffer) -* [CB-4907](https://issues.apache.org/jira/browse/CB-4907): [FireOS] Close stream when we're finished with it -* [CB-6000](https://issues.apache.org/jira/browse/CB-6000): [FireOS] Nginx rejects Content-Type without a space before "boundary". -* [CB-6050](https://issues.apache.org/jira/browse/CB-6050): [FireOS] Use instance method on actual file plugin object to get FileEntry to return on download -* [CB-6460](https://issues.apache.org/jira/browse/CB-6460): Update license headers - -### 0.4.2 (Feb 28, 2014) -* [CB-6106](https://issues.apache.org/jira/browse/CB-6106) Ensure that nativeURL is used by file transfer download -* iOS: Fix default value for trustAllHosts on iOS (YES->NO) -* [CB-6059](https://issues.apache.org/jira/browse/CB-6059) iOS: Stop FileTransfer.download doing IO on the UI thread. -* [CB-5588](https://issues.apache.org/jira/browse/CB-5588) iOS: Add response headers to upload result -* [CB-2190](https://issues.apache.org/jira/browse/CB-2190) iOS: Make backgroundTaskId apply to downloads as well. Move backgroundTaskId to the delegate. -* [CB-6050](https://issues.apache.org/jira/browse/CB-6050) Android: Use instance method on actual file plugin object to get FileEntry to return on download -* [CB-6000](https://issues.apache.org/jira/browse/CB-6000) Android: Nginx rejects Content-Type without a space before "boundary". -* [CB-4907](https://issues.apache.org/jira/browse/CB-4907) Android: Close stream when we're finished with it -* [CB-6022](https://issues.apache.org/jira/browse/CB-6022) Add backwards-compatibility notes to doc - -### 0.4.1 (Feb 05, 2014) -* [CB-5365](https://issues.apache.org/jira/browse/CB-5365) Remove unused exception var to prevent warnings? -* [CB-2421](https://issues.apache.org/jira/browse/CB-2421) explicitly write the bytesSent,responseCode,result to the FileUploadResult pending release of cordova-plugin-file dependency, added some sanity checks for callbacks -* iOS: Update for new file plugin api -* [CB-5631](https://issues.apache.org/jira/browse/CB-5631) Removed SimpleTrackingInputStream.read(byte[] buffer) -* [CB-5762](https://issues.apache.org/jira/browse/CB-5762) android: Fix lengthComputable set wrong for gzip downloads -* [CB-4899](https://issues.apache.org/jira/browse/CB-4899) [BlackBerry10] Improve binary file transfer download -* Delete stale test/ directory -* [CB-5722](https://issues.apache.org/jira/browse/CB-5722) [BlackBerry10] Update upload function to use native file object -* [CB-5658](https://issues.apache.org/jira/browse/CB-5658) Delete stale snapshot of plugin docs -* Remove @1 designation from file plugin dependency until pushed to npm -* [CB-5466](https://issues.apache.org/jira/browse/CB-5466): Update to work with filesystem URLs - -### 0.4.0 (Dec 4, 2013) -* [CB-5466](https://issues.apache.org/jira/browse/CB-5466): Partial revert; we're not ready yet for FS urls -* add ubuntu platform -* [CB-5466](https://issues.apache.org/jira/browse/CB-5466): Minor version bump -* [CB-5466](https://issues.apache.org/jira/browse/CB-5466): Update FileTransfer plugin to accept filesystem urls -* Added amazon-fireos platform. Change to use amazon-fireos as the platform if the user agen string contains 'cordova-amazon-fireos' - -### 0.3.4 (Oct 28, 2013) -* [CB-5128](https://issues.apache.org/jira/browse/CB-5128): added repo + issue tag to plugin.xml for file transfer plugin -* [CB-5010](https://issues.apache.org/jira/browse/CB-5010) Incremented plugin version on dev branch. - -### 0.3.3 (Oct 9, 2013) -* removed un-needed undef check -* Fix missing headers in Windows 8 upload proxy -* Fix missing headers in Windows 8 Proxy -* Fix Windows 8 HTMLAnchorElement return host:80 which force Basic Auth Header to replace options Auth Header -* [CB-4915](https://issues.apache.org/jira/browse/CB-4915) Incremented plugin version on dev branch. - -### 0.3.2 (Sept 25, 2013) -* [CB-4889](https://issues.apache.org/jira/browse/CB-4889) bumping&resetting version -* [windows8] commandProxy was moved -* [CB-4889](https://issues.apache.org/jira/browse/CB-4889) updating core references -* [CB-4889](https://issues.apache.org/jira/browse/CB-4889) renaming org.apache.cordova.core.file-transfer to org.apache.cordova.file-transfer and updating dependency -* Rename CHANGELOG.md -> RELEASENOTES.md diff --git a/plugins/cordova-plugin-file-transfer/doc/de/README.md b/plugins/cordova-plugin-file-transfer/doc/de/README.md deleted file mode 100644 index 03191cb..0000000 --- a/plugins/cordova-plugin-file-transfer/doc/de/README.md +++ /dev/null @@ -1,311 +0,0 @@ - - -# cordova-plugin-file-transfer - -[![Build Status](https://travis-ci.org/apache/cordova-plugin-file-transfer.svg)](https://travis-ci.org/apache/cordova-plugin-file-transfer) - -Plugin-Dokumentation: - -Dieses Plugin ermöglicht Ihnen zum Hochladen und Herunterladen von Dateien. - -Dieses Plugin wird global `FileTransfer`, `FileUploadOptions` Konstruktoren definiert. - -Obwohl im globalen Gültigkeitsbereich, sind sie nicht bis nach dem `deviceready`-Ereignis. - - document.addEventListener("deviceready", onDeviceReady, false); - function onDeviceReady() { - console.log(FileTransfer); - } - - -## Installation - - cordova plugin add cordova-plugin-file-transfer - - -## Unterstützte Plattformen - - * Amazon Fire OS - * Android - * BlackBerry 10 - * Browser - * Firefox OS ** - * iOS - * Windows Phone 7 und 8 * - * Windows 8 - * Windows - -\ * *Unterstützen keine `Onprogress` noch `abort()` * - -\ ** * `Onprogress` nicht unterstützt* - -# FileTransfer - -Das `FileTransfer` -Objekt stellt eine Möglichkeit zum Hochladen von Dateien, die mithilfe einer HTTP-mehrteiligen POST oder PUT-Anforderung, und auch Dateien herunterladen. - -## Eigenschaften - - * **OnProgress**: aufgerufen, wobei ein `ProgressEvent` wann wird eine neue Datenmenge übertragen. *(Funktion)* - -## Methoden - - * **Upload**: sendet eine Datei an einen Server. - - * **Download**: lädt eine Datei vom Server. - - * **abort**: Abbruch eine Ãœbertragung in Bearbeitung. - -## Upload - -**Parameter**: - - * **FileURL**: Dateisystem-URL, das die Datei auf dem Gerät. Für rückwärts Kompatibilität, dies kann auch der vollständige Pfad der Datei auf dem Gerät sein. (Siehe [rückwärts Kompatibilität Notes] unten) - - * **Server**: URL des Servers, die Datei zu empfangen, wie kodiert`encodeURI()`. - - * **successCallback**: ein Rückruf, der ein `FileUploadResult`-Objekt übergeben wird. *(Funktion)* - - * **errorCallback**: ein Rückruf, der ausgeführt wird, tritt ein Fehler beim Abrufen der `FileUploadResult`. Mit einem `FileTransferError`-Objekt aufgerufen. *(Funktion)* - - * **Optionen**: optionale Parameter *(Objekt)*. Gültige Schlüssel: - - * **FileKey**: der Name des Form-Elements. Wird standardmäßig auf `file` . (DOM-String und enthält) - * **Dateiname**: der Dateiname beim Speichern der Datei auf dem Server verwendet. Wird standardmäßig auf `image.jpg` . (DOM-String und enthält) - * **httpMethod**: die HTTP-Methode, die-entweder `PUT` oder `POST`. Der Standardwert ist `POST`. (DOM-String und enthält) - * **mimeType**: den Mime-Typ der Daten hochzuladen. Standardwerte auf `Image/Jpeg`. (DOM-String und enthält) - * **params**: eine Reihe von optionalen Schlüssel/Wert-Paaren in der HTTP-Anforderung übergeben. (Objekt) - * **chunkedMode**: ob die Daten in "Chunked" streaming-Modus hochladen. Der Standardwert ist `true`. (Boolean) - * **headers**: eine Karte von Header-Name-Header-Werte. Verwenden Sie ein Array, um mehr als einen Wert anzugeben. Auf iOS, FireOS und Android wenn ein Content-Type-Header vorhanden ist, werden mehrteilige Formulardaten nicht verwendet werden. (Object) - * **httpMethod**: die HTTP-Methode zu verwenden, z.B. POST oder PUT. Der Standardwert ist `POST`. (DOM-String enthält) - - * **TrustAllHosts**: Optionaler Parameter, wird standardmäßig auf `false` . Wenn legen Sie auf `true` , es akzeptiert alle Sicherheitszertifikate. Dies ist nützlich, da Android selbstsignierte Zertifikate ablehnt. Nicht für den produktiven Einsatz empfohlen. Auf Android und iOS unterstützt. *(Boolean)* - -### Beispiel - - // !! Assumes variable fileURL contains a valid URL to a text file on the device, - // for example, cdvfile://localhost/persistent/path/to/file.txt - - var win = function (r) { - console.log("Code = " + r.responseCode); - console.log("Response = " + r.response); - console.log("Sent = " + r.bytesSent); - } - - var fail = function (error) { - alert("An error has occurred: Code = " + error.code); - console.log("upload error source " + error.source); - console.log("upload error target " + error.target); - } - - var options = new FileUploadOptions(); - options.fileKey = "file"; - options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1); - options.mimeType = "text/plain"; - - var params = {}; - params.value1 = "test"; - params.value2 = "param"; - - options.params = params; - - var ft = new FileTransfer(); - ft.upload(fileURL, encodeURI("http://some.server.com/upload.php"), win, fail, options); - - -### Beispiel mit hochladen Kopf- und Progress-Ereignisse (Android und iOS nur) - - function win(r) { - console.log("Code = " + r.responseCode); - console.log("Response = " + r.response); - console.log("Sent = " + r.bytesSent); - } - - function fail(error) { - alert("An error has occurred: Code = " + error.code); - console.log("upload error source " + error.source); - console.log("upload error target " + error.target); - } - - var uri = encodeURI("http://some.server.com/upload.php"); - - var options = new FileUploadOptions(); - options.fileKey="file"; - options.fileName=fileURL.substr(fileURL.lastIndexOf('/')+1); - options.mimeType="text/plain"; - - var headers={'headerParam':'headerValue'}; - - options.headers = headers; - - var ft = new FileTransfer(); - ft.onprogress = function(progressEvent) { - if (progressEvent.lengthComputable) { - loadingStatus.setPercentage(progressEvent.loaded / progressEvent.total); - } else { - loadingStatus.increment(); - } - }; - ft.upload(fileURL, uri, win, fail, options); - - -## FileUploadResult - -Ein `FileUploadResult`-Objekt wird an den Erfolg-Rückruf des `Objekts FileTransfer`-Upload()-Methode übergeben. - -### Eigenschaften - - * **BytesSent**: die Anzahl der Bytes, die als Teil des Uploads an den Server gesendet. (lange) - - * **ResponseCode**: die HTTP-Response-Code vom Server zurückgegeben. (lange) - - * **response**: der HTTP-Antwort vom Server zurückgegeben. (DOM-String und enthält) - - * **Header**: die HTTP-Response-Header vom Server. (Objekt) - - * Derzeit unterstützt auf iOS nur. - -### iOS Macken - - * Unterstützt keine `responseCode` oder`bytesSent`. - -## Download - -**Parameter**: - - * **source**: URL des Servers, um die Datei herunterzuladen, wie kodiert`encodeURI()`. - - * **target**: Dateisystem-Url, das die Datei auf dem Gerät. Für rückwärts Kompatibilität, dies kann auch der vollständige Pfad der Datei auf dem Gerät sein. (Siehe [rückwärts Kompatibilität Notes] unten) - - * **SuccessCallback**: ein Rückruf, der übergeben wird ein `FileEntry` Objekt. *(Funktion)* - - * **errorCallback**: ein Rückruf, der ausgeführt wird, tritt ein Fehler beim Abrufen der `FileEntry`. Mit einem `FileTransferError`-Objekt aufgerufen. *(Funktion)* - - * **TrustAllHosts**: Optionaler Parameter, wird standardmäßig auf `false` . Wenn legen Sie auf `true` , es akzeptiert alle Sicherheitszertifikate. Dies ist nützlich, da Android selbstsignierte Zertifikate ablehnt. Nicht für den produktiven Einsatz empfohlen. Auf Android und iOS unterstützt. *(Boolean)* - - * **Options**: optionale Parameter, derzeit nur unterstützt Kopfzeilen (z. B. Autorisierung (Standardauthentifizierung), etc.). - -### Beispiel - - // !! Assumes variable fileURL contains a valid URL to a path on the device, - // for example, cdvfile://localhost/persistent/path/to/downloads/ - - var fileTransfer = new FileTransfer(); - var uri = encodeURI("http://some.server.com/download.php"); - - fileTransfer.download( - uri, - fileURL, - function(entry) { - console.log("download complete: " + entry.toURL()); - }, - function(error) { - console.log("download error source " + error.source); - console.log("download error target " + error.target); - console.log("upload error code" + error.code); - }, - false, - { - headers: { - "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA==" - } - } - ); - - -### WP8 Macken - - * Downloaden anfordert, wird von native Implementierung zwischengespeichert wird. Um zu vermeiden, Zwischenspeicherung, übergeben `If-Modified-Since` Header Methode herunterladen. - -## abort - -Bricht einen in-Progress-Transfer. Der Onerror-Rückruf wird ein FileTransferError-Objekt übergeben, die einen Fehlercode FileTransferError.ABORT_ERR hat. - -### Beispiel - - // !! Assumes variable fileURL contains a valid URL to a text file on the device, - // for example, cdvfile://localhost/persistent/path/to/file.txt - - var win = function(r) { - console.log("Should not be called."); - } - - var fail = function(error) { - // error.code == FileTransferError.ABORT_ERR - alert("An error has occurred: Code = " + error.code); - console.log("upload error source " + error.source); - console.log("upload error target " + error.target); - } - - var options = new FileUploadOptions(); - options.fileKey="file"; - options.fileName="myphoto.jpg"; - options.mimeType="image/jpeg"; - - var ft = new FileTransfer(); - ft.upload(fileURL, encodeURI("http://some.server.com/upload.php"), win, fail, options); - ft.abort(); - - -## FileTransferError - -Ein `FileTransferError`-Objekt wird an eine Fehler-Callback übergeben, wenn ein Fehler auftritt. - -### Eigenschaften - - * **Code**: einer der vordefinierten Fehlercodes aufgeführt. (Anzahl) - - * **Quelle**: URL der Quelle. (String) - - * **Ziel**: URL zum Ziel. (String) - - * **HTTP_STATUS**: HTTP-Statuscode. Dieses Attribut ist nur verfügbar, wenn ein Response-Code aus der HTTP-Verbindung eingeht. (Anzahl) - - * **body** Antworttext. Dieses Attribut ist nur verfügbar, wenn eine Antwort von der HTTP-Verbindung eingeht. (String) - - * **exception**: entweder e.getMessage oder e.toString (String) - -### Konstanten - - * 1 = `FileTransferError.FILE_NOT_FOUND_ERR` - * 2 = `FileTransferError.INVALID_URL_ERR` - * 3 = `FileTransferError.CONNECTION_ERR` - * 4 = `FileTransferError.ABORT_ERR` - * 5 = `FileTransferError.NOT_MODIFIED_ERR` - -## Hinweise rückwärts Kompatibilität - -Frühere Versionen des Plugins würde nur Gerät-Absolute-Dateipfade als Quelle für Uploads oder als Ziel für Downloads übernehmen. Diese Pfade wäre in der Regel der form - - /var/mobile/Applications//Documents/path/to/file (iOS) - /storage/emulated/0/path/to/file (Android) - - -Für rückwärts Kompatibilität, diese Pfade noch akzeptiert werden, und wenn Ihre Anwendung Pfade wie diese im permanenten Speicher aufgezeichnet hat, dann sie können weiter verwendet werden. - -Diese Pfade waren zuvor in der Eigenschaft `fullPath` `FileEntry` und `DirectoryEntry`-Objekte, die durch das Plugin Datei zurückgegeben ausgesetzt. Neue Versionen der die Datei-Erweiterung, jedoch nicht länger werden diese Pfade zu JavaScript. - -Wenn Sie ein auf eine neue Upgrade (1.0.0 oder neuere) Version der Datei, und Sie haben zuvor mit `entry.fullPath` als Argumente `download()` oder `upload()`, dann ändern Sie den Code, um die Dateisystem-URLs verwenden müssen. - -`FileEntry.toURL()` und `DirectoryEntry.toURL()` zurück, eine Dateisystem-URL in der form - - cdvfile://localhost/persistent/path/to/file - - -die anstelle der absoluten Dateipfad in `download()` und `upload()` Methode verwendet werden kann. \ No newline at end of file diff --git a/plugins/cordova-plugin-file-transfer/doc/de/index.md b/plugins/cordova-plugin-file-transfer/doc/de/index.md deleted file mode 100644 index 4081503..0000000 --- a/plugins/cordova-plugin-file-transfer/doc/de/index.md +++ /dev/null @@ -1,302 +0,0 @@ - - -# cordova-plugin-file-transfer - -Dieses Plugin ermöglicht Ihnen zum Hochladen und Herunterladen von Dateien. - -Dieses Plugin wird global `FileTransfer`, `FileUploadOptions` Konstruktoren definiert. - -Obwohl im globalen Gültigkeitsbereich, sind sie nicht bis nach dem `deviceready`-Ereignis. - - document.addEventListener("deviceready", onDeviceReady, false); - function onDeviceReady() { - console.log(FileTransfer); - } - - -## Installation - - cordova plugin add cordova-plugin-file-transfer - - -## Unterstützte Plattformen - -* Amazon Fire OS -* Android -* BlackBerry 10 -* Browser -* Firefox OS ** -* iOS -* Windows Phone 7 und 8 * -* Windows 8 -* Windows - -* *Unterstützen keine `onprogress` noch `abort()`* - -* * *`onprogress` nicht unterstützt* - -# FileTransfer - -Das `FileTransfer`-Objekt bietet eine Möglichkeit zum Hochladen von Dateien, die mithilfe einer HTTP-Anforderung für mehrteiligen POST sowie Informationen zum Herunterladen von Dateien sowie. - -## Eigenschaften - -* **OnProgress**: aufgerufen, wobei ein `ProgressEvent` wann wird eine neue Datenmenge übertragen. *(Funktion)* - -## Methoden - -* **Upload**: sendet eine Datei an einen Server. - -* **Download**: lädt eine Datei vom Server. - -* **abort**: Abbruch eine Ãœbertragung in Bearbeitung. - -## Upload - -**Parameter**: - -* **FileURL**: Dateisystem-URL, das die Datei auf dem Gerät. Für rückwärts Kompatibilität, dies kann auch der vollständige Pfad der Datei auf dem Gerät sein. (Siehe [rückwärts Kompatibilität Notes] unten) - -* **Server**: URL des Servers, die Datei zu empfangen, wie kodiert`encodeURI()`. - -* **successCallback**: ein Rückruf, der ein `FileUploadResult`-Objekt übergeben wird. *(Funktion)* - -* **errorCallback**: ein Rückruf, der ausgeführt wird, tritt ein Fehler beim Abrufen der `FileUploadResult`. Mit einem `FileTransferError`-Objekt aufgerufen. *(Funktion)* - -* **Optionen**: optionale Parameter *(Objekt)*. Gültige Schlüssel: - - * **FileKey**: der Name des Form-Elements. Wird standardmäßig auf `file` . (DOM-String und enthält) - * **Dateiname**: der Dateiname beim Speichern der Datei auf dem Server verwendet. Wird standardmäßig auf `image.jpg` . (DOM-String und enthält) - * **httpMethod**: die HTTP-Methode, die-entweder `PUT` oder `POST`. Der Standardwert ist `POST`. (DOM-String und enthält) - * **mimeType**: den Mime-Typ der Daten hochzuladen. Standardwerte auf `Image/Jpeg`. (DOM-String und enthält) - * **params**: eine Reihe von optionalen Schlüssel/Wert-Paaren in der HTTP-Anforderung übergeben. (Objekt) - * **chunkedMode**: ob die Daten in "Chunked" streaming-Modus hochladen. Der Standardwert ist `true`. (Boolean) - * **headers**: eine Karte von Header-Name-Header-Werte. Verwenden Sie ein Array, um mehr als einen Wert anzugeben. (Objekt) - -* **TrustAllHosts**: Optionaler Parameter, wird standardmäßig auf `false` . Wenn legen Sie auf `true` , es akzeptiert alle Sicherheitszertifikate. Dies ist nützlich, da Android selbstsignierte Zertifikate ablehnt. Nicht für den produktiven Einsatz empfohlen. Auf Android und iOS unterstützt. *(Boolean)* - -### Beispiel - - // !! Assumes variable fileURL contains a valid URL to a text file on the device, - // for example, cdvfile://localhost/persistent/path/to/file.txt - - var win = function (r) { - console.log("Code = " + r.responseCode); - console.log("Response = " + r.response); - console.log("Sent = " + r.bytesSent); - } - - var fail = function (error) { - alert("An error has occurred: Code = " + error.code); - console.log("upload error source " + error.source); - console.log("upload error target " + error.target); - } - - var options = new FileUploadOptions(); - options.fileKey = "file"; - options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1); - options.mimeType = "text/plain"; - - var params = {}; - params.value1 = "test"; - params.value2 = "param"; - - options.params = params; - - var ft = new FileTransfer(); - ft.upload(fileURL, encodeURI("http://some.server.com/upload.php"), win, fail, options); - - -### Beispiel mit hochladen Kopf- und Progress-Ereignisse (Android und iOS nur) - - function win(r) { - console.log("Code = " + r.responseCode); - console.log("Response = " + r.response); - console.log("Sent = " + r.bytesSent); - } - - function fail(error) { - alert("An error has occurred: Code = " + error.code); - console.log("upload error source " + error.source); - console.log("upload error target " + error.target); - } - - var uri = encodeURI("http://some.server.com/upload.php"); - - var options = new FileUploadOptions(); - options.fileKey="file"; - options.fileName=fileURL.substr(fileURL.lastIndexOf('/')+1); - options.mimeType="text/plain"; - - var headers={'headerParam':'headerValue'}; - - options.headers = headers; - - var ft = new FileTransfer(); - ft.onprogress = function(progressEvent) { - if (progressEvent.lengthComputable) { - loadingStatus.setPercentage(progressEvent.loaded / progressEvent.total); - } else { - loadingStatus.increment(); - } - }; - ft.upload(fileURL, uri, win, fail, options); - - -## FileUploadResult - -Ein `FileUploadResult`-Objekt wird an den Erfolg-Rückruf des `Objekts FileTransfer`-Upload()-Methode übergeben. - -### Eigenschaften - -* **BytesSent**: die Anzahl der Bytes, die als Teil des Uploads an den Server gesendet. (lange) - -* **ResponseCode**: die HTTP-Response-Code vom Server zurückgegeben. (lange) - -* **response**: der HTTP-Antwort vom Server zurückgegeben. (DOM-String und enthält) - -* **Header**: die HTTP-Response-Header vom Server. (Objekt) - - * Derzeit unterstützt auf iOS nur. - -### iOS Macken - -* Unterstützt keine `responseCode` oder`bytesSent`. - -## Download - -**Parameter**: - -* **source**: URL des Servers, um die Datei herunterzuladen, wie kodiert`encodeURI()`. - -* **target**: Dateisystem-Url, das die Datei auf dem Gerät. Für rückwärts Kompatibilität, dies kann auch der vollständige Pfad der Datei auf dem Gerät sein. (Siehe [rückwärts Kompatibilität Notes] unten) - -* **SuccessCallback**: ein Rückruf, der übergeben wird ein `FileEntry` Objekt. *(Funktion)* - -* **errorCallback**: ein Rückruf, der ausgeführt wird, tritt ein Fehler beim Abrufen der `FileEntry`. Mit einem `FileTransferError`-Objekt aufgerufen. *(Funktion)* - -* **TrustAllHosts**: Optionaler Parameter, wird standardmäßig auf `false` . Wenn legen Sie auf `true` , es akzeptiert alle Sicherheitszertifikate. Dies ist nützlich, da Android selbstsignierte Zertifikate ablehnt. Nicht für den produktiven Einsatz empfohlen. Auf Android und iOS unterstützt. *(Boolean)* - -* **Options**: optionale Parameter, derzeit nur unterstützt Kopfzeilen (z. B. Autorisierung (Standardauthentifizierung), etc.). - -### Beispiel - - // !! Assumes variable fileURL contains a valid URL to a path on the device, - // for example, cdvfile://localhost/persistent/path/to/downloads/ - - var fileTransfer = new FileTransfer(); - var uri = encodeURI("http://some.server.com/download.php"); - - fileTransfer.download( - uri, - fileURL, - function(entry) { - console.log("download complete: " + entry.toURL()); - }, - function(error) { - console.log("download error source " + error.source); - console.log("download error target " + error.target); - console.log("upload error code" + error.code); - }, - false, - { - headers: { - "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA==" - } - } - ); - - -## abort - -Bricht einen in-Progress-Transfer. Der Onerror-Rückruf wird ein FileTransferError-Objekt übergeben, die einen Fehlercode FileTransferError.ABORT_ERR hat. - -### Beispiel - - // !! Assumes variable fileURL contains a valid URL to a text file on the device, - // for example, cdvfile://localhost/persistent/path/to/file.txt - - var win = function(r) { - console.log("Should not be called."); - } - - var fail = function(error) { - // error.code == FileTransferError.ABORT_ERR - alert("An error has occurred: Code = " + error.code); - console.log("upload error source " + error.source); - console.log("upload error target " + error.target); - } - - var options = new FileUploadOptions(); - options.fileKey="file"; - options.fileName="myphoto.jpg"; - options.mimeType="image/jpeg"; - - var ft = new FileTransfer(); - ft.upload(fileURL, encodeURI("http://some.server.com/upload.php"), win, fail, options); - ft.abort(); - - -## FileTransferError - -Ein `FileTransferError`-Objekt wird an eine Fehler-Callback übergeben, wenn ein Fehler auftritt. - -### Eigenschaften - -* **Code**: einer der vordefinierten Fehlercodes aufgeführt. (Anzahl) - -* **Quelle**: URL der Quelle. (String) - -* **Ziel**: URL zum Ziel. (String) - -* **HTTP_STATUS**: HTTP-Statuscode. Dieses Attribut ist nur verfügbar, wenn ein Response-Code aus der HTTP-Verbindung eingeht. (Anzahl) - -* **body** Antworttext. Dieses Attribut ist nur verfügbar, wenn eine Antwort von der HTTP-Verbindung eingeht. (String) - -* **exception**: entweder e.getMessage oder e.toString (String) - -### Konstanten - -* 1 = `FileTransferError.FILE_NOT_FOUND_ERR` -* 2 = `FileTransferError.INVALID_URL_ERR` -* 3 = `FileTransferError.CONNECTION_ERR` -* 4 = `FileTransferError.ABORT_ERR` -* 5 = `FileTransferError.NOT_MODIFIED_ERR` - -## Hinweise rückwärts Kompatibilität - -Frühere Versionen des Plugins würde nur Gerät-Absolute-Dateipfade als Quelle für Uploads oder als Ziel für Downloads übernehmen. Diese Pfade wäre in der Regel der form - - /var/mobile/Applications//Documents/path/to/file (iOS) - /storage/emulated/0/path/to/file (Android) - - -Für rückwärts Kompatibilität, diese Pfade noch akzeptiert werden, und wenn Ihre Anwendung Pfade wie diese im permanenten Speicher aufgezeichnet hat, dann sie können weiter verwendet werden. - -Diese Pfade waren zuvor in der Eigenschaft `fullPath` `FileEntry` und `DirectoryEntry`-Objekte, die durch das Plugin Datei zurückgegeben ausgesetzt. Neue Versionen der die Datei-Erweiterung, jedoch nicht länger werden diese Pfade zu JavaScript. - -Wenn Sie ein auf eine neue Upgrade (1.0.0 oder neuere) Version der Datei, und Sie haben zuvor mit `entry.fullPath` als Argumente `download()` oder `upload()`, dann ändern Sie den Code, um die Dateisystem-URLs verwenden müssen. - -`FileEntry.toURL()` und `DirectoryEntry.toURL()` zurück, eine Dateisystem-URL in der form - - cdvfile://localhost/persistent/path/to/file - - -die anstelle der absoluten Dateipfad in `download()` und `upload()` Methode verwendet werden kann. diff --git a/plugins/cordova-plugin-file-transfer/doc/es/README.md b/plugins/cordova-plugin-file-transfer/doc/es/README.md deleted file mode 100644 index 1c8ee3f..0000000 --- a/plugins/cordova-plugin-file-transfer/doc/es/README.md +++ /dev/null @@ -1,311 +0,0 @@ - - -# cordova-plugin-file-transfer - -[![Build Status](https://travis-ci.org/apache/cordova-plugin-file-transfer.svg)](https://travis-ci.org/apache/cordova-plugin-file-transfer) - -Documentación del plugin: - -Este plugin te permite cargar y descargar archivos. - -Este plugin define global `FileTransfer` , `FileUploadOptions` constructores. - -Aunque en el ámbito global, no están disponibles hasta después de la `deviceready` evento. - - document.addEventListener("deviceready", onDeviceReady, false); - function onDeviceReady() { - console.log(FileTransfer); - } - - -## Instalación - - cordova plugin add cordova-plugin-file-transfer - - -## Plataformas soportadas - - * Amazon fire OS - * Android - * BlackBerry 10 - * Explorador - * Firefox OS ** - * iOS - * Windows Phone 7 y 8 * - * Windows 8 - * Windows - -\ * *No soporta `onprogress` ni `abort()` * - -\ ** *No soporta `onprogress` * - -# FileTransfer - -El objeto `FileTransfer` proporciona una manera para subir archivos utilizando una varias parte solicitud HTTP POST o PUT y descargar archivos, así. - -## Propiedades - - * **OnProgress**: llama con un `ProgressEvent` cuando se transfiere un nuevo paquete de datos. *(Función)* - -## Métodos - - * **cargar**: envía un archivo a un servidor. - - * **Descargar**: descarga un archivo del servidor. - - * **abortar**: aborta una transferencia en curso. - -## subir - -**Parámetros**: - - * **fileURL**: URL de Filesystem que representa el archivo en el dispositivo. Para atrás compatibilidad, esto también puede ser la ruta de acceso completa del archivo en el dispositivo. (Ver [hacia atrás compatibilidad notas] debajo) - - * **servidor**: dirección URL del servidor para recibir el archivo, como codificada por`encodeURI()`. - - * **successCallback**: una devolución de llamada que se pasa un `FileUploadResult` objeto. *(Función)* - - * **errorCallback**: una devolución de llamada que se ejecuta si se produce un error recuperar la `FileUploadResult` . Invocado con un `FileTransferError` objeto. *(Función)* - - * **Opciones**: parámetros opcionales *(objeto)*. Teclas válidas: - - * **fileKey**: el nombre del elemento de formulario. Por defecto es `file` . (DOMString) - * **nombre de archivo**: el nombre del archivo a utilizar al guardar el archivo en el servidor. Por defecto es `image.jpg` . (DOMString) - * **httpMethod**: método HTTP el utilizar - o `PUT` o `POST` . Por defecto es `POST` . (DOMString) - * **mimeType**: el tipo mime de los datos para cargar. Por defecto es `image/jpeg` . (DOMString) - * **params**: un conjunto de pares clave/valor opcional para pasar en la petición HTTP. (Objeto) - * **chunkedMode**: Si desea cargar los datos en modo de transmisión fragmentado. Por defecto es `true` . (Boolean) - * **headers**: un mapa de nombre de encabezado/valores de encabezado Utilice una matriz para especificar más de un valor. En iOS FireOS y Android, si existe un encabezado llamado Content-Type, datos de un formulario multipart no se utilizará. (Object) - * **httpMethod**: HTTP el método a utilizar por ejemplo POST o poner. Por defecto `el POST`. (DOMString) - - * **trustAllHosts**: parámetro opcional, por defecto es `false` . Si establece en `true` , acepta todos los certificados de seguridad. Esto es útil ya que Android rechaza certificados autofirmados seguridad. No se recomienda para uso productivo. Compatible con iOS y Android. *(boolean)* - -### Ejemplo - - // !! Assumes variable fileURL contains a valid URL to a text file on the device, - // for example, cdvfile://localhost/persistent/path/to/file.txt - - var win = function (r) { - console.log("Code = " + r.responseCode); - console.log("Response = " + r.response); - console.log("Sent = " + r.bytesSent); - } - - var fail = function (error) { - alert("An error has occurred: Code = " + error.code); - console.log("upload error source " + error.source); - console.log("upload error target " + error.target); - } - - var options = new FileUploadOptions(); - options.fileKey = "file"; - options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1); - options.mimeType = "text/plain"; - - var params = {}; - params.value1 = "test"; - params.value2 = "param"; - - options.params = params; - - var ft = new FileTransfer(); - ft.upload(fileURL, encodeURI("http://some.server.com/upload.php"), win, fail, options); - - -### Ejemplo con cabeceras de subir y eventos de progreso (Android y iOS solamente) - - function win(r) { - console.log("Code = " + r.responseCode); - console.log("Response = " + r.response); - console.log("Sent = " + r.bytesSent); - } - - function fail(error) { - alert("An error has occurred: Code = " + error.code); - console.log("upload error source " + error.source); - console.log("upload error target " + error.target); - } - - var uri = encodeURI("http://some.server.com/upload.php"); - - var options = new FileUploadOptions(); - options.fileKey="file"; - options.fileName=fileURL.substr(fileURL.lastIndexOf('/')+1); - options.mimeType="text/plain"; - - var headers={'headerParam':'headerValue'}; - - options.headers = headers; - - var ft = new FileTransfer(); - ft.onprogress = function(progressEvent) { - if (progressEvent.lengthComputable) { - loadingStatus.setPercentage(progressEvent.loaded / progressEvent.total); - } else { - loadingStatus.increment(); - } - }; - ft.upload(fileURL, uri, win, fail, options); - - -## FileUploadResult - -A `FileUploadResult` objeto se pasa a la devolución del éxito de la `FileTransfer` del objeto `upload()` método. - -### Propiedades - - * **bytesSent**: el número de bytes enviados al servidor como parte de la carga. (largo) - - * **responseCode**: código de respuesta HTTP el devuelto por el servidor. (largo) - - * **respuesta**: respuesta el HTTP devuelto por el servidor. (DOMString) - - * **cabeceras**: cabeceras de respuesta HTTP el por el servidor. (Objeto) - - * Actualmente compatible con iOS solamente. - -### iOS rarezas - - * No es compatible con `responseCode` o`bytesSent`. - -## descargar - -**Parámetros**: - - * **fuente**: dirección URL del servidor para descargar el archivo, como codificada por`encodeURI()`. - - * **objetivo**: Filesystem url que representa el archivo en el dispositivo. Para atrás compatibilidad, esto también puede ser la ruta de acceso completa del archivo en el dispositivo. (Ver [hacia atrás compatibilidad notas] debajo) - - * **successCallback**: una devolución de llamada que se pasa un `FileEntry` objeto. *(Función)* - - * **errorCallback**: una devolución de llamada que se ejecuta si se produce un error al recuperar los `FileEntry` . Invocado con un `FileTransferError` objeto. *(Función)* - - * **trustAllHosts**: parámetro opcional, por defecto es `false` . Si establece en `true` , acepta todos los certificados de seguridad. Esto es útil porque Android rechaza certificados autofirmados seguridad. No se recomienda para uso productivo. Compatible con iOS y Android. *(boolean)* - - * **Opciones**: parámetros opcionales, actualmente sólo soporta cabeceras (como autorización (autenticación básica), etc.). - -### Ejemplo - - // !! Assumes variable fileURL contains a valid URL to a path on the device, - // for example, cdvfile://localhost/persistent/path/to/downloads/ - - var fileTransfer = new FileTransfer(); - var uri = encodeURI("http://some.server.com/download.php"); - - fileTransfer.download( - uri, - fileURL, - function(entry) { - console.log("download complete: " + entry.toURL()); - }, - function(error) { - console.log("download error source " + error.source); - console.log("download error target " + error.target); - console.log("upload error code" + error.code); - }, - false, - { - headers: { - "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA==" - } - } - ); - - -### Rarezas de WP8 - - * Descargar pide se almacena en caché por aplicación nativa. Para evitar el almacenamiento en caché, pasar `if-Modified-Since` encabezado para descargar el método. - -## abortar - -Aborta a una transferencia en curso. El callback onerror se pasa un objeto FileTransferError que tiene un código de error de FileTransferError.ABORT_ERR. - -### Ejemplo - - // !! Assumes variable fileURL contains a valid URL to a text file on the device, - // for example, cdvfile://localhost/persistent/path/to/file.txt - - var win = function(r) { - console.log("Should not be called."); - } - - var fail = function(error) { - // error.code == FileTransferError.ABORT_ERR - alert("An error has occurred: Code = " + error.code); - console.log("upload error source " + error.source); - console.log("upload error target " + error.target); - } - - var options = new FileUploadOptions(); - options.fileKey="file"; - options.fileName="myphoto.jpg"; - options.mimeType="image/jpeg"; - - var ft = new FileTransfer(); - ft.upload(fileURL, encodeURI("http://some.server.com/upload.php"), win, fail, options); - ft.abort(); - - -## FileTransferError - -A `FileTransferError` objeto se pasa a un callback de error cuando se produce un error. - -### Propiedades - - * **código**: uno de los códigos de error predefinido enumerados a continuación. (Número) - - * **fuente**: URL a la fuente. (String) - - * **objetivo**: URL a la meta. (String) - - * **HTTP_STATUS**: código de estado HTTP. Este atributo sólo está disponible cuando se recibe un código de respuesta de la conexión HTTP. (Número) - - * **cuerpo** Cuerpo de la respuesta. Este atributo sólo está disponible cuando se recibe una respuesta de la conexión HTTP. (String) - - * **excepción**: cualquier e.getMessage o e.toString (String) - -### Constantes - - * 1 = `FileTransferError.FILE_NOT_FOUND_ERR` - * 2 = `FileTransferError.INVALID_URL_ERR` - * 3 = `FileTransferError.CONNECTION_ERR` - * 4 = `FileTransferError.ABORT_ERR` - * 5 = `FileTransferError.NOT_MODIFIED_ERR` - -## Al revés notas de compatibilidad - -Versiones anteriores de este plugin sólo aceptaría dispositivo-absoluto-archivo-rutas como la fuente de carga, o como destino para las descargas. Estos caminos normalmente sería de la forma - - /var/mobile/Applications//Documents/path/to/file (iOS) - /storage/emulated/0/path/to/file (Android) - - -Para atrás compatibilidad, estos caminos son aceptados todavía, y si su solicitud ha grabado caminos como éstos en almacenamiento persistente, entonces pueden seguir utilizarse. - -Estos caminos fueron expuestos anteriormente en el `fullPath` propiedad de `FileEntry` y `DirectoryEntry` objetos devueltos por el plugin de archivo. Las nuevas versiones del archivo plugin, sin embargo, ya no exponen estos caminos a JavaScript. - -Si va a actualizar a una nueva (1.0.0 o más reciente) versión del archivo y previamente han estado utilizando `entry.fullPath` como argumentos para `download()` o `upload()` , entonces tendrá que cambiar su código para usar URLs de sistema de archivos en su lugar. - -`FileEntry.toURL()`y `DirectoryEntry.toURL()` devolver un filesystem dirección URL de la forma - - cdvfile://localhost/persistent/path/to/file - - -que puede ser utilizado en lugar de la ruta del archivo absoluta tanto en `download()` y `upload()` los métodos. \ No newline at end of file diff --git a/plugins/cordova-plugin-file-transfer/doc/es/index.md b/plugins/cordova-plugin-file-transfer/doc/es/index.md deleted file mode 100644 index 981c991..0000000 --- a/plugins/cordova-plugin-file-transfer/doc/es/index.md +++ /dev/null @@ -1,262 +0,0 @@ - - -# cordova-plugin-file-transfer - -Este plugin te permite cargar y descargar archivos. - -Este plugin define global `FileTransfer` , `FileUploadOptions` constructores. - -Aunque en el ámbito global, no están disponibles hasta después de la `deviceready` evento. - - document.addEventListener ("deviceready", onDeviceReady, false); - function onDeviceReady() {console.log(FileTransfer)}; - - -## Instalación - - Cordova plugin añade cordova-plugin-file-transferencia - - -## Plataformas soportadas - -* Amazon fire OS -* Android -* BlackBerry 10 -* Explorador -* Firefox OS ** -* iOS -* Windows Phone 7 y 8 * -* Windows 8 -* Windows - -* *No son compatibles con `onprogress` ni `abort()` * - -** *No son compatibles con `onprogress` * - -# FileTransfer - -El `FileTransfer` objeto proporciona una manera de subir archivos mediante una solicitud HTTP de POST varias parte y para descargar archivos. - -## Propiedades - -* **OnProgress**: llama con un `ProgressEvent` cuando se transfiere un nuevo paquete de datos. *(Función)* - -## Métodos - -* **cargar**: envía un archivo a un servidor. - -* **Descargar**: descarga un archivo del servidor. - -* **abortar**: aborta una transferencia en curso. - -## subir - -**Parámetros**: - -* **fileURL**: URL de Filesystem que representa el archivo en el dispositivo. Para atrás compatibilidad, esto también puede ser la ruta de acceso completa del archivo en el dispositivo. (Ver [hacia atrás compatibilidad notas] debajo) - -* **servidor**: dirección URL del servidor para recibir el archivo, como codificada por`encodeURI()`. - -* **successCallback**: una devolución de llamada que se pasa un `FileUploadResult` objeto. *(Función)* - -* **errorCallback**: una devolución de llamada que se ejecuta si se produce un error recuperar la `FileUploadResult` . Invocado con un `FileTransferError` objeto. *(Función)* - -* **Opciones**: parámetros opcionales *(objeto)*. Teclas válidas: - - * **fileKey**: el nombre del elemento de formulario. Por defecto es `file` . (DOMString) - * **nombre de archivo**: el nombre del archivo a utilizar al guardar el archivo en el servidor. Por defecto es `image.jpg` . (DOMString) - * **httpMethod**: método HTTP el utilizar - o `PUT` o `POST` . Por defecto es `POST` . (DOMString) - * **mimeType**: el tipo mime de los datos para cargar. Por defecto es `image/jpeg` . (DOMString) - * **params**: un conjunto de pares clave/valor opcional para pasar en la petición HTTP. (Objeto) - * **chunkedMode**: Si desea cargar los datos en modo de transmisión fragmentado. Por defecto es `true` . (Boolean) - * **cabeceras**: un mapa de valores de encabezado nombre/cabecera. Utilice una matriz para especificar más de un valor. (Objeto) - -* **trustAllHosts**: parámetro opcional, por defecto es `false` . Si establece en `true` , acepta todos los certificados de seguridad. Esto es útil ya que Android rechaza certificados autofirmados seguridad. No se recomienda para uso productivo. Compatible con iOS y Android. *(boolean)* - -### Ejemplo - - // !! Asume fileURL variable contiene una dirección URL válida a un archivo de texto en el dispositivo, / / por ejemplo, ganar var cdvfile://localhost/persistent/path/to/file.txt = function (r) {console.log ("código =" + r.responseCode); - Console.log ("respuesta =" + r.response); - Console.log ("Sent =" + r.bytesSent);} - - var fallar = function (error) {alert ("ha ocurrido un error: código =" + error.code); - Console.log ("error al cargar el origen" + error.source); - Console.log ("upload error objetivo" + error.target);} - - var opciones = new FileUploadOptions(); - options.fileKey = "file"; - options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1); - options.mimeType = "text/plain"; - - var params = {}; - params.value1 = "prueba"; - params.value2 = "param"; - - options.params = params; - - var ft = new FileTransfer(); - Ft.upload (fileURL, encodeURI ("http://some.server.com/upload.php"), win, fail, opciones); - - -### Ejemplo con cabeceras de subir y eventos de progreso (Android y iOS solamente) - - function win(r) {console.log ("código =" + r.responseCode); - Console.log ("respuesta =" + r.response); - Console.log ("Sent =" + r.bytesSent);} - - function fail(error) {alert ("ha ocurrido un error: código =" + error.code); - Console.log ("error al cargar el origen" + error.source); - Console.log ("upload error objetivo" + error.target);} - - var uri = encodeURI ("http://some.server.com/upload.php"); - - var opciones = new FileUploadOptions(); - options.fileKey="file"; - options.fileName=fileURL.substr(fileURL.lastIndexOf('/')+1); - options.mimeType="text/plain"; - - cabeceras de var ={'headerParam':'headerValue'}; - - options.headers = encabezados; - - var ft = new FileTransfer(); - Ft.OnProgress = function(progressEvent) {si (progressEvent.lengthComputable) {loadingStatus.setPercentage(progressEvent.loaded / progressEvent.total); - } {loadingStatus.increment() más; - } - }; - Ft.upload (fileURL, uri, win, fail, opciones); - - -## FileUploadResult - -A `FileUploadResult` objeto se pasa a la devolución del éxito de la `FileTransfer` del objeto `upload()` método. - -### Propiedades - -* **bytesSent**: el número de bytes enviados al servidor como parte de la carga. (largo) - -* **responseCode**: código de respuesta HTTP el devuelto por el servidor. (largo) - -* **respuesta**: respuesta el HTTP devuelto por el servidor. (DOMString) - -* **cabeceras**: cabeceras de respuesta HTTP el por el servidor. (Objeto) - - * Actualmente compatible con iOS solamente. - -### iOS rarezas - -* No es compatible con `responseCode` o`bytesSent`. - -## descargar - -**Parámetros**: - -* **fuente**: dirección URL del servidor para descargar el archivo, como codificada por`encodeURI()`. - -* **objetivo**: Filesystem url que representa el archivo en el dispositivo. Para atrás compatibilidad, esto también puede ser la ruta de acceso completa del archivo en el dispositivo. (Ver [hacia atrás compatibilidad notas] debajo) - -* **successCallback**: una devolución de llamada que se pasa un `FileEntry` objeto. *(Función)* - -* **errorCallback**: una devolución de llamada que se ejecuta si se produce un error al recuperar los `FileEntry` . Invocado con un `FileTransferError` objeto. *(Función)* - -* **trustAllHosts**: parámetro opcional, por defecto es `false` . Si establece en `true` , acepta todos los certificados de seguridad. Esto es útil porque Android rechaza certificados autofirmados seguridad. No se recomienda para uso productivo. Compatible con iOS y Android. *(boolean)* - -* **Opciones**: parámetros opcionales, actualmente sólo soporta cabeceras (como autorización (autenticación básica), etc.). - -### Ejemplo - - // !! Asume fileURL variable contiene una dirección URL válida a un camino en el dispositivo, / / por ejemplo, File Transfer var cdvfile://localhost/persistent/path/to/downloads/ = new FileTransfer(); - var uri = encodeURI ("http://some.server.com/download.php"); - - fileTransfer.download (uri, fileURL, function(entry) {console.log ("descarga completa:" + entry.toURL()); - }, function(error) {console.log ("error al descargar el origen" + error.source); - Console.log ("descargar error objetivo" + error.target); - Console.log ("código de error de carga" + error.code); - }, falso, {encabezados: {"Autorización": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA =="}}); - - -## abortar - -Aborta a una transferencia en curso. El callback onerror se pasa un objeto FileTransferError que tiene un código de error de FileTransferError.ABORT_ERR. - -### Ejemplo - - // !! Asume fileURL variable contiene una dirección URL válida a un archivo de texto en el dispositivo, / / por ejemplo, ganar cdvfile://localhost/persistent/path/to/file.txt var function(r) = {console.log ("no se debe llamar.");} - - var fallar = function(error) {/ / error.code == FileTransferError.ABORT_ERR alert ("ha ocurrido un error: código =" + error.code); - Console.log ("error al cargar el origen" + error.source); - Console.log ("upload error objetivo" + error.target);} - - var opciones = new FileUploadOptions(); - options.fileKey="file"; - options.fileName="myphoto.jpg"; - options.mimeType="image/jpeg"; - - var ft = new FileTransfer(); - Ft.upload (fileURL, encodeURI ("http://some.server.com/upload.php"), win, fail, opciones); - Ft.Abort(); - - -## FileTransferError - -A `FileTransferError` objeto se pasa a un callback de error cuando se produce un error. - -### Propiedades - -* **código**: uno de los códigos de error predefinido enumerados a continuación. (Número) - -* **fuente**: URL a la fuente. (String) - -* **objetivo**: URL a la meta. (String) - -* **HTTP_STATUS**: código de estado HTTP. Este atributo sólo está disponible cuando se recibe un código de respuesta de la conexión HTTP. (Número) - -* **cuerpo** Cuerpo de la respuesta. Este atributo sólo está disponible cuando se recibe una respuesta de la conexión HTTP. (String) - -* **excepción**: cualquier e.getMessage o e.toString (String) - -### Constantes - -* 1 = `FileTransferError.FILE_NOT_FOUND_ERR` -* 2 = `FileTransferError.INVALID_URL_ERR` -* 3 = `FileTransferError.CONNECTION_ERR` -* 4 = `FileTransferError.ABORT_ERR` -* 5 = `FileTransferError.NOT_MODIFIED_ERR` - -## Al revés notas de compatibilidad - -Versiones anteriores de este plugin sólo aceptaría dispositivo-absoluto-archivo-rutas como la fuente de carga, o como destino para las descargas. Estos caminos normalmente sería de la forma - - /var/mobile/Applications//Documents/path/to/file (iOS) - /storage/emulated/0/path/to/file (Android) - - -Para atrás compatibilidad, estos caminos son aceptados todavía, y si su solicitud ha grabado caminos como éstos en almacenamiento persistente, entonces pueden seguir utilizarse. - -Estos caminos fueron expuestos anteriormente en el `fullPath` propiedad de `FileEntry` y `DirectoryEntry` objetos devueltos por el plugin de archivo. Las nuevas versiones del archivo plugin, sin embargo, ya no exponen estos caminos a JavaScript. - -Si va a actualizar a una nueva (1.0.0 o más reciente) versión del archivo y previamente han estado utilizando `entry.fullPath` como argumentos para `download()` o `upload()` , entonces tendrá que cambiar su código para usar URLs de sistema de archivos en su lugar. - -`FileEntry.toURL()`y `DirectoryEntry.toURL()` devolver un filesystem dirección URL de la forma - - cdvfile://localhost/persistent/path/to/file - - -que puede ser utilizado en lugar de la ruta del archivo absoluta tanto en `download()` y `upload()` los métodos. diff --git a/plugins/cordova-plugin-file-transfer/doc/fr/README.md b/plugins/cordova-plugin-file-transfer/doc/fr/README.md deleted file mode 100644 index ca3e18a..0000000 --- a/plugins/cordova-plugin-file-transfer/doc/fr/README.md +++ /dev/null @@ -1,270 +0,0 @@ - - -# cordova-plugin-file-transfer - -[![Build Status](https://travis-ci.org/apache/cordova-plugin-file-transfer.svg)](https://travis-ci.org/apache/cordova-plugin-file-transfer) - -Documentation du plugin : - -Ce plugin vous permet de télécharger des fichiers. - -Ce plugin définit global `FileTransfer` , `FileUploadOptions` constructeurs. - -Bien que dans la portée globale, ils ne sont pas disponibles jusqu'après la `deviceready` événement. - - document.addEventListener (« deviceready », onDeviceReady, false) ; - function onDeviceReady() {console.log(FileTransfer);} - - -## Installation - - cordova plugin add cordova-plugin-file-transfer - - -## Plates-formes supportées - - * Amazon Fire OS - * Android - * BlackBerry 10 - * Navigateur - * Firefox OS ** - * iOS - * Windows Phone 7 et 8 * - * Windows 8 - * Windows - -\ * *Ne supportent pas `onprogress` ni `abort()` * - -\ ** *Ne prennent pas en charge les `onprogress` * - -# Transfert de fichiers - -L'objet de `FileTransfer` fournit un moyen de télécharger des fichiers à l'aide d'une requête HTTP multi-part POST ou PUT et pour télécharger des fichiers. - -## Propriétés - - * **onprogress** : fonction appelée avec un `ProgressEvent` à chaque fois qu'un nouveau segment de données est transféré. *(Function)* - -## Méthodes - - * **upload** : envoie un fichier à un serveur. - - * **download** : télécharge un fichier depuis un serveur. - - * **abort** : annule le transfert en cours. - -## upload - -**Paramètres**: - - * **fileURL** : système de fichiers URL représentant le fichier sur le périphérique. Pour la compatibilité ascendante, cela peut aussi être le chemin complet du fichier sur le périphérique. (Voir [Backwards Compatibility Notes] ci-dessous) - - * **server** : l'URL du serveur destiné à recevoir le fichier, encodée via `encodeURI()`. - - * **successCallback**: un rappel passé un `FileUploadResult` objet. *(Fonction)* - - * **errorCallback**: un rappel qui s'exécute si une erreur survient récupérer la `FileUploadResult` . Appelée avec un `FileTransferError` objet. *(Fonction)* - - * **options**: paramètres facultatifs *(objet)*. Clés valides : - - * **fileKey**: le nom de l'élément form. Valeur par défaut est `file` . (DOMString) - * **fileName**: le nom de fichier à utiliser lorsque vous enregistrez le fichier sur le serveur. Valeur par défaut est `image.jpg` . (DOMString) - * **httpMethod**: méthode de The HTTP à utiliser - soit `PUT` ou `POST` . Valeur par défaut est `POST` . (DOMString) - * **type MIME**: le type mime des données à télécharger. Valeur par défaut est `image/jpeg` . (DOMString) - * **params**: un ensemble de paires clé/valeur facultative pour passer dans la requête HTTP. (Objet) - * **chunkedMode**: s'il faut télécharger les données en mode streaming mémorisé en bloc. Valeur par défaut est `true` . (Boolean) - * **headers**: une carte des valeurs d'en-tête en-tête/nom. Un tableau permet de spécifier plusieurs valeurs. Sur iOS, FireOS et Android, si un en-tête nommé Content-Type n'est présent, les données de formulaire multipart servira pas. (Object) - * **httpMethod**: The HTTP méthode à utiliser par exemple poster ou mis. Par défaut, `message`. (DOMString) - - * **trustAllHosts**: paramètre facultatif, valeur par défaut est `false` . Si la valeur est `true` , il accepte tous les certificats de sécurité. Ceci est utile car Android rejette des certificats auto-signés. N'est pas recommandé pour une utilisation en production. Supporté sur Android et iOS. *(booléen)* - -### Exemple - - // !! Suppose fileURL variable contient une URL valide dans un fichier texte sur le périphérique, / / par exemple, cdvfile://localhost/persistent/path/to/file.txt var win = function (r) {console.log ("Code =" + r.responseCode) ; - Console.log ("réponse =" + r.response) ; - Console.log ("envoyés =" + r.bytesSent);} - - échouer var = function (erreur) {alert ("une erreur est survenue : Code =" + error.code) ; - Console.log (« source de l'erreur de téléchargement » + error.source) ; - Console.log ("erreur de téléchargement cible" + error.target);} - - options de var = new FileUploadOptions() ; - options.fileKey = « fichier » ; - options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1) ; - options.mimeType = « text/plain » ; - - var params = {} ; - params.value1 = « test » ; - params.Value2 = « param » ; - - options.params = params ; - - ft var = new FileTransfer() ; - ft.upload (fileURL, encodeURI ("http://some.server.com/upload.php"), win, fail, options) ; - - -### Exemple avec téléchargement du Header et des Progress Events (Android et iOS uniquement) - - function win(r) {console.log ("Code =" + r.responseCode) ; - Console.log ("réponse =" + r.response) ; - Console.log ("envoyés =" + r.bytesSent);} - - function fail(error) {alert ("une erreur est survenue : Code =" + error.code) ; - Console.log (« source de l'erreur de téléchargement » + error.source) ; - Console.log ("erreur de téléchargement cible" + error.target);} - - var uri = encodeURI ("http://some.server.com/upload.php") ; - - options de var = new FileUploadOptions() ; - options.fileKey="file" ; - options.fileName=fileURL.substr(fileURL.lastIndexOf('/')+1) ; - options.mimeType="text/plain" ; - - en-têtes var ={'headerParam':'headerValue'} ; - - options.Headers = en-têtes ; - - ft var = new FileTransfer() ; - ft.OnProgress = function(progressEvent) {si (progressEvent.lengthComputable) {loadingStatus.setPercentage(progressEvent.loaded / progressEvent.total) ; - } else {loadingStatus.increment() ; - } - }; - ft.upload (fileURL, uri, win, fail, options) ; - - -## FileUploadResult - -A `FileUploadResult` objet est passé au rappel de succès la `FileTransfer` de l'objet `upload()` méthode. - -### Propriétés - - * **bytesSent** : le nombre d'octets envoyés au serveur dans le cadre du téléchargement. (long) - - * **responseCode** : le code de réponse HTTP retourné par le serveur. (long) - - * **response** : la réponse HTTP renvoyée par le serveur. (DOMString) - - * **en-têtes** : en-têtes de réponse HTTP par le serveur. (Objet) - - * Actuellement pris en charge sur iOS seulement. - -### Notes au sujet d'iOS - - * Ne prend pas en charge les propriétés `responseCode` et `bytesSent`. - -## download - -**Paramètres**: - - * **source** : l'URL du serveur depuis lequel télécharger le fichier, encodée via `encodeURI()`. - - * **target** : système de fichiers url représentant le fichier sur le périphérique. Pour la compatibilité ascendante, cela peut aussi être le chemin complet du fichier sur le périphérique. (Voir [Backwards Compatibility Notes] ci-dessous) - - * **successCallback** : une callback de succès à laquelle est passée un objet `FileEntry`. *(Function)* - - * **errorCallback**: un rappel qui s'exécute si une erreur se produit lors de la récupération du `FileEntry` . Appelée avec un `FileTransferError` objet. *(Fonction)* - - * **trustAllHosts**: paramètre facultatif, valeur par défaut est `false` . Si la valeur est `true` , il accepte tous les certificats de sécurité. Ceci peut être utile car Android rejette les certificats auto-signés. N'est pas recommandé pour une utilisation en production. Supporté sur Android et iOS. *(booléen)* - - * **options** : paramètres facultatifs, seules les en-têtes sont actuellement supportées (par exemple l'autorisation (authentification basique), etc.). - -### Exemple - - // !! Suppose fileURL variable contient une URL valide vers un chemin d'accès sur le périphérique, / / par exemple, transfert de fichiers var cdvfile://localhost/persistent/path/to/downloads/ = new FileTransfer() ; - var uri = encodeURI ("http://some.server.com/download.php") ; - - fileTransfer.download (uri, fileURL, function(entry) {console.log ("téléchargement complet:" + entry.toURL()) ; - }, function(error) {console.log (« source de l'erreur de téléchargement » + error.source) ; - Console.log (« erreur de téléchargement cible » + error.target) ; - Console.log (« code d'erreur de téléchargement » + error.code) ; - }, faux, {en-têtes: {« Autorisation »: « dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA base == "}}) ; - - -### Quirks wp8 - - * Télécharger demande est mis en cache par l'implémentation native. Pour éviter la mise en cache, pass `if-Modified-Since` en-tête Télécharger méthode. - -## abort - -Abandonne un transfert en cours. Le rappel onerror est passé à un objet FileTransferError qui a un code d'erreur de FileTransferError.ABORT_ERR. - -### Exemple - - // !! Suppose fileURL variable contient une URL valide dans un fichier texte sur le périphérique, / / par exemple, cdvfile://localhost/persistent/path/to/file.txt var win = function(r) {console.log ("ne devrait pas être appelée.");} - - var fail = function(error) {/ / error.code == FileTransferError.ABORT_ERR alert ("une erreur est survenue : Code =" + error.code) ; - Console.log (« source de l'erreur de téléchargement » + error.source) ; - Console.log ("erreur de téléchargement cible" + error.target);} - - options de var = new FileUploadOptions() ; - options.fileKey="file" ; - options.fileName="myphoto.jpg" ; - options.mimeType="image/jpeg" ; - - ft var = new FileTransfer() ; - ft.upload (fileURL, encodeURI ("http://some.server.com/upload.php"), win, fail, options) ; - ft.Abort() ; - - -## FileTransferError - -A `FileTransferError` objet est passé à un rappel d'erreur lorsqu'une erreur survient. - -### Propriétés - - * **code** : l'un des codes d'erreur prédéfinis énumérés ci-dessous. (Number) - - * **source** : l'URI de la source. (String) - - * **target**: l'URI de la destination. (String) - - * **http_status** : code d'état HTTP. Cet attribut n'est disponible que lorsqu'un code de réponse est fourni via la connexion HTTP. (Number) - - * **corps** Corps de réponse. Cet attribut n'est disponible que lorsqu'une réponse est reçue de la connexion HTTP. (String) - - * **exception**: soit e.getMessage ou e.toString (String) - -### Constantes - - * 1 = `FileTransferError.FILE_NOT_FOUND_ERR` - * 2 = `FileTransferError.INVALID_URL_ERR` - * 3 = `FileTransferError.CONNECTION_ERR` - * 4 = `FileTransferError.ABORT_ERR` - * 5 = `FileTransferError.NOT_MODIFIED_ERR` - -## Backwards Compatibility Notes - -Les versions précédentes de ce plugin n'accepterait périphérique--fichier-chemins d'accès absolus comme source pour les téléchargements, ou comme cible pour les téléchargements. Ces chemins seraient généralement de la forme - - / var/mobile/Applications/< application UUID >/Documents/chemin/vers/fichier (iOS), /storage/emulated/0/path/to/file (Android) - - -Pour vers l'arrière la compatibilité, ces chemins sont toujours acceptés, et si votre application a enregistré des chemins comme celles-ci dans un stockage persistant, alors ils peuvent continuer à être utilisé. - -Ces chemins ont été précédemment exposés dans le `fullPath` propriété de `FileEntry` et `DirectoryEntry` les objets retournés par le fichier plugin. Nouvelles versions du fichier plugin, cependant, ne plus exposent ces chemins à JavaScript. - -Si vous migrez vers une nouvelle (1.0.0 ou plus récent) version de fichier et vous avez précédemment utilisé `entry.fullPath` comme arguments à `download()` ou `upload()` , alors vous aurez besoin de modifier votre code pour utiliser le système de fichiers URL au lieu de cela. - -`FileEntry.toURL()`et `DirectoryEntry.toURL()` retournent une URL de système de fichiers du formulaire - - cdvfile://localhost/persistent/path/to/file - - -qui peut être utilisé à la place le chemin d'accès absolu au fichier dans les deux `download()` et `upload()` méthodes. \ No newline at end of file diff --git a/plugins/cordova-plugin-file-transfer/doc/fr/index.md b/plugins/cordova-plugin-file-transfer/doc/fr/index.md deleted file mode 100644 index 6b2bce0..0000000 --- a/plugins/cordova-plugin-file-transfer/doc/fr/index.md +++ /dev/null @@ -1,261 +0,0 @@ - - -# cordova-plugin-file-transfer - -Ce plugin vous permet de télécharger des fichiers. - -Ce plugin définit global `FileTransfer` , `FileUploadOptions` constructeurs. - -Bien que dans la portée globale, ils ne sont pas disponibles jusqu'après la `deviceready` événement. - - document.addEventListener (« deviceready », onDeviceReady, false) ; - function onDeviceReady() {console.log(FileTransfer);} - - -## Installation - - Cordova plugin ajouter cordova-plugin-file-transfert - - -## Plates-formes prises en charge - -* Amazon Fire OS -* Android -* BlackBerry 10 -* Navigateur -* Firefox OS ** -* iOS -* Windows Phone 7 et 8 * -* Windows 8 -* Windows - -* *Ne supportent pas `onprogress` ni `abort()` * - -** *Ne prennent pas en charge `onprogress` * - -# Transfert de fichiers - -Le `FileTransfer` objet fournit un moyen de télécharger des fichiers à l'aide d'une requête HTTP de la poste plusieurs partie et pour télécharger des fichiers aussi bien. - -## Propriétés - -* **onprogress** : fonction appelée avec un `ProgressEvent` à chaque fois qu'un nouveau segment de données est transféré. *(Function)* - -## Méthodes - -* **upload** : envoie un fichier à un serveur. - -* **download** : télécharge un fichier depuis un serveur. - -* **abort** : annule le transfert en cours. - -## upload - -**Paramètres**: - -* **fileURL** : système de fichiers URL représentant le fichier sur le périphérique. Pour la compatibilité ascendante, cela peut aussi être le chemin complet du fichier sur le périphérique. (Voir [Backwards Compatibility Notes] ci-dessous) - -* **server** : l'URL du serveur destiné à recevoir le fichier, encodée via `encodeURI()`. - -* **successCallback**: un rappel passé un `FileUploadResult` objet. *(Fonction)* - -* **errorCallback**: un rappel qui s'exécute si une erreur survient récupérer la `FileUploadResult` . Appelée avec un `FileTransferError` objet. *(Fonction)* - -* **options**: paramètres facultatifs *(objet)*. Clés valides : - - * **fileKey**: le nom de l'élément form. Valeur par défaut est `file` . (DOMString) - * **fileName**: le nom de fichier à utiliser lorsque vous enregistrez le fichier sur le serveur. Valeur par défaut est `image.jpg` . (DOMString) - * **httpMethod**: méthode de The HTTP à utiliser - soit `PUT` ou `POST` . Valeur par défaut est `POST` . (DOMString) - * **type MIME**: le type mime des données à télécharger. Valeur par défaut est `image/jpeg` . (DOMString) - * **params**: un ensemble de paires clé/valeur facultative pour passer dans la requête HTTP. (Objet) - * **chunkedMode**: s'il faut télécharger les données en mode streaming mémorisé en bloc. Valeur par défaut est `true` . (Boolean) - * **en-têtes**: une carte des valeurs d'en-tête en-tête/nom. Un tableau permet de spécifier plusieurs valeurs. (Objet) - -* **trustAllHosts**: paramètre facultatif, valeur par défaut est `false` . Si la valeur `true` , il accepte tous les certificats de sécurité. Ceci est utile car Android rejette des certificats auto-signés. Non recommandé pour une utilisation de production. Supporté sur Android et iOS. *(boolean)* - -### Exemple - - // !! Suppose fileURL variable contient une URL valide dans un fichier texte sur le périphérique, / / par exemple, cdvfile://localhost/persistent/path/to/file.txt var win = function (r) {console.log ("Code =" + r.responseCode) ; - Console.log ("réponse =" + r.response) ; - Console.log ("envoyés =" + r.bytesSent);} - - échouer var = function (erreur) {alert ("une erreur est survenue : Code =" + error.code) ; - Console.log (« source de l'erreur de téléchargement » + error.source) ; - Console.log ("erreur de téléchargement cible" + error.target);} - - options de var = new FileUploadOptions() ; - options.fileKey = « fichier » ; - options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1) ; - options.mimeType = « text/plain » ; - - var params = {} ; - params.value1 = « test » ; - params.Value2 = « param » ; - - options.params = params ; - - ft var = new FileTransfer() ; - ft.upload (fileURL, encodeURI ("http://some.server.com/upload.php"), win, fail, options) ; - - -### Exemple avec téléchargement du Header et des Progress Events (Android et iOS uniquement) - - function win(r) {console.log ("Code =" + r.responseCode) ; - Console.log ("réponse =" + r.response) ; - Console.log ("envoyés =" + r.bytesSent);} - - function fail(error) {alert ("une erreur est survenue : Code =" + error.code) ; - Console.log (« source de l'erreur de téléchargement » + error.source) ; - Console.log ("erreur de téléchargement cible" + error.target);} - - var uri = encodeURI ("http://some.server.com/upload.php") ; - - options de var = new FileUploadOptions() ; - options.fileKey="file" ; - options.fileName=fileURL.substr(fileURL.lastIndexOf('/')+1) ; - options.mimeType="text/plain" ; - - en-têtes var ={'headerParam':'headerValue'} ; - - options.Headers = en-têtes ; - - ft var = new FileTransfer() ; - ft.OnProgress = function(progressEvent) {si (progressEvent.lengthComputable) {loadingStatus.setPercentage(progressEvent.loaded / progressEvent.total) ; - } else {loadingStatus.increment() ; - } - }; - ft.upload (fileURL, uri, win, fail, options) ; - - -## FileUploadResult - -A `FileUploadResult` objet est passé au rappel de succès la `FileTransfer` de l'objet `upload()` méthode. - -### Propriétés - -* **bytesSent** : le nombre d'octets envoyés au serveur dans le cadre du téléchargement. (long) - -* **responseCode** : le code de réponse HTTP retourné par le serveur. (long) - -* **response** : la réponse HTTP renvoyée par le serveur. (DOMString) - -* **en-têtes** : en-têtes de réponse HTTP par le serveur. (Objet) - - * Actuellement pris en charge sur iOS seulement. - -### iOS Remarques - -* Ne prend pas en charge les propriétés `responseCode` et `bytesSent`. - -## download - -**Paramètres**: - -* **source** : l'URL du serveur depuis lequel télécharger le fichier, encodée via `encodeURI()`. - -* **target** : système de fichiers url représentant le fichier sur le périphérique. Pour vers l'arrière la compatibilité, cela peut aussi être le chemin d'accès complet du fichier sur le périphérique. (Voir [vers l'arrière compatibilité note] ci-dessous) - -* **successCallback** : une callback de succès à laquelle est passée un objet `FileEntry`. *(Function)* - -* **errorCallback**: un rappel qui s'exécute si une erreur se produit lors de la récupération du `FileEntry` . Appelée avec un `FileTransferError` objet. *(Fonction)* - -* **trustAllHosts**: paramètre facultatif, valeur par défaut est `false` . Si la valeur est `true` , il accepte tous les certificats de sécurité. Ceci peut être utile car Android rejette les certificats auto-signés. N'est pas recommandé pour une utilisation en production. Supporté sur Android et iOS. *(booléen)* - -* **options** : paramètres facultatifs, seules les en-têtes sont actuellement supportées (par exemple l'autorisation (authentification basique), etc.). - -### Exemple - - // !! Suppose fileURL variable contient une URL valide vers un chemin d'accès sur le périphérique, / / par exemple, transfert de fichiers var cdvfile://localhost/persistent/path/to/downloads/ = new FileTransfer() ; - var uri = encodeURI ("http://some.server.com/download.php") ; - - fileTransfer.download (uri, fileURL, function(entry) {console.log ("téléchargement complet:" + entry.toURL()) ; - }, function(error) {console.log (« source de l'erreur de téléchargement » + error.source) ; - Console.log (« erreur de téléchargement cible » + error.target) ; - Console.log (« code d'erreur de téléchargement » + error.code) ; - }, faux, {en-têtes: {« Autorisation »: « dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA base == "}}) ; - - -## abort - -Abandonne un transfert en cours. Le rappel onerror est passé à un objet FileTransferError qui a un code d'erreur de FileTransferError.ABORT_ERR. - -### Exemple - - // !! Suppose fileURL variable contient une URL valide dans un fichier texte sur le périphérique, / / par exemple, cdvfile://localhost/persistent/path/to/file.txt var win = function(r) {console.log ("ne devrait pas être appelée.");} - - var fail = function(error) {/ / error.code == FileTransferError.ABORT_ERR alert ("une erreur est survenue : Code =" + error.code) ; - Console.log (« source de l'erreur de téléchargement » + error.source) ; - Console.log ("erreur de téléchargement cible" + error.target);} - - options de var = new FileUploadOptions() ; - options.fileKey="file" ; - options.fileName="myphoto.jpg" ; - options.mimeType="image/jpeg" ; - - ft var = new FileTransfer() ; - ft.upload (fileURL, encodeURI ("http://some.server.com/upload.php"), win, fail, options) ; - ft.Abort() ; - - -## FileTransferError - -A `FileTransferError` objet est passé à un rappel d'erreur lorsqu'une erreur survient. - -### Propriétés - -* **code** : l'un des codes d'erreur prédéfinis énumérés ci-dessous. (Number) - -* **source** : l'URI de la source. (String) - -* **target**: l'URI de la destination. (String) - -* **http_status** : code d'état HTTP. Cet attribut n'est disponible que lorsqu'un code de réponse est fourni via la connexion HTTP. (Number) - -* **corps** Corps de réponse. Cet attribut n'est disponible que lorsqu'une réponse est reçue de la connexion HTTP. (String) - -* **exception**: soit e.getMessage ou e.toString (String) - -### Constantes - -* 1 = `FileTransferError.FILE_NOT_FOUND_ERR` -* 2 = `FileTransferError.INVALID_URL_ERR` -* 3 = `FileTransferError.CONNECTION_ERR` -* 4 = `FileTransferError.ABORT_ERR` -* 5 = `FileTransferError.NOT_MODIFIED_ERR` - -## Backwards Compatibility Notes - -Les versions précédentes de ce plugin n'accepterait périphérique--fichier-chemins d'accès absolus comme source pour les téléchargements, ou comme cible pour les téléchargements. Ces chemins seraient généralement de la forme - - / var/mobile/Applications/< application UUID >/Documents/chemin/vers/fichier (iOS), /storage/emulated/0/path/to/file (Android) - - -Pour vers l'arrière la compatibilité, ces chemins sont toujours acceptés, et si votre application a enregistré des chemins comme celles-ci dans un stockage persistant, alors ils peuvent continuer à être utilisé. - -Ces chemins ont été précédemment exposés dans le `fullPath` propriété de `FileEntry` et `DirectoryEntry` les objets retournés par le fichier plugin. Nouvelles versions du fichier plugin, cependant, ne plus exposent ces chemins à JavaScript. - -Si vous migrez vers une nouvelle (1.0.0 ou plus récent) version de fichier et vous avez précédemment utilisé `entry.fullPath` comme arguments à `download()` ou `upload()` , alors vous aurez besoin de modifier votre code pour utiliser le système de fichiers URL au lieu de cela. - -`FileEntry.toURL()`et `DirectoryEntry.toURL()` retournent une URL de système de fichiers du formulaire - - cdvfile://localhost/persistent/path/to/file - - -qui peut être utilisé à la place le chemin d'accès absolu au fichier dans les deux `download()` et `upload()` méthodes. diff --git a/plugins/cordova-plugin-file-transfer/doc/it/README.md b/plugins/cordova-plugin-file-transfer/doc/it/README.md deleted file mode 100644 index 74d4ef5..0000000 --- a/plugins/cordova-plugin-file-transfer/doc/it/README.md +++ /dev/null @@ -1,311 +0,0 @@ - - -# cordova-plugin-file-transfer - -[![Build Status](https://travis-ci.org/apache/cordova-plugin-file-transfer.svg)](https://travis-ci.org/apache/cordova-plugin-file-transfer) - -Documentazione plugin: - -Questo plugin permette di caricare e scaricare file. - -Questo plugin definisce globale `FileTransfer`, costruttori di `FileUploadOptions`. - -Anche se in ambito globale, non sono disponibili fino a dopo l'evento `deviceready`. - - document.addEventListener("deviceready", onDeviceReady, false); - function onDeviceReady() { - console.log(FileTransfer); - } - - -## Installazione - - cordova plugin add cordova-plugin-file-transfer - - -## Piattaforme supportate - - * Amazon fuoco OS - * Android - * BlackBerry 10 - * Browser - * Firefox OS** - * iOS - * Windows Phone 7 e 8 * - * Windows 8 - * Windows - -\ * *Non supportano `onprogress` né `abort()` * - -\ * * *Non supportano `onprogress` * - -# FileTransfer - -L'oggetto `FileTransfer` fornisce un modo per caricare i file utilizzando una richiesta HTTP multiparte POST o PUT e scaricare file pure. - -## Proprietà - - * **OnProgress**: chiamata con un `ProgressEvent` ogni volta che un nuovo blocco di dati viene trasferito. *(Funzione)* - -## Metodi - - * **caricare**: invia un file a un server. - - * **Scarica**: Scarica un file dal server. - - * **Abort**: interrompe un trasferimento in corso. - -## upload - -**Parametri**: - - * **fileURL**: Filesystem URL che rappresenta il file nel dispositivo. Per indietro la compatibilità, questo può anche essere il percorso completo del file sul dispositivo. (Vedere [indietro compatibilità rileva] qui sotto) - - * **server**: URL del server per ricevere il file, come codificato dal`encodeURI()`. - - * **successCallback**: un callback che viene passato un oggetto `FileUploadResult`. *(Funzione)* - - * **errorCallback**: un callback che viene eseguito se si verifica un errore di recupero `FileUploadResult`. Richiamato con un oggetto `FileTransferError`. *(Funzione)* - - * **opzioni**: parametri facoltativi *(oggetto)*. Chiavi valide: - - * **fileKey**: il nome dell'elemento form. Valore predefinito è `file` . (DOMString) - * **nome file**: il nome del file da utilizzare quando si salva il file sul server. Valore predefinito è `image.jpg` . (DOMString) - * **httpMethod**: metodo HTTP da utilizzare - `PUT` o `POST`. Impostazioni predefinite per `POST`. (DOMString) - * **mimeType**: il tipo mime dei dati da caricare. Impostazioni predefinite su `image/jpeg`. (DOMString) - * **params**: un insieme di coppie chiave/valore opzionale per passare nella richiesta HTTP. (Object) - * **chunkedMode**: se a caricare i dati in modalità streaming chunked. Impostazione predefinita è `true`. (Boolean) - * **headers**: una mappa di valori di intestazione e nome dell'intestazione. Utilizzare una matrice per specificare più di un valore. Su iOS, FireOS e Android, se è presente, un'intestazione Content-Type il nome dati form multipart non verranno utilizzati. (Object) - * **httpMethod**: metodo HTTP da utilizzare per esempio POST o PUT. Il valore predefinito è `POST`. (DOMString) - - * **trustAllHosts**: parametro opzionale, valore predefinito è `false` . Se impostata su `true` , accetta tutti i certificati di sicurezza. Questo è utile poiché Android respinge i certificati autofirmati sicurezza. Non raccomandato per uso in produzione. Supportato su Android e iOS. *(boolean)* - -### Esempio - - // !! Assumes variable fileURL contains a valid URL to a text file on the device, - // for example, cdvfile://localhost/persistent/path/to/file.txt - - var win = function (r) { - console.log("Code = " + r.responseCode); - console.log("Response = " + r.response); - console.log("Sent = " + r.bytesSent); - } - - var fail = function (error) { - alert("An error has occurred: Code = " + error.code); - console.log("upload error source " + error.source); - console.log("upload error target " + error.target); - } - - var options = new FileUploadOptions(); - options.fileKey = "file"; - options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1); - options.mimeType = "text/plain"; - - var params = {}; - params.value1 = "test"; - params.value2 = "param"; - - options.params = params; - - var ft = new FileTransfer(); - ft.upload(fileURL, encodeURI("http://some.server.com/upload.php"), win, fail, options); - - -### Esempio con intestazioni di caricare ed eventi Progress (Android e iOS solo) - - function win(r) { - console.log("Code = " + r.responseCode); - console.log("Response = " + r.response); - console.log("Sent = " + r.bytesSent); - } - - function fail(error) { - alert("An error has occurred: Code = " + error.code); - console.log("upload error source " + error.source); - console.log("upload error target " + error.target); - } - - var uri = encodeURI("http://some.server.com/upload.php"); - - var options = new FileUploadOptions(); - options.fileKey="file"; - options.fileName=fileURL.substr(fileURL.lastIndexOf('/')+1); - options.mimeType="text/plain"; - - var headers={'headerParam':'headerValue'}; - - options.headers = headers; - - var ft = new FileTransfer(); - ft.onprogress = function(progressEvent) { - if (progressEvent.lengthComputable) { - loadingStatus.setPercentage(progressEvent.loaded / progressEvent.total); - } else { - loadingStatus.increment(); - } - }; - ft.upload(fileURL, uri, win, fail, options); - - -## FileUploadResult - -Un oggetto `FileUploadResult` viene passato al metodo di callback del metodo `upload()` dell'oggetto `FileTransfer` successo. - -### Proprietà - - * **bytesSent**: il numero di byte inviati al server come parte dell'upload. (lungo) - - * **responseCode**: codice di risposta HTTP restituito dal server. (lungo) - - * **risposta**: risposta HTTP restituito dal server. (DOMString) - - * **intestazioni**: intestazioni di risposta HTTP dal server. (Oggetto) - - * Attualmente supportato solo iOS. - -### iOS stranezze - - * Non supporta `responseCode` o`bytesSent`. - -## Scarica - -**Parametri**: - - * **fonte**: URL del server per scaricare il file, come codificato dal`encodeURI()`. - - * **destinazione**: Filesystem url che rappresenta il file nel dispositivo. Per indietro la compatibilità, questo può anche essere il percorso completo del file sul dispositivo. (Vedere [indietro compatibilità rileva] qui sotto) - - * **successCallback**: un callback passato un `FileEntry` oggetto. *(Funzione)* - - * **errorCallback**: un callback che viene eseguito se si verifica un errore durante il recupero `FileEntry`. Richiamato con un oggetto `FileTransferError`. *(Function)* - - * **trustAllHosts**: parametro opzionale, valore predefinito è `false` . Se impostata su `true` , accetta tutti i certificati di sicurezza. Questo è utile perché Android respinge i certificati autofirmati sicurezza. Non raccomandato per uso in produzione. Supportato su Android e iOS. *(boolean)* - - * **opzioni**: parametri facoltativi, attualmente solo supporti intestazioni (ad esempio autorizzazione (autenticazione di base), ecc.). - -### Esempio - - // !! Assumes variable fileURL contains a valid URL to a path on the device, - // for example, cdvfile://localhost/persistent/path/to/downloads/ - - var fileTransfer = new FileTransfer(); - var uri = encodeURI("http://some.server.com/download.php"); - - fileTransfer.download( - uri, - fileURL, - function(entry) { - console.log("download complete: " + entry.toURL()); - }, - function(error) { - console.log("download error source " + error.source); - console.log("download error target " + error.target); - console.log("upload error code" + error.code); - }, - false, - { - headers: { - "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA==" - } - } - ); - - -### WP8 stranezze - - * Il download richiede è nella cache di implementazione nativa. Per evitare la memorizzazione nella cache, passare `if-Modified-Since` intestazione per metodo di download. - -## Abort - -Interrompe un trasferimento in corso. Il callback onerror viene passato un oggetto FileTransferError che presenta un codice di errore di FileTransferError.ABORT_ERR. - -### Esempio - - // !! Assumes variable fileURL contains a valid URL to a text file on the device, - // for example, cdvfile://localhost/persistent/path/to/file.txt - - var win = function(r) { - console.log("Should not be called."); - } - - var fail = function(error) { - // error.code == FileTransferError.ABORT_ERR - alert("An error has occurred: Code = " + error.code); - console.log("upload error source " + error.source); - console.log("upload error target " + error.target); - } - - var options = new FileUploadOptions(); - options.fileKey="file"; - options.fileName="myphoto.jpg"; - options.mimeType="image/jpeg"; - - var ft = new FileTransfer(); - ft.upload(fileURL, encodeURI("http://some.server.com/upload.php"), win, fail, options); - ft.abort(); - - -## FileTransferError - -Un oggetto `FileTransferError` viene passato a un callback di errore quando si verifica un errore. - -### Proprietà - - * **codice**: uno dei codici di errore predefiniti elencati di seguito. (Numero) - - * **fonte**: URL all'origine. (String) - - * **destinazione**: URL di destinazione. (String) - - * **http_status**: codice di stato HTTP. Questo attributo è disponibile solo quando viene ricevuto un codice di risposta della connessione HTTP. (Numero) - - * **body** Corpo della risposta. Questo attributo è disponibile solo quando viene ricevuta una risposta dalla connessione HTTP. (String) - - * **exception**: O e.getMessage o e.toString (String) - -### Costanti - - * 1 = `FileTransferError.FILE_NOT_FOUND_ERR` - * 2 = `FileTransferError.INVALID_URL_ERR` - * 3 = `FileTransferError.CONNECTION_ERR` - * 4 = `FileTransferError.ABORT_ERR` - * 5 = `FileTransferError.NOT_MODIFIED_ERR` - -## Note di compatibilità all'indietro - -Versioni precedenti di questo plugin accetterebbe solo dispositivo-assoluto-percorsi di file come origine per upload, o come destinazione per il download. Questi percorsi si sarebbero generalmente di forma - - /var/mobile/Applications//Documents/path/to/file (iOS) - /storage/emulated/0/path/to/file (Android) - - -Per indietro compatibilità, questi percorsi sono ancora accettati, e se l'applicazione ha registrato percorsi come questi in un archivio permanente, quindi possono continuare a essere utilizzato. - -Questi percorsi sono stati precedentemente esposti nella proprietà `fullPath` di `FileEntry` e oggetti `DirectoryEntry` restituiti dal File plugin. Nuove versioni del File plugin, tuttavia, non è più espongono questi percorsi a JavaScript. - -Se si esegue l'aggiornamento a una nuova (1.0.0 o più recente) versione del File e si hanno precedentemente utilizzato `entry.fullPath` come argomenti per `download()` o `upload()`, quindi sarà necessario cambiare il codice per utilizzare gli URL filesystem invece. - -`FileEntry.toURL()` e `DirectoryEntry.toURL()` restituiscono un filesystem URL del modulo - - cdvfile://localhost/persistent/path/to/file - - -che può essere utilizzato al posto del percorso assoluto nei metodi sia `download()` e `upload()`. \ No newline at end of file diff --git a/plugins/cordova-plugin-file-transfer/doc/it/index.md b/plugins/cordova-plugin-file-transfer/doc/it/index.md deleted file mode 100644 index e1b74e3..0000000 --- a/plugins/cordova-plugin-file-transfer/doc/it/index.md +++ /dev/null @@ -1,302 +0,0 @@ - - -# cordova-plugin-file-transfer - -Questo plugin permette di caricare e scaricare file. - -Questo plugin definisce globale `FileTransfer`, costruttori di `FileUploadOptions`. - -Anche se in ambito globale, non sono disponibili fino a dopo l'evento `deviceready`. - - document.addEventListener("deviceready", onDeviceReady, false); - function onDeviceReady() { - console.log(FileTransfer); - } - - -## Installazione - - cordova plugin add cordova-plugin-file-transfer - - -## Piattaforme supportate - -* Amazon fuoco OS -* Android -* BlackBerry 10 -* Browser -* Firefox OS** -* iOS -* Windows Phone 7 e 8 * -* Windows 8 -* Windows - -* *Supporto `onprogress` né `abort()`* - -** *Non supportano `onprogress`* - -# FileTransfer - -L'oggetto `FileTransfer` fornisce un modo per caricare i file utilizzando una richiesta HTTP di POST più parte e scaricare file pure. - -## Proprietà - -* **OnProgress**: chiamata con un `ProgressEvent` ogni volta che un nuovo blocco di dati viene trasferito. *(Funzione)* - -## Metodi - -* **caricare**: invia un file a un server. - -* **Scarica**: Scarica un file dal server. - -* **Abort**: interrompe un trasferimento in corso. - -## caricare - -**Parametri**: - -* **fileURL**: Filesystem URL che rappresenta il file nel dispositivo. Per indietro la compatibilità, questo può anche essere il percorso completo del file sul dispositivo. (Vedere [indietro compatibilità rileva] qui sotto) - -* **server**: URL del server per ricevere il file, come codificato dal`encodeURI()`. - -* **successCallback**: un callback che viene passato un oggetto `FileUploadResult`. *(Funzione)* - -* **errorCallback**: un callback che viene eseguito se si verifica un errore di recupero `FileUploadResult`. Richiamato con un oggetto `FileTransferError`. *(Funzione)* - -* **opzioni**: parametri facoltativi *(oggetto)*. Chiavi valide: - - * **fileKey**: il nome dell'elemento form. Valore predefinito è `file` . (DOMString) - * **nome file**: il nome del file da utilizzare quando si salva il file sul server. Valore predefinito è `image.jpg` . (DOMString) - * **httpMethod**: metodo HTTP da utilizzare - `PUT` o `POST`. Impostazioni predefinite per `POST`. (DOMString) - * **mimeType**: il tipo mime dei dati da caricare. Impostazioni predefinite su `image/jpeg`. (DOMString) - * **params**: un insieme di coppie chiave/valore opzionale per passare nella richiesta HTTP. (Object) - * **chunkedMode**: se a caricare i dati in modalità streaming chunked. Impostazione predefinita è `true`. (Boolean) - * **headers**: mappa di valori nome/intestazione intestazione. Utilizzare una matrice per specificare più valori. (Object) - -* **trustAllHosts**: parametro opzionale, valore predefinito è `false` . Se impostata su `true` , accetta tutti i certificati di sicurezza. Questo è utile poiché Android respinge i certificati autofirmati sicurezza. Non raccomandato per uso in produzione. Supportato su Android e iOS. *(boolean)* - -### Esempio - - // !! Assumes variable fileURL contains a valid URL to a text file on the device, - // for example, cdvfile://localhost/persistent/path/to/file.txt - - var win = function (r) { - console.log("Code = " + r.responseCode); - console.log("Response = " + r.response); - console.log("Sent = " + r.bytesSent); - } - - var fail = function (error) { - alert("An error has occurred: Code = " + error.code); - console.log("upload error source " + error.source); - console.log("upload error target " + error.target); - } - - var options = new FileUploadOptions(); - options.fileKey = "file"; - options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1); - options.mimeType = "text/plain"; - - var params = {}; - params.value1 = "test"; - params.value2 = "param"; - - options.params = params; - - var ft = new FileTransfer(); - ft.upload(fileURL, encodeURI("http://some.server.com/upload.php"), win, fail, options); - - -### Esempio con intestazioni di caricare ed eventi Progress (Android e iOS solo) - - function win(r) { - console.log("Code = " + r.responseCode); - console.log("Response = " + r.response); - console.log("Sent = " + r.bytesSent); - } - - function fail(error) { - alert("An error has occurred: Code = " + error.code); - console.log("upload error source " + error.source); - console.log("upload error target " + error.target); - } - - var uri = encodeURI("http://some.server.com/upload.php"); - - var options = new FileUploadOptions(); - options.fileKey="file"; - options.fileName=fileURL.substr(fileURL.lastIndexOf('/')+1); - options.mimeType="text/plain"; - - var headers={'headerParam':'headerValue'}; - - options.headers = headers; - - var ft = new FileTransfer(); - ft.onprogress = function(progressEvent) { - if (progressEvent.lengthComputable) { - loadingStatus.setPercentage(progressEvent.loaded / progressEvent.total); - } else { - loadingStatus.increment(); - } - }; - ft.upload(fileURL, uri, win, fail, options); - - -## FileUploadResult - -Un oggetto `FileUploadResult` viene passato al metodo di callback del metodo `upload()` dell'oggetto `FileTransfer` successo. - -### Proprietà - -* **bytesSent**: il numero di byte inviati al server come parte dell'upload. (lungo) - -* **responseCode**: codice di risposta HTTP restituito dal server. (lungo) - -* **risposta**: risposta HTTP restituito dal server. (DOMString) - -* **intestazioni**: intestazioni di risposta HTTP dal server. (Oggetto) - - * Attualmente supportato solo iOS. - -### iOS stranezze - -* Non supporta `responseCode` o`bytesSent`. - -## Scarica - -**Parametri**: - -* **fonte**: URL del server per scaricare il file, come codificato dal`encodeURI()`. - -* **destinazione**: Filesystem url che rappresenta il file nel dispositivo. Per indietro la compatibilità, questo può anche essere il percorso completo del file sul dispositivo. (Vedere [indietro compatibilità rileva] qui sotto) - -* **successCallback**: un callback passato un `FileEntry` oggetto. *(Funzione)* - -* **errorCallback**: un callback che viene eseguito se si verifica un errore durante il recupero `FileEntry`. Richiamato con un oggetto `FileTransferError`. *(Function)* - -* **trustAllHosts**: parametro opzionale, valore predefinito è `false` . Se impostata su `true` , accetta tutti i certificati di sicurezza. Questo è utile perché Android respinge i certificati autofirmati sicurezza. Non raccomandato per uso in produzione. Supportato su Android e iOS. *(boolean)* - -* **opzioni**: parametri facoltativi, attualmente solo supporti intestazioni (ad esempio autorizzazione (autenticazione di base), ecc.). - -### Esempio - - // !! Assumes variable fileURL contains a valid URL to a path on the device, - // for example, cdvfile://localhost/persistent/path/to/downloads/ - - var fileTransfer = new FileTransfer(); - var uri = encodeURI("http://some.server.com/download.php"); - - fileTransfer.download( - uri, - fileURL, - function(entry) { - console.log("download complete: " + entry.toURL()); - }, - function(error) { - console.log("download error source " + error.source); - console.log("download error target " + error.target); - console.log("upload error code" + error.code); - }, - false, - { - headers: { - "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA==" - } - } - ); - - -## Abort - -Interrompe un trasferimento in corso. Il callback onerror viene passato un oggetto FileTransferError che presenta un codice di errore di FileTransferError.ABORT_ERR. - -### Esempio - - // !! Assumes variable fileURL contains a valid URL to a text file on the device, - // for example, cdvfile://localhost/persistent/path/to/file.txt - - var win = function(r) { - console.log("Should not be called."); - } - - var fail = function(error) { - // error.code == FileTransferError.ABORT_ERR - alert("An error has occurred: Code = " + error.code); - console.log("upload error source " + error.source); - console.log("upload error target " + error.target); - } - - var options = new FileUploadOptions(); - options.fileKey="file"; - options.fileName="myphoto.jpg"; - options.mimeType="image/jpeg"; - - var ft = new FileTransfer(); - ft.upload(fileURL, encodeURI("http://some.server.com/upload.php"), win, fail, options); - ft.abort(); - - -## FileTransferError - -Un oggetto `FileTransferError` viene passato a un callback di errore quando si verifica un errore. - -### Proprietà - -* **codice**: uno dei codici di errore predefiniti elencati di seguito. (Numero) - -* **fonte**: URL all'origine. (String) - -* **destinazione**: URL di destinazione. (String) - -* **http_status**: codice di stato HTTP. Questo attributo è disponibile solo quando viene ricevuto un codice di risposta della connessione HTTP. (Numero) - -* **body** Corpo della risposta. Questo attributo è disponibile solo quando viene ricevuta una risposta dalla connessione HTTP. (String) - -* **exception**: O e.getMessage o e.toString (String) - -### Costanti - -* 1 = `FileTransferError.FILE_NOT_FOUND_ERR` -* 2 = `FileTransferError.INVALID_URL_ERR` -* 3 = `FileTransferError.CONNECTION_ERR` -* 4 = `FileTransferError.ABORT_ERR` -* 5 = `FileTransferError.NOT_MODIFIED_ERR` - -## Note di compatibilità all'indietro - -Versioni precedenti di questo plugin accetterebbe solo dispositivo-assoluto-percorsi di file come origine per upload, o come destinazione per il download. Questi percorsi si sarebbero generalmente di forma - - /var/mobile/Applications//Documents/path/to/file (iOS) - /storage/emulated/0/path/to/file (Android) - - -Per indietro compatibilità, questi percorsi sono ancora accettati, e se l'applicazione ha registrato percorsi come questi in un archivio permanente, quindi possono continuare a essere utilizzato. - -Questi percorsi sono stati precedentemente esposti nella proprietà `fullPath` di `FileEntry` e oggetti `DirectoryEntry` restituiti dal File plugin. Nuove versioni del File plugin, tuttavia, non è più espongono questi percorsi a JavaScript. - -Se si esegue l'aggiornamento a una nuova (1.0.0 o più recente) versione del File e si hanno precedentemente utilizzato `entry.fullPath` come argomenti per `download()` o `upload()`, quindi sarà necessario cambiare il codice per utilizzare gli URL filesystem invece. - -`FileEntry.toURL()` e `DirectoryEntry.toURL()` restituiscono un filesystem URL del modulo - - cdvfile://localhost/persistent/path/to/file - - -che può essere utilizzato al posto del percorso assoluto nei metodi sia `download()` e `upload()`. diff --git a/plugins/cordova-plugin-file-transfer/doc/ja/README.md b/plugins/cordova-plugin-file-transfer/doc/ja/README.md deleted file mode 100644 index a8156a2..0000000 --- a/plugins/cordova-plugin-file-transfer/doc/ja/README.md +++ /dev/null @@ -1,311 +0,0 @@ - - -# cordova-plugin-file-transfer - -[![Build Status](https://travis-ci.org/apache/cordova-plugin-file-transfer.svg)](https://travis-ci.org/apache/cordova-plugin-file-transfer) - -プラグインã®ãƒžãƒ‹ãƒ¥ã‚¢ãƒ«: - -ã“ã®ãƒ—ラグインã¯ã€ã‚¢ãƒƒãƒ—ロードã—ã€ãƒ•ã‚¡ã‚¤ãƒ«ã‚’ダウンロードã™ã‚‹ã“ã¨ãŒã§ãã¾ã™ã€‚ - -ã“ã®ãƒ—ラグインã§ã¯ã€ã‚°ãƒ­ãƒ¼ãƒãƒ« `FileTransfer`ã€`FileUploadOptions` コンス トラクターを定義ã—ã¾ã™ã€‚ - -グローãƒãƒ« スコープã§ã¯ä½¿ç”¨ã§ãã¾ã›ã‚“ã¾ã§ `deviceready` イベントã®å¾Œã§ã™ã€‚ - - document.addEventListener("deviceready", onDeviceReady, false); - function onDeviceReady() { - console.log(FileTransfer); - } - - -## インストール - - cordova plugin add cordova-plugin-file-transfer - - -## サãƒãƒ¼ãƒˆã•ã‚Œã¦ã„るプラットフォーム - - * ã‚¢ãƒžã‚¾ãƒ³ç« OS - * アンドロイド - * ブラックベリー 10 - * ブラウザー - * Firefox ã® OS * * - * iOS - * Windows Phone 7 㨠8 * - * Windows 8 - * Windows - -\ * * `Onprogress`ã‚‚`abort()`をサãƒãƒ¼ãƒˆã—ã¦ã„ã¾ã›ã‚“。* - -\ * * * `Onprogress`をサãƒãƒ¼ãƒˆã—ã¦ã„ã¾ã›ã‚“。* - -# 出色 - -`出色`オブジェクトã¯ã€HTTP マルãƒãƒ‘ート POST ã¾ãŸã¯ PUT è¦æ±‚を使用ã—ã¦ãƒ•ã‚¡ã‚¤ãƒ«ã‚’アップロードã—ã€åŒæ§˜ã«ãƒ•ã‚¡ã‚¤ãƒ«ã‚’ダウンロードã™ã‚‹æ–¹æ³•ã‚’æä¾›ã—ã¾ã™ã€‚ - -## プロパティ - - * **onprogress**: ã¨å‘¼ã°ã‚Œã‚‹ã€ `ProgressEvent` データã®æ–°ã—ã„ãƒãƒ£ãƒ³ã‚¯ãŒè»¢é€ã•ã‚Œã‚‹ãŸã³ã«ã€‚*(機能)* - -## メソッド - - * **アップロード**: サーãƒãƒ¼ã«ãƒ•ã‚¡ã‚¤ãƒ«ã‚’é€ä¿¡ã—ã¾ã™ã€‚ - - * **ダウンロード**: サーãƒãƒ¼ã‹ã‚‰ãƒ•ã‚¡ã‚¤ãƒ«ã‚’ダウンロードã—ã¾ã™ã€‚ - - * **中止**: 進行中ã®è»¢é€ã‚’中止ã—ã¾ã™ã€‚ - -## upload - -**パラメーター**: - - * **fileURL**: デãƒã‚¤ã‚¹ä¸Šã®ãƒ•ã‚¡ã‚¤ãƒ«ã‚’表ã™ãƒ•ã‚¡ã‚¤ãƒ«ã‚·ã‚¹ãƒ†ãƒ  URL。 下ä½äº’æ›æ€§ã¯ã€ã“ã®ã“ã¨ã‚‚ã€ãƒ‡ãƒã‚¤ã‚¹ä¸Šã®ãƒ•ã‚¡ã‚¤ãƒ«ã®å®Œå…¨ãƒ‘スã§ã‚ã‚Šã¾ã™ã€‚ (å‚ç…§ã—ã¦ãã ã•ã„ [後方互æ›æ€§ãƒ¡ãƒ¢] ã®ä¸‹) - - * **サーãƒãƒ¼**: ã«ã‚ˆã£ã¦ç¬¦å·åŒ–ã•ã‚Œã‚‹ã‚ˆã†ã«ã€ãƒ•ã‚¡ã‚¤ãƒ«ã‚’å—ä¿¡ã™ã‚‹ã‚µãƒ¼ãƒãƒ¼ã® URL`encodeURI()`. - - * **successCallback**: `FileUploadResult` オブジェクトãŒæ¸¡ã•ã‚Œã‚‹ã‚³ãƒ¼ãƒ«ãƒãƒƒã‚¯ã€‚*(機能)* - - * **errorCallback**: エラー `FileUploadResult` ã‚’å–å¾—ã™ã‚‹ãŒç™ºç”Ÿã—ãŸå ´åˆã«å®Ÿè¡Œã•ã‚Œã‚‹ã‚³ãƒ¼ãƒ«ãƒãƒƒã‚¯ã€‚`FileTransferError` オブジェクトを使ã£ã¦å‘¼ã³å‡ºã•ã‚Œã¾ã™ã€‚*(機能)* - - * **オプション**: çœç•¥å¯èƒ½ãªãƒ‘ラメーター *(オブジェクト)*。有効ãªã‚­ãƒ¼: - - * **fileKey**: フォームè¦ç´ ã®åå‰ã€‚既定値㯠`file` ã§ã™ã€‚(,) - * **ファイルå**: ファイルåã€ã‚µãƒ¼ãƒãƒ¼ä¸Šã®ãƒ•ã‚¡ã‚¤ãƒ«ã‚’ä¿å­˜ã™ã‚‹ã¨ãã«ä½¿ç”¨ã—ã¾ã™ã€‚既定値㯠`image.jpg` ã§ã™ã€‚(,) - * **httpMethod**: - `ã‚’ç½®ã` ã¾ãŸã¯ `POST` ã®ã„ãšã‚Œã‹ã‚’使用ã™ã‚‹ HTTP メソッド。デフォルト `ã®ãƒã‚¹ãƒˆ` ã§ã™ã€‚(,) - * **mimeType**: アップロードã™ã‚‹ãƒ‡ãƒ¼ã‚¿ã® mime タイプ。`イメージ/jpeg` ã®ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆã§ã™ã€‚(,) - * **params**: HTTP リクエストã«æ¸¡ã™ãŸã‚ã«ä»»æ„ã®ã‚­ãƒ¼/値ペアã®ã‚»ãƒƒãƒˆã€‚(オブジェクト) - * **chunkedMode**: ãƒãƒ£ãƒ³ã‚¯ ストリーミング モードã§ãƒ‡ãƒ¼ã‚¿ã‚’アップロードã™ã‚‹ã‹ã©ã†ã‹ã€‚デフォルト㯠`true` ã§ã™ã€‚(ブール値) - * **headers**: ヘッダーå/ヘッダー値ã®ãƒžãƒƒãƒ—。 é…列を使用ã—ã¦ã€1 ã¤ä»¥ä¸Šã®å€¤ã‚’指定ã—ã¾ã™ã€‚ IOSã€FireOSã€ã‚¢ãƒ³ãƒ‰ãƒ­ã‚¤ãƒ‰ã§ã¯ã¨ã„ã†åå‰ã®ã‚³ãƒ³ãƒ†ãƒ³ãƒ„ タイプ ヘッダーãŒå­˜åœ¨ã™ã‚‹å ´åˆã€ãƒžãƒ«ãƒãƒ‘ート フォーム データã¯ä½¿ç”¨ã•ã‚Œã¾ã›ã‚“。 (Object) - * **httpMethod**: 例ãˆã°ã‚’使用ã™ã‚‹ HTTP メソッドを POST ã¾ãŸã¯ PUT ã§ã™ã€‚ デフォルト`ã®ãƒã‚¹ãƒˆ`ã§ã™ã€‚(DOMString) - - * **trustAllHosts**: çœç•¥å¯èƒ½ãªãƒ‘ラメーターã¯ã€ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ `false` 。 å ´åˆè¨­å®š `true` ã€ã‚»ã‚­ãƒ¥ãƒªãƒ†ã‚£è¨¼æ˜Žæ›¸ã‚’ã™ã¹ã¦å—ã‘付ã‘ã¾ã™ã€‚ ã“れ㯠Android ã®è‡ªå·±ç½²å入りセキュリティ証明書を拒å¦ã™ã‚‹ã®ã§ä¾¿åˆ©ã§ã™ã€‚ é‹ç”¨ç’°å¢ƒã§ä½¿ç”¨ã—ãªã„ã§ãã ã•ã„。 Android 㨠iOS ã§ã‚µãƒãƒ¼ãƒˆã•ã‚Œã¦ã„ã¾ã™ã€‚ *(ブール値)* - -### 例 - - // !! Assumes variable fileURL contains a valid URL to a text file on the device, - // for example, cdvfile://localhost/persistent/path/to/file.txt - - var win = function (r) { - console.log("Code = " + r.responseCode); - console.log("Response = " + r.response); - console.log("Sent = " + r.bytesSent); - } - - var fail = function (error) { - alert("An error has occurred: Code = " + error.code); - console.log("upload error source " + error.source); - console.log("upload error target " + error.target); - } - - var options = new FileUploadOptions(); - options.fileKey = "file"; - options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1); - options.mimeType = "text/plain"; - - var params = {}; - params.value1 = "test"; - params.value2 = "param"; - - options.params = params; - - var ft = new FileTransfer(); - ft.upload(fileURL, encodeURI("http://some.server.com/upload.php"), win, fail, options); - - -### サンプルã®ã‚¢ãƒƒãƒ—ロード ヘッダーã¨é€²è¡ŒçŠ¶æ³ã®ã‚¤ãƒ™ãƒ³ãƒˆ (Android 㨠iOS ã®ã¿ï¼‰ - - function win(r) { - console.log("Code = " + r.responseCode); - console.log("Response = " + r.response); - console.log("Sent = " + r.bytesSent); - } - - function fail(error) { - alert("An error has occurred: Code = " + error.code); - console.log("upload error source " + error.source); - console.log("upload error target " + error.target); - } - - var uri = encodeURI("http://some.server.com/upload.php"); - - var options = new FileUploadOptions(); - options.fileKey="file"; - options.fileName=fileURL.substr(fileURL.lastIndexOf('/')+1); - options.mimeType="text/plain"; - - var headers={'headerParam':'headerValue'}; - - options.headers = headers; - - var ft = new FileTransfer(); - ft.onprogress = function(progressEvent) { - if (progressEvent.lengthComputable) { - loadingStatus.setPercentage(progressEvent.loaded / progressEvent.total); - } else { - loadingStatus.increment(); - } - }; - ft.upload(fileURL, uri, win, fail, options); - - -## FileUploadResult - -`FileUploadResult` オブジェクト㯠`FileTransfer` オブジェクト `upload()` メソッドã®æˆåŠŸæ™‚ã®ã‚³ãƒ¼ãƒ«ãƒãƒƒã‚¯ã«æ¸¡ã•ã‚Œã¾ã™ã€‚ - -### プロパティ - - * **bytesSent**: アップロードã®ä¸€éƒ¨ã¨ã—ã¦ã‚µãƒ¼ãƒãƒ¼ã«é€ä¿¡ã•ã‚ŒãŸãƒã‚¤ãƒˆæ•°ã€‚(ロング) - - * **記述**: サーãƒãƒ¼ã«ã‚ˆã£ã¦è¿”ã•ã‚Œã‚‹ HTTP 応答コード。(ロング) - - * **応答**: サーãƒãƒ¼ã«ã‚ˆã£ã¦è¿”ã•ã‚Œã‚‹ HTTP 応答。(,) - - * **ヘッダー**: HTTP 応答ヘッダー サーãƒãƒ¼ã«ã‚ˆã£ã¦ã€‚(オブジェクト) - - * ç¾åœ¨ iOS ã®ã¿ã§ã‚µãƒãƒ¼ãƒˆã•ã‚Œã¾ã™ã€‚ - -### iOS ã®ç™– - - * サãƒãƒ¼ãƒˆã—ã¦ã„ãªã„ `responseCode` ã¾ãŸã¯`bytesSent`. - -## download - -**パラメーター**: - - * **ソース**: ã«ã‚ˆã£ã¦ç¬¦å·åŒ–ã•ã‚Œã‚‹ã‚ˆã†ã«ã€ãƒ•ã‚¡ã‚¤ãƒ«ã‚’ダウンロードã™ã‚‹ã‚µãƒ¼ãƒãƒ¼ã® URL`encodeURI()`. - - * **ターゲット**: デãƒã‚¤ã‚¹ä¸Šã®ãƒ•ã‚¡ã‚¤ãƒ«ã‚’表ã™ãƒ•ã‚¡ã‚¤ãƒ«ã‚·ã‚¹ãƒ†ãƒ  url。 下ä½äº’æ›æ€§ã¯ã€ã“ã®ã“ã¨ã‚‚ã€ãƒ‡ãƒã‚¤ã‚¹ä¸Šã®ãƒ•ã‚¡ã‚¤ãƒ«ã®å®Œå…¨ãƒ‘スã§ã‚ã‚Šã¾ã™ã€‚ (å‚ç…§ã—ã¦ãã ã•ã„ [後方互æ›æ€§ãƒ¡ãƒ¢] ã®ä¸‹) - - * **successCallback**: 渡ã•ã‚ŒãŸã‚³ãƒ¼ãƒ«ãƒãƒƒã‚¯ã‚’ `FileEntry` オブジェクト。*(機能)* - - * **errorCallback**: `FileEntry` ã‚’å–å¾—ã™ã‚‹ã¨ãã«ã‚¨ãƒ©ãƒ¼ãŒç™ºç”Ÿã—ãŸå ´åˆã«å®Ÿè¡Œã•ã‚Œã‚‹ã‚³ãƒ¼ãƒ«ãƒãƒƒã‚¯ã€‚`FileTransferError` オブジェクトを使ã£ã¦å‘¼ã³å‡ºã•ã‚Œã¾ã™ã€‚*(機能)* - - * **trustAllHosts**: çœç•¥å¯èƒ½ãªãƒ‘ラメーターã¯ã€ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ `false` 。 å ´åˆè¨­å®š `true` ã€ã‚»ã‚­ãƒ¥ãƒªãƒ†ã‚£è¨¼æ˜Žæ›¸ã‚’ã™ã¹ã¦å—ã‘付ã‘ã¾ã™ã€‚ Android ã¯ã€è‡ªå·±ç½²å入りセキュリティ証明書を拒å¦ã—ã¾ã™ã®ã§ä¾¿åˆ©ã§ã™ã€‚ é‹ç”¨ç’°å¢ƒã§ä½¿ç”¨ã—ãªã„ã§ãã ã•ã„。 Android 㨠iOS ã§ã‚µãƒãƒ¼ãƒˆã•ã‚Œã¦ã„ã¾ã™ã€‚ *(ブール値)* - - * **オプション**: çœç•¥å¯èƒ½ãªãƒ‘ラメーターã¯ã€ç¾åœ¨ã‚µãƒãƒ¼ãƒˆã™ã‚‹ãƒ˜ãƒƒãƒ€ãƒ¼ã®ã¿ (èªè¨¼ (基本èªè¨¼) ãªã©)。 - -### 例 - - // !! Assumes variable fileURL contains a valid URL to a path on the device, - // for example, cdvfile://localhost/persistent/path/to/downloads/ - - var fileTransfer = new FileTransfer(); - var uri = encodeURI("http://some.server.com/download.php"); - - fileTransfer.download( - uri, - fileURL, - function(entry) { - console.log("download complete: " + entry.toURL()); - }, - function(error) { - console.log("download error source " + error.source); - console.log("download error target " + error.target); - console.log("upload error code" + error.code); - }, - false, - { - headers: { - "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA==" - } - } - ); - - -### WP8 ç™– - - * ダウンロードè¦æ±‚ã™ã‚‹ãƒã‚¤ãƒ†ã‚£ãƒ–実装ã«ã‚ˆã£ã¦ã‚­ãƒ£ãƒƒã‚·ãƒ¥ã«æ ¼ç´ã•ã‚Œã¦ã„ã¾ã™ã€‚キャッシュã•ã‚Œãªã„よã†ã«ã€æ¸¡ã™`以æ¥å¤‰æ›´ã•ã‚ŒãŸ if`ヘッダー メソッドをダウンロードã—ã¾ã™ã€‚ - -## abort - -進行中ã®è»¢é€ã‚’中止ã—ã¾ã™ã€‚Onerror コールãƒãƒƒã‚¯ãŒ FileTransferError.ABORT_ERR ã®ã‚¨ãƒ©ãƒ¼ コードをæŒã£ã¦ã„ã‚‹ FileTransferError オブジェクトã«æ¸¡ã•ã‚Œã¾ã™ã€‚ - -### 例 - - // !! Assumes variable fileURL contains a valid URL to a text file on the device, - // for example, cdvfile://localhost/persistent/path/to/file.txt - - var win = function(r) { - console.log("Should not be called."); - } - - var fail = function(error) { - // error.code == FileTransferError.ABORT_ERR - alert("An error has occurred: Code = " + error.code); - console.log("upload error source " + error.source); - console.log("upload error target " + error.target); - } - - var options = new FileUploadOptions(); - options.fileKey="file"; - options.fileName="myphoto.jpg"; - options.mimeType="image/jpeg"; - - var ft = new FileTransfer(); - ft.upload(fileURL, encodeURI("http://some.server.com/upload.php"), win, fail, options); - ft.abort(); - - -## FileTransferError - -`FileTransferError` オブジェクトã¯ã€ã‚¨ãƒ©ãƒ¼ãŒç™ºç”Ÿã—ãŸã¨ãã«ã‚¨ãƒ©ãƒ¼ コールãƒãƒƒã‚¯ã«æ¸¡ã•ã‚Œã¾ã™ã€‚ - -### プロパティ - - * **コード**: 次ã®ã„ãšã‚Œã‹ã®å®šç¾©æ¸ˆã¿ã®ã‚¨ãƒ©ãƒ¼ コード。(æ•°) - - * **ソース**: ソース㮠URL。(文字列) - - * **ターゲット**: 先㮠URL。(文字列) - - * **http_status**: HTTP ステータス コード。ã“ã®å±žæ€§ã¯ã€HTTP 接続ã‹ã‚‰å¿œç­”コードをå—ä¿¡ã—ãŸã¨ãã«ã®ã¿ä½¿ç”¨ã§ãã¾ã™ã€‚(æ•°) - - * **body**応答本体。ã“ã®å±žæ€§ã¯ã€HTTP 接続ã‹ã‚‰å¿œç­”ã‚’å—ä¿¡ã—ãŸã¨ãã«ã®ã¿ä½¿ç”¨ã§ãã¾ã™ã€‚(文字列) - - * **exception**: ã©ã¡ã‚‰ã‹ e.getMessage ã¾ãŸã¯ e.toString (文字列) - -### 定数 - - * 1 = `FileTransferError.FILE_NOT_FOUND_ERR` - * 2 = `FileTransferError.INVALID_URL_ERR` - * 3 = `FileTransferError.CONNECTION_ERR` - * 4 = `FileTransferError.ABORT_ERR` - * 5 = `FileTransferError.NOT_MODIFIED_ERR` - -## 後方互æ›æ€§ã‚’ノートã—ã¾ã™ã€‚ - -ã“ã®ãƒ—ラグインã®ä»¥å‰ã®ãƒãƒ¼ã‚¸ãƒ§ãƒ³ã¾ãŸã¯ãƒ€ã‚¦ãƒ³ãƒ­ãƒ¼ãƒ‰ã®ã‚¿ãƒ¼ã‚²ãƒƒãƒˆã¨ã—ã¦ã€ã‚¢ãƒƒãƒ—ロードã®ã‚½ãƒ¼ã‚¹ã¨ã—ã¦ã®ã¿ãƒ‡ãƒã‚¤ã‚¹çµ¶å¯¾ãƒ•ã‚¡ã‚¤ãƒ« パスをå—ã‘入れるã§ã—ょã†ã€‚ã“れらã®ãƒ‘スã®å½¢å¼ã¯ã€é€šå¸¸ - - /var/mobile/Applications//Documents/path/to/file (iOS) - /storage/emulated/0/path/to/file (Android) - - -下ä½äº’æ›æ€§ã€ã“れらã®ãƒ‘スを使用ã—ã¦ã‚‚ã€ã‚¢ãƒ—リケーションã¯ã€æ°¸ç¶šçš„ãªã‚¹ãƒˆãƒ¬ãƒ¼ã‚¸ã§ã“ã®ã‚ˆã†ãªãƒ‘スを記録ã—ã¦ã„ã‚‹å ´åˆã€ã—彼らãŒå¼•ã続ã使用ã•ã‚Œã¾ã™ã€‚ - -ã“れらã®ãƒ‘ス㮠`FileEntry` やファイル プラグインã«ã‚ˆã£ã¦è¿”ã•ã‚Œã‚‹ `DirectoryEntry` オブジェクト㮠`fullPath` プロパティã§å…¬é–‹ã•ã‚Œã¦ã„ãªã‹ã£ãŸã€‚ æ–°ã—ã„プラグインã®ãƒãƒ¼ã‚¸ãƒ§ãƒ³ã€ãƒ•ã‚¡ã‚¤ãƒ«ã€ãŸã ã—ã€ã‚‚ã¯ã‚„ java スクリプトã®è¨­å®šã‚’ã“れらã®ãƒ‘スを公開ã—ã¾ã™ã€‚ - -æ–°ã—ã„ã«ã‚¢ãƒƒãƒ—グレードã™ã‚‹å ´åˆ (1.0.0 以é™) ファイルã®ãƒãƒ¼ã‚¸ãƒ§ãƒ³ä»¥å‰ã‚’使用ã—ã¦ã„ã‚‹ `entry.fullPath` `download()` ã¾ãŸã¯ `upload()` ã¸ã®å¼•æ•°ã¨ã—ã¦ã€ãƒ•ã‚¡ã‚¤ãƒ«ã‚·ã‚¹ãƒ†ãƒ ã® Url を代ã‚ã‚Šã«ä½¿ç”¨ã™ã‚‹ã‚³ãƒ¼ãƒ‰ã‚’変更ã™ã‚‹å¿…è¦ãŒã‚ã‚Šã¾ã™ã€‚ - -`FileEntry.toURL()` 㨠`DirectoryEntry.toURL()` ファイルシステム㮠URL ã‚’è¿”ã™ãƒ•ã‚©ãƒ¼ãƒ  - - cdvfile://localhost/persistent/path/to/file - - -`download()`ã€`upload()` メソッドã®çµ¶å¯¾ãƒ•ã‚¡ã‚¤ãƒ« パスã®ä»£ã‚ã‚Šã«ä½¿ç”¨ã§ãã¾ã™ã€‚ \ No newline at end of file diff --git a/plugins/cordova-plugin-file-transfer/doc/ja/index.md b/plugins/cordova-plugin-file-transfer/doc/ja/index.md deleted file mode 100644 index f885b3c..0000000 --- a/plugins/cordova-plugin-file-transfer/doc/ja/index.md +++ /dev/null @@ -1,302 +0,0 @@ - - -# cordova-plugin-file-transfer - -ã“ã®ãƒ—ラグインã¯ã€ã‚¢ãƒƒãƒ—ロードã—ã€ãƒ•ã‚¡ã‚¤ãƒ«ã‚’ダウンロードã™ã‚‹ã“ã¨ãŒã§ãã¾ã™ã€‚ - -ã“ã®ãƒ—ラグインã§ã¯ã€ã‚°ãƒ­ãƒ¼ãƒãƒ« `FileTransfer`ã€`FileUploadOptions` コンス トラクターを定義ã—ã¾ã™ã€‚ - -グローãƒãƒ« スコープã§ã¯ä½¿ç”¨ã§ãã¾ã›ã‚“ã¾ã§ `deviceready` イベントã®å¾Œã§ã™ã€‚ - - document.addEventListener("deviceready", onDeviceReady, false); - function onDeviceReady() { - console.log(FileTransfer); - } - - -## インストール - - cordova plugin add cordova-plugin-file-transfer - - -## サãƒãƒ¼ãƒˆã•ã‚Œã¦ã„るプラットフォーム - -* ã‚¢ãƒžã‚¾ãƒ³ç« OS -* アンドロイド -* ブラックベリー 10 -* ブラウザー -* Firefox ã® OS * * -* iOS -* Windows Phone 7 㨠8 * -* Windows 8 -* Windows - -* *`onprogress` ã‚‚ `abort()` をサãƒãƒ¼ãƒˆã—ã¦ã„ã¾ã›ã‚“* - -* * *`onprogress` をサãƒãƒ¼ãƒˆã—ã¦ã„ã¾ã›ã‚“* - -# FileTransfer - -`FileTransfer` オブジェクトã¯ãƒžãƒ«ãƒãƒ‘ートã®ãƒã‚¹ãƒˆã€HTTP è¦æ±‚を使用ã—ã¦ãƒ•ã‚¡ã‚¤ãƒ«ã‚’アップロードã—ã¦åŒæ§˜ã«ãƒ•ã‚¡ã‚¤ãƒ«ã‚’ダウンロードã™ã‚‹æ–¹æ³•ã‚’æä¾›ã—ã¾ã™ã€‚ - -## プロパティ - -* **onprogress**: ã¨å‘¼ã°ã‚Œã‚‹ã€ `ProgressEvent` データã®æ–°ã—ã„ãƒãƒ£ãƒ³ã‚¯ãŒè»¢é€ã•ã‚Œã‚‹ãŸã³ã«ã€‚*(機能)* - -## メソッド - -* **アップロード**: サーãƒãƒ¼ã«ãƒ•ã‚¡ã‚¤ãƒ«ã‚’é€ä¿¡ã—ã¾ã™ã€‚ - -* **ダウンロード**: サーãƒãƒ¼ã‹ã‚‰ãƒ•ã‚¡ã‚¤ãƒ«ã‚’ダウンロードã—ã¾ã™ã€‚ - -* **中止**: 進行中ã®è»¢é€ã‚’中止ã—ã¾ã™ã€‚ - -## upload - -**パラメーター**: - -* **fileURL**: デãƒã‚¤ã‚¹ä¸Šã®ãƒ•ã‚¡ã‚¤ãƒ«ã‚’表ã™ãƒ•ã‚¡ã‚¤ãƒ«ã‚·ã‚¹ãƒ†ãƒ  URL。 下ä½äº’æ›æ€§ã¯ã€ã“ã®ã“ã¨ã‚‚ã€ãƒ‡ãƒã‚¤ã‚¹ä¸Šã®ãƒ•ã‚¡ã‚¤ãƒ«ã®å®Œå…¨ãƒ‘スã§ã‚ã‚Šã¾ã™ã€‚ (å‚ç…§ã—ã¦ãã ã•ã„ [後方互æ›æ€§ãƒ¡ãƒ¢] ã®ä¸‹) - -* **サーãƒãƒ¼**: ã«ã‚ˆã£ã¦ç¬¦å·åŒ–ã•ã‚Œã‚‹ã‚ˆã†ã«ã€ãƒ•ã‚¡ã‚¤ãƒ«ã‚’å—ä¿¡ã™ã‚‹ã‚µãƒ¼ãƒãƒ¼ã® URL`encodeURI()`. - -* **successCallback**: `FileUploadResult` オブジェクトãŒæ¸¡ã•ã‚Œã‚‹ã‚³ãƒ¼ãƒ«ãƒãƒƒã‚¯ã€‚*(機能)* - -* **errorCallback**: エラー `FileUploadResult` ã‚’å–å¾—ã™ã‚‹ãŒç™ºç”Ÿã—ãŸå ´åˆã«å®Ÿè¡Œã•ã‚Œã‚‹ã‚³ãƒ¼ãƒ«ãƒãƒƒã‚¯ã€‚`FileTransferError` オブジェクトを使ã£ã¦å‘¼ã³å‡ºã•ã‚Œã¾ã™ã€‚*(機能)* - -* **オプション**: çœç•¥å¯èƒ½ãªãƒ‘ラメーター *(オブジェクト)*。有効ãªã‚­ãƒ¼: - - * **fileKey**: フォームè¦ç´ ã®åå‰ã€‚既定値㯠`file` ã§ã™ã€‚(,) - * **ファイルå**: ファイルåã€ã‚µãƒ¼ãƒãƒ¼ä¸Šã®ãƒ•ã‚¡ã‚¤ãƒ«ã‚’ä¿å­˜ã™ã‚‹ã¨ãã«ä½¿ç”¨ã—ã¾ã™ã€‚既定値㯠`image.jpg` ã§ã™ã€‚(,) - * **httpMethod**: - `ã‚’ç½®ã` ã¾ãŸã¯ `POST` ã®ã„ãšã‚Œã‹ã‚’使用ã™ã‚‹ HTTP メソッド。デフォルト `ã®ãƒã‚¹ãƒˆ` ã§ã™ã€‚(,) - * **mimeType**: アップロードã™ã‚‹ãƒ‡ãƒ¼ã‚¿ã® mime タイプ。`イメージ/jpeg` ã®ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆã§ã™ã€‚(,) - * **params**: HTTP リクエストã«æ¸¡ã™ãŸã‚ã«ä»»æ„ã®ã‚­ãƒ¼/値ペアã®ã‚»ãƒƒãƒˆã€‚(オブジェクト) - * **chunkedMode**: ãƒãƒ£ãƒ³ã‚¯ ストリーミング モードã§ãƒ‡ãƒ¼ã‚¿ã‚’アップロードã™ã‚‹ã‹ã©ã†ã‹ã€‚デフォルト㯠`true` ã§ã™ã€‚(ブール値) - * **headers**: ヘッダーã®åå‰/ヘッダー値ã®ãƒžãƒƒãƒ—。1 ã¤ä»¥ä¸Šã®å€¤ã‚’指定ã™ã‚‹ã«ã¯ã€é…列を使用ã—ã¾ã™ã€‚(オブジェクト) - -* **trustAllHosts**: çœç•¥å¯èƒ½ãªãƒ‘ラメーターã¯ã€ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ `false` 。 å ´åˆè¨­å®š `true` ã€ã‚»ã‚­ãƒ¥ãƒªãƒ†ã‚£è¨¼æ˜Žæ›¸ã‚’ã™ã¹ã¦å—ã‘付ã‘ã¾ã™ã€‚ ã“れ㯠Android ã®è‡ªå·±ç½²å入りセキュリティ証明書を拒å¦ã™ã‚‹ã®ã§ä¾¿åˆ©ã§ã™ã€‚ é‹ç”¨ç’°å¢ƒã§ä½¿ç”¨ã—ãªã„ã§ãã ã•ã„。 Android 㨠iOS ã§ã‚µãƒãƒ¼ãƒˆã•ã‚Œã¦ã„ã¾ã™ã€‚ *(ブール値)* - -### 例 - - // !! Assumes variable fileURL contains a valid URL to a text file on the device, - // for example, cdvfile://localhost/persistent/path/to/file.txt - - var win = function (r) { - console.log("Code = " + r.responseCode); - console.log("Response = " + r.response); - console.log("Sent = " + r.bytesSent); - } - - var fail = function (error) { - alert("An error has occurred: Code = " + error.code); - console.log("upload error source " + error.source); - console.log("upload error target " + error.target); - } - - var options = new FileUploadOptions(); - options.fileKey = "file"; - options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1); - options.mimeType = "text/plain"; - - var params = {}; - params.value1 = "test"; - params.value2 = "param"; - - options.params = params; - - var ft = new FileTransfer(); - ft.upload(fileURL, encodeURI("http://some.server.com/upload.php"), win, fail, options); - - -### サンプルã®ã‚¢ãƒƒãƒ—ロード ヘッダーã¨é€²è¡ŒçŠ¶æ³ã®ã‚¤ãƒ™ãƒ³ãƒˆ (Android 㨠iOS ã®ã¿ï¼‰ - - function win(r) { - console.log("Code = " + r.responseCode); - console.log("Response = " + r.response); - console.log("Sent = " + r.bytesSent); - } - - function fail(error) { - alert("An error has occurred: Code = " + error.code); - console.log("upload error source " + error.source); - console.log("upload error target " + error.target); - } - - var uri = encodeURI("http://some.server.com/upload.php"); - - var options = new FileUploadOptions(); - options.fileKey="file"; - options.fileName=fileURL.substr(fileURL.lastIndexOf('/')+1); - options.mimeType="text/plain"; - - var headers={'headerParam':'headerValue'}; - - options.headers = headers; - - var ft = new FileTransfer(); - ft.onprogress = function(progressEvent) { - if (progressEvent.lengthComputable) { - loadingStatus.setPercentage(progressEvent.loaded / progressEvent.total); - } else { - loadingStatus.increment(); - } - }; - ft.upload(fileURL, uri, win, fail, options); - - -## FileUploadResult - -`FileUploadResult` オブジェクト㯠`FileTransfer` オブジェクト `upload()` メソッドã®æˆåŠŸæ™‚ã®ã‚³ãƒ¼ãƒ«ãƒãƒƒã‚¯ã«æ¸¡ã•ã‚Œã¾ã™ã€‚ - -### プロパティ - -* **bytesSent**: アップロードã®ä¸€éƒ¨ã¨ã—ã¦ã‚µãƒ¼ãƒãƒ¼ã«é€ä¿¡ã•ã‚ŒãŸãƒã‚¤ãƒˆæ•°ã€‚(ロング) - -* **記述**: サーãƒãƒ¼ã«ã‚ˆã£ã¦è¿”ã•ã‚Œã‚‹ HTTP 応答コード。(ロング) - -* **応答**: サーãƒãƒ¼ã«ã‚ˆã£ã¦è¿”ã•ã‚Œã‚‹ HTTP 応答。(,) - -* **ヘッダー**: HTTP 応答ヘッダー サーãƒãƒ¼ã«ã‚ˆã£ã¦ã€‚(オブジェクト) - - * ç¾åœ¨ iOS ã®ã¿ã§ã‚µãƒãƒ¼ãƒˆã•ã‚Œã¾ã™ã€‚ - -### iOS ã®ç™– - -* サãƒãƒ¼ãƒˆã—ã¦ã„ãªã„ `responseCode` ã¾ãŸã¯`bytesSent`. - -## download - -**パラメーター**: - -* **ソース**: ã«ã‚ˆã£ã¦ç¬¦å·åŒ–ã•ã‚Œã‚‹ã‚ˆã†ã«ã€ãƒ•ã‚¡ã‚¤ãƒ«ã‚’ダウンロードã™ã‚‹ã‚µãƒ¼ãƒãƒ¼ã® URL`encodeURI()`. - -* **ターゲット**: デãƒã‚¤ã‚¹ä¸Šã®ãƒ•ã‚¡ã‚¤ãƒ«ã‚’表ã™ãƒ•ã‚¡ã‚¤ãƒ«ã‚·ã‚¹ãƒ†ãƒ  url。 下ä½äº’æ›æ€§ã¯ã€ã“ã®ã“ã¨ã‚‚ã€ãƒ‡ãƒã‚¤ã‚¹ä¸Šã®ãƒ•ã‚¡ã‚¤ãƒ«ã®å®Œå…¨ãƒ‘スã§ã‚ã‚Šã¾ã™ã€‚ (å‚ç…§ã—ã¦ãã ã•ã„ [後方互æ›æ€§ãƒ¡ãƒ¢] ã®ä¸‹) - -* **successCallback**: 渡ã•ã‚ŒãŸã‚³ãƒ¼ãƒ«ãƒãƒƒã‚¯ã‚’ `FileEntry` オブジェクト。*(機能)* - -* **errorCallback**: `FileEntry` ã‚’å–å¾—ã™ã‚‹ã¨ãã«ã‚¨ãƒ©ãƒ¼ãŒç™ºç”Ÿã—ãŸå ´åˆã«å®Ÿè¡Œã•ã‚Œã‚‹ã‚³ãƒ¼ãƒ«ãƒãƒƒã‚¯ã€‚`FileTransferError` オブジェクトを使ã£ã¦å‘¼ã³å‡ºã•ã‚Œã¾ã™ã€‚*(機能)* - -* **trustAllHosts**: çœç•¥å¯èƒ½ãªãƒ‘ラメーターã¯ã€ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ `false` 。 å ´åˆè¨­å®š `true` ã€ã‚»ã‚­ãƒ¥ãƒªãƒ†ã‚£è¨¼æ˜Žæ›¸ã‚’ã™ã¹ã¦å—ã‘付ã‘ã¾ã™ã€‚ Android ã¯ã€è‡ªå·±ç½²å入りセキュリティ証明書を拒å¦ã—ã¾ã™ã®ã§ä¾¿åˆ©ã§ã™ã€‚ é‹ç”¨ç’°å¢ƒã§ä½¿ç”¨ã—ãªã„ã§ãã ã•ã„。 Android 㨠iOS ã§ã‚µãƒãƒ¼ãƒˆã•ã‚Œã¦ã„ã¾ã™ã€‚ *(ブール値)* - -* **オプション**: çœç•¥å¯èƒ½ãªãƒ‘ラメーターã¯ã€ç¾åœ¨ã‚µãƒãƒ¼ãƒˆã™ã‚‹ãƒ˜ãƒƒãƒ€ãƒ¼ã®ã¿ (èªè¨¼ (基本èªè¨¼) ãªã©)。 - -### 例 - - // !! Assumes variable fileURL contains a valid URL to a path on the device, - // for example, cdvfile://localhost/persistent/path/to/downloads/ - - var fileTransfer = new FileTransfer(); - var uri = encodeURI("http://some.server.com/download.php"); - - fileTransfer.download( - uri, - fileURL, - function(entry) { - console.log("download complete: " + entry.toURL()); - }, - function(error) { - console.log("download error source " + error.source); - console.log("download error target " + error.target); - console.log("upload error code" + error.code); - }, - false, - { - headers: { - "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA==" - } - } - ); - - -## abort - -進行中ã®è»¢é€ã‚’中止ã—ã¾ã™ã€‚Onerror コールãƒãƒƒã‚¯ãŒ FileTransferError.ABORT_ERR ã®ã‚¨ãƒ©ãƒ¼ コードをæŒã£ã¦ã„ã‚‹ FileTransferError オブジェクトã«æ¸¡ã•ã‚Œã¾ã™ã€‚ - -### 例 - - // !! Assumes variable fileURL contains a valid URL to a text file on the device, - // for example, cdvfile://localhost/persistent/path/to/file.txt - - var win = function(r) { - console.log("Should not be called."); - } - - var fail = function(error) { - // error.code == FileTransferError.ABORT_ERR - alert("An error has occurred: Code = " + error.code); - console.log("upload error source " + error.source); - console.log("upload error target " + error.target); - } - - var options = new FileUploadOptions(); - options.fileKey="file"; - options.fileName="myphoto.jpg"; - options.mimeType="image/jpeg"; - - var ft = new FileTransfer(); - ft.upload(fileURL, encodeURI("http://some.server.com/upload.php"), win, fail, options); - ft.abort(); - - -## FileTransferError - -`FileTransferError` オブジェクトã¯ã€ã‚¨ãƒ©ãƒ¼ãŒç™ºç”Ÿã—ãŸã¨ãã«ã‚¨ãƒ©ãƒ¼ コールãƒãƒƒã‚¯ã«æ¸¡ã•ã‚Œã¾ã™ã€‚ - -### プロパティ - -* **コード**: 次ã®ã„ãšã‚Œã‹ã®å®šç¾©æ¸ˆã¿ã®ã‚¨ãƒ©ãƒ¼ コード。(æ•°) - -* **ソース**: ソース㮠URL。(文字列) - -* **ターゲット**: 先㮠URL。(文字列) - -* **http_status**: HTTP ステータス コード。ã“ã®å±žæ€§ã¯ã€HTTP 接続ã‹ã‚‰å¿œç­”コードをå—ä¿¡ã—ãŸã¨ãã«ã®ã¿ä½¿ç”¨ã§ãã¾ã™ã€‚(æ•°) - -* **body**応答本体。ã“ã®å±žæ€§ã¯ã€HTTP 接続ã‹ã‚‰å¿œç­”ã‚’å—ä¿¡ã—ãŸã¨ãã«ã®ã¿ä½¿ç”¨ã§ãã¾ã™ã€‚(文字列) - -* **exception**: ã©ã¡ã‚‰ã‹ e.getMessage ã¾ãŸã¯ e.toString (文字列) - -### 定数 - -* 1 = `FileTransferError.FILE_NOT_FOUND_ERR` -* 2 = `FileTransferError.INVALID_URL_ERR` -* 3 = `FileTransferError.CONNECTION_ERR` -* 4 = `FileTransferError.ABORT_ERR` -* 5 = `FileTransferError.NOT_MODIFIED_ERR` - -## 後方互æ›æ€§ã‚’ノートã—ã¾ã™ã€‚ - -ã“ã®ãƒ—ラグインã®ä»¥å‰ã®ãƒãƒ¼ã‚¸ãƒ§ãƒ³ã¾ãŸã¯ãƒ€ã‚¦ãƒ³ãƒ­ãƒ¼ãƒ‰ã®ã‚¿ãƒ¼ã‚²ãƒƒãƒˆã¨ã—ã¦ã€ã‚¢ãƒƒãƒ—ロードã®ã‚½ãƒ¼ã‚¹ã¨ã—ã¦ã®ã¿ãƒ‡ãƒã‚¤ã‚¹çµ¶å¯¾ãƒ•ã‚¡ã‚¤ãƒ« パスをå—ã‘入れるã§ã—ょã†ã€‚ã“れらã®ãƒ‘スã®å½¢å¼ã¯ã€é€šå¸¸ - - /var/mobile/Applications//Documents/path/to/file (iOS) - /storage/emulated/0/path/to/file (Android) - - -下ä½äº’æ›æ€§ã€ã“れらã®ãƒ‘スを使用ã—ã¦ã‚‚ã€ã‚¢ãƒ—リケーションã¯ã€æ°¸ç¶šçš„ãªã‚¹ãƒˆãƒ¬ãƒ¼ã‚¸ã§ã“ã®ã‚ˆã†ãªãƒ‘スを記録ã—ã¦ã„ã‚‹å ´åˆã€ã—彼らãŒå¼•ã続ã使用ã•ã‚Œã¾ã™ã€‚ - -ã“れらã®ãƒ‘ス㮠`FileEntry` やファイル プラグインã«ã‚ˆã£ã¦è¿”ã•ã‚Œã‚‹ `DirectoryEntry` オブジェクト㮠`fullPath` プロパティã§å…¬é–‹ã•ã‚Œã¦ã„ãªã‹ã£ãŸã€‚ æ–°ã—ã„プラグインã®ãƒãƒ¼ã‚¸ãƒ§ãƒ³ã€ãƒ•ã‚¡ã‚¤ãƒ«ã€ãŸã ã—ã€ã‚‚ã¯ã‚„ java スクリプトã®è¨­å®šã‚’ã“れらã®ãƒ‘スを公開ã—ã¾ã™ã€‚ - -æ–°ã—ã„ã«ã‚¢ãƒƒãƒ—グレードã™ã‚‹å ´åˆ (1.0.0 以é™) ファイルã®ãƒãƒ¼ã‚¸ãƒ§ãƒ³ä»¥å‰ã‚’使用ã—ã¦ã„ã‚‹ `entry.fullPath` `download()` ã¾ãŸã¯ `upload()` ã¸ã®å¼•æ•°ã¨ã—ã¦ã€ãƒ•ã‚¡ã‚¤ãƒ«ã‚·ã‚¹ãƒ†ãƒ ã® Url を代ã‚ã‚Šã«ä½¿ç”¨ã™ã‚‹ã‚³ãƒ¼ãƒ‰ã‚’変更ã™ã‚‹å¿…è¦ãŒã‚ã‚Šã¾ã™ã€‚ - -`FileEntry.toURL()` 㨠`DirectoryEntry.toURL()` ファイルシステム㮠URL ã‚’è¿”ã™ãƒ•ã‚©ãƒ¼ãƒ  - - cdvfile://localhost/persistent/path/to/file - - -`download()`ã€`upload()` メソッドã®çµ¶å¯¾ãƒ•ã‚¡ã‚¤ãƒ« パスã®ä»£ã‚ã‚Šã«ä½¿ç”¨ã§ãã¾ã™ã€‚ diff --git a/plugins/cordova-plugin-file-transfer/doc/ko/README.md b/plugins/cordova-plugin-file-transfer/doc/ko/README.md deleted file mode 100644 index f91e8a2..0000000 --- a/plugins/cordova-plugin-file-transfer/doc/ko/README.md +++ /dev/null @@ -1,311 +0,0 @@ - - -# cordova-plugin-file-transfer - -[![Build Status](https://travis-ci.org/apache/cordova-plugin-file-transfer.svg)](https://travis-ci.org/apache/cordova-plugin-file-transfer) - -í”ŒëŸ¬ê·¸ì¸ ë¬¸ì„œ: - -ì´ í”ŒëŸ¬ê·¸ì¸ì„ 사용 하면 업로드 ë° ë‹¤ìš´ë¡œë“œ íŒŒì¼ ìˆ˜ 있습니다. - -ì´ í”ŒëŸ¬ê·¸ì¸ ê¸€ë¡œë²Œ `FileTransfer`, `FileUploadOptions` ìƒì„±ìžë¥¼ ì •ì˜í•©ë‹ˆë‹¤. - -ì „ì—­ 범위ì—ì„œ ê·¸ë“¤ì€ ì œê³µ ë˜ì§€ 않습니다 때까지 `deviceready` ì´ë²¤íŠ¸ 후. - - document.addEventListener("deviceready", onDeviceReady, false); - function onDeviceReady() { - console.log(FileTransfer); - } - - -## 설치 - - cordova plugin add cordova-plugin-file-transfer - - -## ì§€ì› ë˜ëŠ” í”Œëž«í¼ - - * 아마존 화재 ìš´ì˜ ì²´ì œ - * 안 ë“œ ë¡œì´ë“œ - * 블랙베리 10 - * 브ë¼ìš°ì € - * 파ì´ì–´ í­ìŠ¤ OS * * - * iOS - * Windows Phone 7ê³¼ 8 * - * 윈ë„ìš° 8 - * 윈ë„ìš° - -\** `Onprogress` ë„ `abort()` 를 ì§€ì› í•˜ì§€ 않습니다* - -\*** `Onprogress` 를 ì§€ì› í•˜ì§€ 않습니다* - -# FileTransfer - -`FileTransfer` 개체는 HTTP 다중 파트 POST ë˜ëŠ” PUT ìš”ì²­ì„ ì‚¬ìš© 하 ì—¬ 파ì¼ì„ 업로드 하 ê³  ë˜í•œ 파ì¼ì„ 다운로드 하는 ë°©ë²•ì„ ì œê³µ 합니다. - -## ì†ì„± - - * **onprogress**:ë¡œ 불리는 `ProgressEvent` 새로운 ì–‘ì˜ ë°ì´í„°ë¥¼ 전송 하는 때마다. *(기능)* - -## 메서드 - - * **업로드**: 파ì¼ì„ ì„œë²„ì— ë³´ëƒ…ë‹ˆë‹¤. - - * **다운로드**: 서버ì—ì„œ 파ì¼ì„ 다운로드 합니다. - - * **중단**: 진행 ì¤‘ì¸ ì „ì†¡ 중단. - -## 업로드 - -**매개 변수**: - - * **fileURL**: ìž¥ì¹˜ì— íŒŒì¼ì„ 나타내는 íŒŒì¼ ì‹œìŠ¤í…œ URL. ì— ëŒ€ í•œ ì´ì „ 버전과 호환성ì„ì´ ìˆ˜ë„ ìž¥ì¹˜ì— ìžˆëŠ” 파ì¼ì˜ ì „ì²´ 경로 수. (참조 [거꾸로 호환성 노트] 아래) - - * **서버**: ì¸ì½”딩 íŒŒì¼ ìˆ˜ì‹  ì„œë²„ì˜ URL`encodeURI()`. - - * **successCallback**: `FileUploadResult` 개체를 전달 하는 콜백. *(기능)* - - * **errorCallback**: `FileUploadResult` ê²€ìƒ‰ì— ì˜¤ë¥˜ê°€ ë°œìƒ í•˜ë©´ 실행 ë˜ëŠ” 콜백. `FileTransferError` 개체와 함께 호출 ë©ë‹ˆë‹¤. *(기능)* - - * **옵션**: ì„ íƒì  매개 변수 *(개체)*. 유효한 키: - - * **fileKey**: form ìš”ì†Œì˜ ì´ë¦„. ê¸°ë³¸ê°’ì€ `file` . (DOMString) - * **íŒŒì¼ ì´ë¦„**: íŒŒì¼ ì´ë¦„ì„ ì„œë²„ì— íŒŒì¼ì„ 저장할 ë•Œ 사용 합니다. ê¸°ë³¸ê°’ì€ `image.jpg` . (DOMString) - * **httpMethod**: `넣어` ë˜ëŠ” `게시물`-사용 하ë„ë¡ HTTP 메서드. `게시물` 기본값입니다. (DOMString) - * **mimeType**: 업로드 ë°ì´í„°ì˜ mime 형ì‹ì„. `ì´ë¯¸ì§€/jpeg`ì˜ ê¸°ë³¸ê°’ìž…ë‹ˆë‹¤. (DOMString) - * **params**: HTTP ìš”ì²­ì— ì „ë‹¬í•  ì„ íƒì  키/ê°’ ìŒì˜ 집합. (개체) - * **chunkedMode**: ì²­í¬ ìŠ¤íŠ¸ë¦¬ë° ëª¨ë“œì—ì„œ ë°ì´í„° 업로드를 합니다. ê¸°ë³¸ê°’ì€ `true`입니다. (부울) - * **headers**: í—¤ë” ì´ë¦„ ë° í—¤ë” ê°’ì˜ ì§€ë„. ë°°ì—´ì„ ì‚¬ìš© 하 ì—¬ 하나 ì´ìƒì˜ ê°’ì„ ì§€ì •. IOS, FireOS, 안 ë“œ ë¡œì´ë“œì— 있으면 ë¼ëŠ” 콘í…츠 í˜•ì‹ í—¤ë”, 다중 ì–‘ì‹ ë°ì´í„°ëŠ” 사용할 수 없습니다. (Object) - * **httpMethod**: HTTP 메서드 예를 사용 하 ì—¬ 게시 하거나 넣어. `게시물`기본값입니다. (DOMString) - - * **trustAllHosts**: ì„ íƒì  매개 변수는 기본ì ìœ¼ë¡œ `false` . 만약 설정 `true` , ê·¸ê²ƒì€ ëª¨ë“  보안 ì¸ì¦ì„œë¥¼ 허용 합니다. ì´ ì•ˆ ë“œ ë¡œì´ë“œ ìžì²´ 서명 ëœ ë³´ì•ˆ ì¸ì¦ì„œë¥¼ 거부 하기 ë•Œë¬¸ì— ìœ ìš© 합니다. 프로ë•ì…˜ 환경ì—ì„œ 사용 권장 ë˜ì§€ 않습니다. 안 ë“œ ë¡œì´ë“œì™€ iOSì—ì„œ 지ì›. *(부울)* - -### 예를 들어 - - // !! Assumes variable fileURL contains a valid URL to a text file on the device, - // for example, cdvfile://localhost/persistent/path/to/file.txt - - var win = function (r) { - console.log("Code = " + r.responseCode); - console.log("Response = " + r.response); - console.log("Sent = " + r.bytesSent); - } - - var fail = function (error) { - alert("An error has occurred: Code = " + error.code); - console.log("upload error source " + error.source); - console.log("upload error target " + error.target); - } - - var options = new FileUploadOptions(); - options.fileKey = "file"; - options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1); - options.mimeType = "text/plain"; - - var params = {}; - params.value1 = "test"; - params.value2 = "param"; - - options.params = params; - - var ft = new FileTransfer(); - ft.upload(fileURL, encodeURI("http://some.server.com/upload.php"), win, fail, options); - - -### 예를 들어 í—¤ë” ì—…ë¡œë“œ ë° ì§„í–‰ ì´ë²¤íŠ¸ (안 ë“œ ë¡œì´ë“œì™€ iOS만) - - function win(r) { - console.log("Code = " + r.responseCode); - console.log("Response = " + r.response); - console.log("Sent = " + r.bytesSent); - } - - function fail(error) { - alert("An error has occurred: Code = " + error.code); - console.log("upload error source " + error.source); - console.log("upload error target " + error.target); - } - - var uri = encodeURI("http://some.server.com/upload.php"); - - var options = new FileUploadOptions(); - options.fileKey="file"; - options.fileName=fileURL.substr(fileURL.lastIndexOf('/')+1); - options.mimeType="text/plain"; - - var headers={'headerParam':'headerValue'}; - - options.headers = headers; - - var ft = new FileTransfer(); - ft.onprogress = function(progressEvent) { - if (progressEvent.lengthComputable) { - loadingStatus.setPercentage(progressEvent.loaded / progressEvent.total); - } else { - loadingStatus.increment(); - } - }; - ft.upload(fileURL, uri, win, fail, options); - - -## FileUploadResult - -`FileUploadResult` 개체 `FileTransfer` ê°œì²´ì˜ `ì›ëž˜` ë°©ë²•ì˜ ì„±ê³µ ì½œë°±ì— ì „ë‹¬ ë©ë‹ˆë‹¤. - -### ì†ì„± - - * **bytesSent**: ì—…ë¡œë“œì˜ ì¼ë¶€ë¡œ ì„œë²„ì— ë³´ë‚¸ ë°”ì´íŠ¸ 수. (긴) - - * **responseCode**: 서버ì—ì„œ 반환 ëœ HTTP ì‘답 코드. (긴) - - * **response**: 서버ì—ì„œ 반환 ë˜ëŠ” HTTP ì‘답. (DOMString) - - * **headers**: 서버ì—ì„œ HTTP ì‘답 í—¤ë”. (개체) - - * 현재 ios만 ì§€ì› í•©ë‹ˆë‹¤. - -### iOS ë‹¨ì  - - * ì§€ì› í•˜ì§€ 않는 `responseCode` ë˜ëŠ”`bytesSent`. - -## download - -**매개 변수**: - - * **source**: URLë¡œ ì¸ì½”ë”©ëœ íŒŒì¼, 다운로드 서버`encodeURI()`. - - * **target**: ìž¥ì¹˜ì— íŒŒì¼ì„ 나타내는 íŒŒì¼ ì‹œìŠ¤í…œ url. ì— ëŒ€ í•œ ì´ì „ 버전과 호환성ì„ì´ ìˆ˜ë„ ìž¥ì¹˜ì— ìžˆëŠ” 파ì¼ì˜ ì „ì²´ 경로 수. (참조 [거꾸로 호환성 노트] 아래) - - * **successCallback**: 콜백 전달 ë˜ëŠ” `FileEntry` 개체. *(기능)* - - * **errorCallback**: `FileEntry`를 검색할 ë•Œ 오류가 ë°œìƒ í•˜ë©´ 실행 ë˜ëŠ” 콜백. `FileTransferError` 개체와 함께 호출 ë©ë‹ˆë‹¤. *(기능)* - - * **trustAllHosts**: ì„ íƒì  매개 변수는 기본ì ìœ¼ë¡œ `false` . 만약 설정 `true` , ê·¸ê²ƒì€ ëª¨ë“  보안 ì¸ì¦ì„œë¥¼ 허용 합니다. 안 ë“œ ë¡œì´ë“œ ìžì²´ 서명 ëœ ë³´ì•ˆ ì¸ì¦ì„œë¥¼ 거부 하기 ë•Œë¬¸ì— ìœ ìš© 합니다. 프로ë•ì…˜ 환경ì—ì„œ 사용 권장 ë˜ì§€ 않습니다. 안 ë“œ ë¡œì´ë“œì™€ iOSì—ì„œ 지ì›. *(부울)* - - * **options**: ì„ íƒì  매개 변수를 현재 지 ì›í•˜ëŠ” 머리글만 (예: ì¸ì¦ (기본 ì¸ì¦), 등). - -### 예를 들어 - - // !! Assumes variable fileURL contains a valid URL to a path on the device, - // for example, cdvfile://localhost/persistent/path/to/downloads/ - - var fileTransfer = new FileTransfer(); - var uri = encodeURI("http://some.server.com/download.php"); - - fileTransfer.download( - uri, - fileURL, - function(entry) { - console.log("download complete: " + entry.toURL()); - }, - function(error) { - console.log("download error source " + error.source); - console.log("download error target " + error.target); - console.log("upload error code" + error.code); - }, - false, - { - headers: { - "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA==" - } - } - ); - - -### WP8 특수 - - * 다운로드 요청 기본 êµ¬í˜„ì— ì˜í•´ ìºì‹œ ë˜ ê³ . ìºì‹±ì„ 방지 하려면 전달 `if-수정-ì´í›„` í—¤ë”를 다운로드 하는 방법. - -## abort - -진행 ì¤‘ì¸ ì „ì†¡ì„ ì¤‘ë‹¨í•©ë‹ˆë‹¤. onerror 콜백 FileTransferError.ABORT_ERRì˜ ì˜¤ë¥˜ 코드는 FileTransferError 개체를 전달 합니다. - -### 예를 들어 - - // !! Assumes variable fileURL contains a valid URL to a text file on the device, - // for example, cdvfile://localhost/persistent/path/to/file.txt - - var win = function(r) { - console.log("Should not be called."); - } - - var fail = function(error) { - // error.code == FileTransferError.ABORT_ERR - alert("An error has occurred: Code = " + error.code); - console.log("upload error source " + error.source); - console.log("upload error target " + error.target); - } - - var options = new FileUploadOptions(); - options.fileKey="file"; - options.fileName="myphoto.jpg"; - options.mimeType="image/jpeg"; - - var ft = new FileTransfer(); - ft.upload(fileURL, encodeURI("http://some.server.com/upload.php"), win, fail, options); - ft.abort(); - - -## FileTransferError - -`FileTransferError` 개체 오류가 ë°œìƒ í•˜ë©´ 오류 ì½œë°±ì— ì „ë‹¬ ë©ë‹ˆë‹¤. - -### ì†ì„± - - * **code**: 미리 ì •ì˜ ëœ ì˜¤ë¥˜ 코드 중 하나가 ì•„ëž˜ì— ë‚˜ì—´ ëœ. (수) - - * **source**: 소스 URL. (문ìžì—´) - - * **target**: ëŒ€ìƒ URL. (문ìžì—´) - - * **http_status**: HTTP ìƒíƒœ 코드. ì´ íŠ¹ì„±ì€ ì‘답 코드를 HTTP ì—°ê²°ì—ì„œ ìˆ˜ì‹ ì— ì‚¬ìš©í•  수 있습니다. (수) - - * **body** ì‘답 본문입니다. ì´ íŠ¹ì„±ì€ HTTP ì—°ê²°ì—ì„œ ì‘ë‹µì„ ë°›ì„ ë•Œì— ì‚¬ìš©í•  수 있습니다. (문ìžì—´) - - * **exception**: ì–´ëŠ e.getMessage ë˜ëŠ” e.toString (문ìžì—´) - -### ìƒìˆ˜ - - * 1 = `FileTransferError.FILE_NOT_FOUND_ERR` - * 2 = `FileTransferError.INVALID_URL_ERR` - * 3 = `FileTransferError.CONNECTION_ERR` - * 4 = `FileTransferError.ABORT_ERR` - * 5 = `FileTransferError.NOT_MODIFIED_ERR` - -## ì´ì „ 버전과 호환성 노트 - -ì´ í”ŒëŸ¬ê·¸ì¸ì˜ ì´ì „ 버전만 ì—…ë¡œë“œì— ëŒ€ í•œ 소스 ë˜ëŠ” ë‹¤ìš´ë¡œë“œì— ëŒ€ í•œ ëŒ€ìƒ ìž¥ì¹˜ 절대 íŒŒì¼ ê²½ë¡œ ë°›ì•„ë“¤ì¼ ê²ƒ ì´ë‹¤. ì´ëŸ¬í•œ 경로 ì¼ë°˜ì ìœ¼ë¡œ í¼ì˜ 것 - - /var/mobile/Applications//Documents/path/to/file (iOS) - /storage/emulated/0/path/to/file (Android) - - -대 í•œ ë’¤ 호환성, ì´ëŸ¬í•œ 경로 여전히 허용, 그리고 ì‘ìš© í”„ë¡œê·¸ëž¨ì´ ì˜êµ¬ 저장소ì—ì„œ ì´ì™€ ê°™ì€ ê²½ë¡œ ê¸°ë¡ í–ˆë‹¤, 그때 ê·¸ë“¤ì€ ê³„ì†í•  수 있다면 사용할 수. - -ì´ëŸ¬í•œ 경로 `FileEntry` ë° íŒŒì¼ í”ŒëŸ¬ê·¸ì¸ì— ì˜í•´ 반환 ëœ `DirectoryEntry` ê°œì²´ì˜ `fullPath` ì†ì„±ì— 노출 ë˜ì—ˆë˜. 그러나 íŒŒì¼ í”ŒëŸ¬ê·¸ì¸ì˜,, ë” ì´ìƒ 새로운 버전 ìžë°” 스í¬ë¦½íŠ¸ì´ 경로 노출. - -새로 업그레ì´ë“œ 하는 경우 (1.0.0 ì´ìƒ) ë²„ì „ì˜ íŒŒì¼, ë° ì´ì „ 사용 하 ê³  `entry.fullPath` `download()` ë˜ëŠ” `upload()` ì¸ìˆ˜ë¡œ ë‹¤ìŒ ëŒ€ì‹  íŒŒì¼ ì‹œìŠ¤í…œ Urlì„ ì‚¬ìš© 하 ì—¬ 코드를 변경 해야 합니다. - -í¼ì˜ íŒŒì¼ URLì„ ë°˜í™˜ 하는 `FileEntry.toURL()` ë° `DirectoryEntry.toURL()` - - cdvfile://localhost/persistent/path/to/file - - -ì–´ë–¤ `download()` ë° `upload()` 방법ì—ì„œ 절대 íŒŒì¼ ê²½ë¡œ 대신 사용할 수 있습니다. \ No newline at end of file diff --git a/plugins/cordova-plugin-file-transfer/doc/ko/index.md b/plugins/cordova-plugin-file-transfer/doc/ko/index.md deleted file mode 100644 index a6e39c0..0000000 --- a/plugins/cordova-plugin-file-transfer/doc/ko/index.md +++ /dev/null @@ -1,302 +0,0 @@ - - -# cordova-plugin-file-transfer - -ì´ í”ŒëŸ¬ê·¸ì¸ì„ 사용 하면 업로드 ë° ë‹¤ìš´ë¡œë“œ íŒŒì¼ ìˆ˜ 있습니다. - -ì´ í”ŒëŸ¬ê·¸ì¸ ê¸€ë¡œë²Œ `FileTransfer`, `FileUploadOptions` ìƒì„±ìžë¥¼ ì •ì˜í•©ë‹ˆë‹¤. - -ì „ì—­ 범위ì—ì„œ ê·¸ë“¤ì€ ì œê³µ ë˜ì§€ 않습니다 때까지 `deviceready` ì´ë²¤íŠ¸ 후. - - document.addEventListener("deviceready", onDeviceReady, false); - function onDeviceReady() { - console.log(FileTransfer); - } - - -## 설치 - - cordova plugin add cordova-plugin-file-transfer - - -## ì§€ì› ë˜ëŠ” í”Œëž«í¼ - -* 아마존 화재 ìš´ì˜ ì²´ì œ -* 안 ë“œ ë¡œì´ë“œ -* 블랙베리 10 -* 브ë¼ìš°ì € -* 파ì´ì–´ í­ìŠ¤ OS * * -* iOS -* Windows Phone 7ê³¼ 8 * -* 윈ë„ìš° 8 -* 윈ë„ìš° - -* *`onprogress`ë„ `abort()`를 ì§€ì› í•˜ì§€ 않습니다* - -* * *`onprogress`를 ì§€ì› í•˜ì§€ 않습니다* - -# FileTransfer - -`FileTransfer` 개체는 HTTP 다중 파트 POST ìš”ì²­ì„ ì‚¬ìš© 하 ì—¬ íŒŒì¼ ì—…ë¡œë“œ ë¿ë§Œ ì•„ë‹ˆë¼ íŒŒì¼ì„ 다운로드 하는 ë°©ë²•ì„ ì œê³µ 합니다. - -## ì†ì„± - -* **onprogress**:ë¡œ 불리는 `ProgressEvent` 새로운 ì–‘ì˜ ë°ì´í„°ë¥¼ 전송 하는 때마다. *(기능)* - -## 메서드 - -* **업로드**: 파ì¼ì„ ì„œë²„ì— ë³´ëƒ…ë‹ˆë‹¤. - -* **다운로드**: 서버ì—ì„œ 파ì¼ì„ 다운로드 합니다. - -* **중단**: 진행 ì¤‘ì¸ ì „ì†¡ 중단. - -## 업로드 - -**매개 변수**: - -* **fileURL**: ìž¥ì¹˜ì— íŒŒì¼ì„ 나타내는 íŒŒì¼ ì‹œìŠ¤í…œ URL. ì— ëŒ€ í•œ ì´ì „ 버전과 호환성ì„ì´ ìˆ˜ë„ ìž¥ì¹˜ì— ìžˆëŠ” 파ì¼ì˜ ì „ì²´ 경로 수. (참조 [거꾸로 호환성 노트] 아래) - -* **서버**: ì¸ì½”딩 íŒŒì¼ ìˆ˜ì‹  ì„œë²„ì˜ URL`encodeURI()`. - -* **successCallback**: `FileUploadResult` 개체를 전달 하는 콜백. *(기능)* - -* **errorCallback**: `FileUploadResult` ê²€ìƒ‰ì— ì˜¤ë¥˜ê°€ ë°œìƒ í•˜ë©´ 실행 ë˜ëŠ” 콜백. `FileTransferError` 개체와 함께 호출 ë©ë‹ˆë‹¤. *(기능)* - -* **옵션**: ì„ íƒì  매개 변수 *(개체)*. 유효한 키: - - * **fileKey**: form ìš”ì†Œì˜ ì´ë¦„. ê¸°ë³¸ê°’ì€ `file` . (DOMString) - * **íŒŒì¼ ì´ë¦„**: íŒŒì¼ ì´ë¦„ì„ ì„œë²„ì— íŒŒì¼ì„ 저장할 ë•Œ 사용 합니다. ê¸°ë³¸ê°’ì€ `image.jpg` . (DOMString) - * **httpMethod**: `넣어` ë˜ëŠ” `게시물`-사용 하ë„ë¡ HTTP 메서드. `게시물` 기본값입니다. (DOMString) - * **mimeType**: 업로드 ë°ì´í„°ì˜ mime 형ì‹ì„. `ì´ë¯¸ì§€/jpeg`ì˜ ê¸°ë³¸ê°’ìž…ë‹ˆë‹¤. (DOMString) - * **params**: HTTP ìš”ì²­ì— ì „ë‹¬í•  ì„ íƒì  키/ê°’ ìŒì˜ 집합. (개체) - * **chunkedMode**: ì²­í¬ ìŠ¤íŠ¸ë¦¬ë° ëª¨ë“œì—ì„œ ë°ì´í„° 업로드를 합니다. ê¸°ë³¸ê°’ì€ `true`입니다. (부울) - * **headers**: í—¤ë” ì´ë¦„/í—¤ë” ê°’ì˜ ì§€ë„. ë°°ì—´ì„ ì‚¬ìš© 하 ì—¬ 하나 ì´ìƒì˜ ê°’ì„ ì§€ì • 합니다. (개체) - -* **trustAllHosts**: ì„ íƒì  매개 변수는 기본ì ìœ¼ë¡œ `false` . 만약 설정 `true` , ê·¸ê²ƒì€ ëª¨ë“  보안 ì¸ì¦ì„œë¥¼ 허용 합니다. ì´ ì•ˆ ë“œ ë¡œì´ë“œ ìžì²´ 서명 ëœ ë³´ì•ˆ ì¸ì¦ì„œë¥¼ 거부 하기 ë•Œë¬¸ì— ìœ ìš© 합니다. 프로ë•ì…˜ 환경ì—ì„œ 사용 권장 ë˜ì§€ 않습니다. 안 ë“œ ë¡œì´ë“œì™€ iOSì—ì„œ 지ì›. *(부울)* - -### 예를 들어 - - // !! Assumes variable fileURL contains a valid URL to a text file on the device, - // for example, cdvfile://localhost/persistent/path/to/file.txt - - var win = function (r) { - console.log("Code = " + r.responseCode); - console.log("Response = " + r.response); - console.log("Sent = " + r.bytesSent); - } - - var fail = function (error) { - alert("An error has occurred: Code = " + error.code); - console.log("upload error source " + error.source); - console.log("upload error target " + error.target); - } - - var options = new FileUploadOptions(); - options.fileKey = "file"; - options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1); - options.mimeType = "text/plain"; - - var params = {}; - params.value1 = "test"; - params.value2 = "param"; - - options.params = params; - - var ft = new FileTransfer(); - ft.upload(fileURL, encodeURI("http://some.server.com/upload.php"), win, fail, options); - - -### 예를 들어 í—¤ë” ì—…ë¡œë“œ ë° ì§„í–‰ ì´ë²¤íŠ¸ (안 ë“œ ë¡œì´ë“œì™€ iOS만) - - function win(r) { - console.log("Code = " + r.responseCode); - console.log("Response = " + r.response); - console.log("Sent = " + r.bytesSent); - } - - function fail(error) { - alert("An error has occurred: Code = " + error.code); - console.log("upload error source " + error.source); - console.log("upload error target " + error.target); - } - - var uri = encodeURI("http://some.server.com/upload.php"); - - var options = new FileUploadOptions(); - options.fileKey="file"; - options.fileName=fileURL.substr(fileURL.lastIndexOf('/')+1); - options.mimeType="text/plain"; - - var headers={'headerParam':'headerValue'}; - - options.headers = headers; - - var ft = new FileTransfer(); - ft.onprogress = function(progressEvent) { - if (progressEvent.lengthComputable) { - loadingStatus.setPercentage(progressEvent.loaded / progressEvent.total); - } else { - loadingStatus.increment(); - } - }; - ft.upload(fileURL, uri, win, fail, options); - - -## FileUploadResult - -`FileUploadResult` 개체 `FileTransfer` ê°œì²´ì˜ `ì›ëž˜` ë°©ë²•ì˜ ì„±ê³µ ì½œë°±ì— ì „ë‹¬ ë©ë‹ˆë‹¤. - -### ì†ì„± - -* **bytesSent**: ì—…ë¡œë“œì˜ ì¼ë¶€ë¡œ ì„œë²„ì— ë³´ë‚¸ ë°”ì´íŠ¸ 수. (긴) - -* **responseCode**: 서버ì—ì„œ 반환 ëœ HTTP ì‘답 코드. (긴) - -* **response**: 서버ì—ì„œ 반환 ë˜ëŠ” HTTP ì‘답. (DOMString) - -* **headers**: 서버ì—ì„œ HTTP ì‘답 í—¤ë”. (개체) - - * 현재 ios만 ì§€ì› í•©ë‹ˆë‹¤. - -### iOS ë‹¨ì  - -* ì§€ì› í•˜ì§€ 않는 `responseCode` ë˜ëŠ”`bytesSent`. - -## download - -**매개 변수**: - -* **source**: URLë¡œ ì¸ì½”ë”©ëœ íŒŒì¼, 다운로드 서버`encodeURI()`. - -* **target**: ìž¥ì¹˜ì— íŒŒì¼ì„ 나타내는 íŒŒì¼ ì‹œìŠ¤í…œ url. ì— ëŒ€ í•œ ì´ì „ 버전과 호환성ì„ì´ ìˆ˜ë„ ìž¥ì¹˜ì— ìžˆëŠ” 파ì¼ì˜ ì „ì²´ 경로 수. (참조 [거꾸로 호환성 노트] 아래) - -* **successCallback**: 콜백 전달 ë˜ëŠ” `FileEntry` 개체. *(기능)* - -* **errorCallback**: `FileEntry`를 검색할 ë•Œ 오류가 ë°œìƒ í•˜ë©´ 실행 ë˜ëŠ” 콜백. `FileTransferError` 개체와 함께 호출 ë©ë‹ˆë‹¤. *(기능)* - -* **trustAllHosts**: ì„ íƒì  매개 변수는 기본ì ìœ¼ë¡œ `false` . 만약 설정 `true` , ê·¸ê²ƒì€ ëª¨ë“  보안 ì¸ì¦ì„œë¥¼ 허용 합니다. 안 ë“œ ë¡œì´ë“œ ìžì²´ 서명 ëœ ë³´ì•ˆ ì¸ì¦ì„œë¥¼ 거부 하기 ë•Œë¬¸ì— ìœ ìš© 합니다. 프로ë•ì…˜ 환경ì—ì„œ 사용 권장 ë˜ì§€ 않습니다. 안 ë“œ ë¡œì´ë“œì™€ iOSì—ì„œ 지ì›. *(부울)* - -* **options**: ì„ íƒì  매개 변수를 현재 지 ì›í•˜ëŠ” 머리글만 (예: ì¸ì¦ (기본 ì¸ì¦), 등). - -### 예를 들어 - - // !! Assumes variable fileURL contains a valid URL to a path on the device, - // for example, cdvfile://localhost/persistent/path/to/downloads/ - - var fileTransfer = new FileTransfer(); - var uri = encodeURI("http://some.server.com/download.php"); - - fileTransfer.download( - uri, - fileURL, - function(entry) { - console.log("download complete: " + entry.toURL()); - }, - function(error) { - console.log("download error source " + error.source); - console.log("download error target " + error.target); - console.log("upload error code" + error.code); - }, - false, - { - headers: { - "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA==" - } - } - ); - - -## abort - -진행 ì¤‘ì¸ ì „ì†¡ì„ ì¤‘ë‹¨í•©ë‹ˆë‹¤. onerror 콜백 FileTransferError.ABORT_ERRì˜ ì˜¤ë¥˜ 코드는 FileTransferError 개체를 전달 합니다. - -### 예를 들어 - - // !! Assumes variable fileURL contains a valid URL to a text file on the device, - // for example, cdvfile://localhost/persistent/path/to/file.txt - - var win = function(r) { - console.log("Should not be called."); - } - - var fail = function(error) { - // error.code == FileTransferError.ABORT_ERR - alert("An error has occurred: Code = " + error.code); - console.log("upload error source " + error.source); - console.log("upload error target " + error.target); - } - - var options = new FileUploadOptions(); - options.fileKey="file"; - options.fileName="myphoto.jpg"; - options.mimeType="image/jpeg"; - - var ft = new FileTransfer(); - ft.upload(fileURL, encodeURI("http://some.server.com/upload.php"), win, fail, options); - ft.abort(); - - -## FileTransferError - -`FileTransferError` 개체 오류가 ë°œìƒ í•˜ë©´ 오류 ì½œë°±ì— ì „ë‹¬ ë©ë‹ˆë‹¤. - -### ì†ì„± - -* **code**: 미리 ì •ì˜ ëœ ì˜¤ë¥˜ 코드 중 하나가 ì•„ëž˜ì— ë‚˜ì—´ ëœ. (수) - -* **source**: 소스 URL. (문ìžì—´) - -* **target**: ëŒ€ìƒ URL. (문ìžì—´) - -* **http_status**: HTTP ìƒíƒœ 코드. ì´ íŠ¹ì„±ì€ ì‘답 코드를 HTTP ì—°ê²°ì—ì„œ ìˆ˜ì‹ ì— ì‚¬ìš©í•  수 있습니다. (수) - -* **body** ì‘답 본문입니다. ì´ íŠ¹ì„±ì€ HTTP ì—°ê²°ì—ì„œ ì‘ë‹µì„ ë°›ì„ ë•Œì— ì‚¬ìš©í•  수 있습니다. (문ìžì—´) - -* **exception**: ì–´ëŠ e.getMessage ë˜ëŠ” e.toString (문ìžì—´) - -### ìƒìˆ˜ - -* 1 = `FileTransferError.FILE_NOT_FOUND_ERR` -* 2 = `FileTransferError.INVALID_URL_ERR` -* 3 = `FileTransferError.CONNECTION_ERR` -* 4 = `FileTransferError.ABORT_ERR` -* 5 = `FileTransferError.NOT_MODIFIED_ERR` - -## ì´ì „ 버전과 호환성 노트 - -ì´ í”ŒëŸ¬ê·¸ì¸ì˜ ì´ì „ 버전만 ì—…ë¡œë“œì— ëŒ€ í•œ 소스 ë˜ëŠ” ë‹¤ìš´ë¡œë“œì— ëŒ€ í•œ ëŒ€ìƒ ìž¥ì¹˜ 절대 íŒŒì¼ ê²½ë¡œ ë°›ì•„ë“¤ì¼ ê²ƒ ì´ë‹¤. ì´ëŸ¬í•œ 경로 ì¼ë°˜ì ìœ¼ë¡œ í¼ì˜ 것 - - /var/mobile/Applications//Documents/path/to/file (iOS) - /storage/emulated/0/path/to/file (Android) - - -대 í•œ ë’¤ 호환성, ì´ëŸ¬í•œ 경로 여전히 허용, 그리고 ì‘ìš© í”„ë¡œê·¸ëž¨ì´ ì˜êµ¬ 저장소ì—ì„œ ì´ì™€ ê°™ì€ ê²½ë¡œ ê¸°ë¡ í–ˆë‹¤, 그때 ê·¸ë“¤ì€ ê³„ì†í•  수 있다면 사용할 수. - -ì´ëŸ¬í•œ 경로 `FileEntry` ë° íŒŒì¼ í”ŒëŸ¬ê·¸ì¸ì— ì˜í•´ 반환 ëœ `DirectoryEntry` ê°œì²´ì˜ `fullPath` ì†ì„±ì— 노출 ë˜ì—ˆë˜. 그러나 íŒŒì¼ í”ŒëŸ¬ê·¸ì¸ì˜,, ë” ì´ìƒ 새로운 버전 ìžë°” 스í¬ë¦½íŠ¸ì´ 경로 노출. - -새로 업그레ì´ë“œ 하는 경우 (1.0.0 ì´ìƒ) ë²„ì „ì˜ íŒŒì¼, ë° ì´ì „ 사용 하 ê³  `entry.fullPath` `download()` ë˜ëŠ” `upload()` ì¸ìˆ˜ë¡œ ë‹¤ìŒ ëŒ€ì‹  íŒŒì¼ ì‹œìŠ¤í…œ Urlì„ ì‚¬ìš© 하 ì—¬ 코드를 변경 해야 합니다. - -í¼ì˜ íŒŒì¼ URLì„ ë°˜í™˜ 하는 `FileEntry.toURL()` ë° `DirectoryEntry.toURL()` - - cdvfile://localhost/persistent/path/to/file - - -ì–´ë–¤ `download()` ë° `upload()` 방법ì—ì„œ 절대 íŒŒì¼ ê²½ë¡œ 대신 사용할 수 있습니다. diff --git a/plugins/cordova-plugin-file-transfer/doc/pl/README.md b/plugins/cordova-plugin-file-transfer/doc/pl/README.md deleted file mode 100644 index c430979..0000000 --- a/plugins/cordova-plugin-file-transfer/doc/pl/README.md +++ /dev/null @@ -1,311 +0,0 @@ - - -# cordova-plugin-file-transfer - -[![Build Status](https://travis-ci.org/apache/cordova-plugin-file-transfer.svg)](https://travis-ci.org/apache/cordova-plugin-file-transfer) - -Plugin dokumentacja: - -Plugin pozwala na przesyÅ‚anie i pobieranie plików. - -Ten plugin okreÅ›la globalne `FileTransfer`, `FileUploadOptions` konstruktorów. - -Chociaż w globalnym zasiÄ™gu, sÄ… nie dostÄ™pne dopiero po `deviceready` imprezie. - - document.addEventListener("deviceready", onDeviceReady, false); - function onDeviceReady() { - console.log(FileTransfer); - } - - -## Instalacja - - cordova plugin add cordova-plugin-file-transfer - - -## ObsÅ‚ugiwane platformy - - * Amazon Fire OS - * Android - * BlackBerry 10 - * PrzeglÄ…darka - * Firefox OS ** - * iOS - * Windows Phone 7 i 8 * - * Windows 8 - * Windows - -\ * *Nie obsÅ‚ugujÄ… `onprogress` ani `abort()` * - -\ ** *Nie obsÅ‚ugujÄ… `onprogress` * - -# FileTransfer - -Obiekt `FileTransfer` zapewnia sposób wgrać pliki za pomocÄ… Multi-część POST lub PUT żądania HTTP i pobierania plików, jak również. - -## WÅ‚aÅ›ciwoÅ›ci - - * **OnProgress**: o nazwie `ProgressEvent` gdy nowy kawaÅ‚ek danych jest przenoszona. *(Funkcja)* - -## Metody - - * **wgraj**: wysyÅ‚a plik na serwer. - - * **do pobrania**: pliki do pobrania pliku z serwera. - - * **przerwać**: przerywa w toku transferu. - -## upload - -**Parametry**: - - * **fileURL**: URL plików reprezentujÄ…cych pliku na urzÄ…dzenie. Dla wstecznej kompatybilnoÅ›ci, to może również być peÅ‚nÄ… Å›cieżkÄ™ pliku na urzÄ…dzenie. (Zobacz [wstecz zgodnoÅ›ci zauważa] poniżej) - - * **serwer**: adres URL serwera, aby otrzymać plik, jak kodowane przez`encodeURI()`. - - * **successCallback**: wywoÅ‚ania zwrotnego, który jest przekazywany obiekt `FileUploadResult`. *(Funkcja)* - - * **errorCallback**: wywoÅ‚anie zwrotne, które wykonuje, jeżeli wystÄ…pi bÅ‚Ä…d pobierania `FileUploadResult`. WywoÅ‚ywany z obiektu `FileTransferError`. *(Funkcja)* - - * **Opcje**: parametry opcjonalne *(obiektu)*. Ważne klucze: - - * **fileKey**: nazwa elementu form. DomyÅ›lnie `file` . (DOMString) - * **Nazwa pliku**: nazwy pliku, aby użyć podczas zapisywania pliku na serwerze. DomyÅ›lnie `image.jpg` . (DOMString) - * **element httpMethod**: Metoda HTTP do użycia - `umieÅ›cić` lub `POST`. DomyÅ›lnie `POST`. (DOMString) - * **mimeType**: Typ mime danych do przesÅ‚ania. DomyÅ›lnie do `image/jpeg`. (DOMString) - * **params**: zestaw par opcjonalny klucz/wartość w żądaniu HTTP. (Obiekt) - * **chunkedMode**: czy przekazać dane w trybie pakietowego przesyÅ‚ania strumieniowego. WartoÅ›ciÄ… domyÅ›lnÄ… jest `true`. (Wartość logiczna) - * **headers**: Mapa wartoÅ›ci Nazwa/nagłówka nagłówek. Aby okreÅ›lić wiÄ™cej niż jednÄ… wartość, należy użyć tablicÄ™. Na iOS, FireOS i Android jeÅ›li nagłówek o nazwie Content-Type jest obecny, wieloczęściowa forma nie danych. (Object) - * **element httpMethod**: Metoda HTTP np. POST lub PUT. Ustawienia domyÅ›lne do `POST`. (DOMString) - - * **trustAllHosts**: parametr opcjonalny, domyÅ›lnie `false` . JeÅ›li zestaw `true` , to akceptuje wszystkie certyfikaty bezpieczeÅ„stwa. Jest to przydatne, ponieważ Android odrzuca Certyfikaty samopodpisane. Nie zaleca siÄ™ do użytku produkcyjnego. ObsÅ‚ugiwane na Androida i iOS. *(wartość logiczna)* - -### PrzykÅ‚ad - - // !! Assumes variable fileURL contains a valid URL to a text file on the device, - // for example, cdvfile://localhost/persistent/path/to/file.txt - - var win = function (r) { - console.log("Code = " + r.responseCode); - console.log("Response = " + r.response); - console.log("Sent = " + r.bytesSent); - } - - var fail = function (error) { - alert("An error has occurred: Code = " + error.code); - console.log("upload error source " + error.source); - console.log("upload error target " + error.target); - } - - var options = new FileUploadOptions(); - options.fileKey = "file"; - options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1); - options.mimeType = "text/plain"; - - var params = {}; - params.value1 = "test"; - params.value2 = "param"; - - options.params = params; - - var ft = new FileTransfer(); - ft.upload(fileURL, encodeURI("http://some.server.com/upload.php"), win, fail, options); - - -### PrzykÅ‚ad z PrzeÅ›lij nagłówki i zdarzeÅ„ postÄ™pu (Android i iOS tylko) - - function win(r) { - console.log("Code = " + r.responseCode); - console.log("Response = " + r.response); - console.log("Sent = " + r.bytesSent); - } - - function fail(error) { - alert("An error has occurred: Code = " + error.code); - console.log("upload error source " + error.source); - console.log("upload error target " + error.target); - } - - var uri = encodeURI("http://some.server.com/upload.php"); - - var options = new FileUploadOptions(); - options.fileKey="file"; - options.fileName=fileURL.substr(fileURL.lastIndexOf('/')+1); - options.mimeType="text/plain"; - - var headers={'headerParam':'headerValue'}; - - options.headers = headers; - - var ft = new FileTransfer(); - ft.onprogress = function(progressEvent) { - if (progressEvent.lengthComputable) { - loadingStatus.setPercentage(progressEvent.loaded / progressEvent.total); - } else { - loadingStatus.increment(); - } - }; - ft.upload(fileURL, uri, win, fail, options); - - -## FileUploadResult - -Obiekt `FileUploadResult` jest przekazywana do sukcesu wywoÅ‚ania zwrotnego metody `upload() sÅ‚użącÄ…` obiektu `FileTransfer`. - -### WÅ‚aÅ›ciwoÅ›ci - - * **bytesSent**: liczba bajtów wysÅ‚anych do serwera jako część upload. (dÅ‚ugie) - - * **responseCode**: kod odpowiedzi HTTP, zwracane przez serwer. (dÅ‚ugie) - - * **odpowiedź**: HTTP odpowiedzi zwracane przez serwer. (DOMString) - - * **nagłówki**: nagłówki HTTP odpowiedzi przez serwer. (Obiekt) - - * Obecnie obsÅ‚ugiwane na iOS tylko. - -### Dziwactwa iOS - - * Nie obsÅ‚uguje `responseCode` lub`bytesSent`. - -## download - -**Parametry**: - - * **ŹródÅ‚o**: adres URL serwera, aby pobrać plik, jak kodowane przez`encodeURI()`. - - * **cel**: url plików reprezentujÄ…cych pliku na urzÄ…dzenie. Dla wstecznej kompatybilnoÅ›ci, to może również być peÅ‚nÄ… Å›cieżkÄ™ pliku na urzÄ…dzenie. (Zobacz [wstecz zgodnoÅ›ci zauważa] poniżej) - - * **successCallback**: wywoÅ‚ania zwrotnego, który jest przekazywany `FileEntry` obiektu. *(Funkcja)* - - * **errorCallback**: wywoÅ‚anie zwrotne, które wykonuje, jeÅ›li wystÄ…pi bÅ‚Ä…d podczas pobierania `FileEntry`. WywoÅ‚ywany z obiektu `FileTransferError`. *(Funkcja)* - - * **trustAllHosts**: parametr opcjonalny, domyÅ›lnie `false` . JeÅ›li zestaw `true` , to akceptuje wszystkie certyfikaty bezpieczeÅ„stwa. Jest to przydatne, ponieważ Android odrzuca Certyfikaty samopodpisane. Nie zaleca siÄ™ do użytku produkcyjnego. ObsÅ‚ugiwane na Androida i iOS. *(wartość logiczna)* - - * **Opcje**: parametry opcjonalne, obecnie tylko obsÅ‚uguje nagłówki (takie jak autoryzacja (uwierzytelnianie podstawowe), itp.). - -### PrzykÅ‚ad - - // !! Assumes variable fileURL contains a valid URL to a path on the device, - // for example, cdvfile://localhost/persistent/path/to/downloads/ - - var fileTransfer = new FileTransfer(); - var uri = encodeURI("http://some.server.com/download.php"); - - fileTransfer.download( - uri, - fileURL, - function(entry) { - console.log("download complete: " + entry.toURL()); - }, - function(error) { - console.log("download error source " + error.source); - console.log("download error target " + error.target); - console.log("upload error code" + error.code); - }, - false, - { - headers: { - "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA==" - } - } - ); - - -### WP8 dziwactwa - - * Pobierz wnioski sÄ… buforowane przez rodzimych realizacji. Aby uniknąć, buforowanie, przekazać `if-Modified-Since` nagłówka do pobrania Metoda. - -## abort - -Przerywa w toku transferu. Onerror callback jest przekazywany obiekt FileTransferError, który kod bÅ‚Ä™du z FileTransferError.ABORT_ERR. - -### PrzykÅ‚ad - - // !! Assumes variable fileURL contains a valid URL to a text file on the device, - // for example, cdvfile://localhost/persistent/path/to/file.txt - - var win = function(r) { - console.log("Should not be called."); - } - - var fail = function(error) { - // error.code == FileTransferError.ABORT_ERR - alert("An error has occurred: Code = " + error.code); - console.log("upload error source " + error.source); - console.log("upload error target " + error.target); - } - - var options = new FileUploadOptions(); - options.fileKey="file"; - options.fileName="myphoto.jpg"; - options.mimeType="image/jpeg"; - - var ft = new FileTransfer(); - ft.upload(fileURL, encodeURI("http://some.server.com/upload.php"), win, fail, options); - ft.abort(); - - -## FileTransferError - -Obiekt `FileTransferError` jest przekazywana do bÅ‚Ä…d wywoÅ‚ania zwrotnego, gdy wystÄ…pi bÅ‚Ä…d. - -### WÅ‚aÅ›ciwoÅ›ci - - * **Kod**: jeden z kodów bÅ‚Ä™dów wstÄ™pnie zdefiniowanych poniżej. (Liczba) - - * **ŹródÅ‚o**: URL do źródÅ‚a. (String) - - * **cel**: adres URL do docelowego. (String) - - * **HTTP_STATUS**: kod stanu HTTP. Ten atrybut jest dostÄ™pna tylko po otrzymaniu kodu odpowiedzi z poÅ‚Ä…czenia HTTP. (Liczba) - - * **body** Treść odpowiedzi. Ten atrybut jest dostÄ™pna tylko wtedy, gdy odpowiedź jest otrzymanych od poÅ‚Ä…czenia HTTP. (String) - - * **exception**: albo e.getMessage lub e.toString (String) - -### StaÅ‚e - - * 1 = `FileTransferError.FILE_NOT_FOUND_ERR` - * 2 = `FileTransferError.INVALID_URL_ERR` - * 3 = `FileTransferError.CONNECTION_ERR` - * 4 = `FileTransferError.ABORT_ERR` - * 5 = `FileTransferError.NOT_MODIFIED_ERR` - -## Do tyÅ‚u zgodnoÅ›ci stwierdza - -Poprzednie wersje tego pluginu tylko zaakceptować urzÄ…dzenia bezwzglÄ™dnych Å›cieżek jako źródÅ‚o dla przekazywania, lub w celu pobrania. Te Å›cieżki bÄ™dzie zazwyczaj formy - - /var/mobile/Applications//Documents/path/to/file (iOS) - /storage/emulated/0/path/to/file (Android) - - -Do tyÅ‚u zgodnoÅ›ci, akceptowane sÄ… jeszcze te Å›cieżki, i jeÅ›li aplikacja nagraÅ‚ Å›cieżki, jak te w trwaÅ‚ej pamiÄ™ci, nastÄ™pnie można nadal stosować. - -Te Å›cieżki byÅ‚y narażone wczeÅ›niej we wÅ‚aÅ›ciwoÅ›ci `fullPath` `FileEntry` i `DirectoryEntry` obiektów zwróconych przez wtyczki pliku. Nowe wersje pliku plugin, jednak już wystawiać te Å›cieżki do JavaScript. - -JeÅ›li uaktualniasz nowy (1.0.0 lub nowsza) wersja pliku i mieć wczeÅ›niej przy `entry.fullPath` jako argumenty `download()` lub `upload() sÅ‚użącÄ…`, a nastÄ™pnie trzeba bÄ™dzie zmienić kod aby używać adresów URL plików zamiast. - -`FileEntry.toURL()` i `DirectoryEntry.toURL()` zwraca adres URL plików formularza - - cdvfile://localhost/persistent/path/to/file - - -które mogÄ… być używane zamiast bezwzglÄ™dna Å›cieżka zarówno `download()` i `metody upload()` metody. \ No newline at end of file diff --git a/plugins/cordova-plugin-file-transfer/doc/pl/index.md b/plugins/cordova-plugin-file-transfer/doc/pl/index.md deleted file mode 100644 index ff9b557..0000000 --- a/plugins/cordova-plugin-file-transfer/doc/pl/index.md +++ /dev/null @@ -1,302 +0,0 @@ - - -# cordova-plugin-file-transfer - -Plugin pozwala na przesyÅ‚anie i pobieranie plików. - -Ten plugin okreÅ›la globalne `FileTransfer`, `FileUploadOptions` konstruktorów. - -Chociaż w globalnym zasiÄ™gu, sÄ… nie dostÄ™pne dopiero po `deviceready` imprezie. - - document.addEventListener("deviceready", onDeviceReady, false); - function onDeviceReady() { - console.log(FileTransfer); - } - - -## Instalacja - - cordova plugin add cordova-plugin-file-transfer - - -## ObsÅ‚ugiwane platformy - -* Amazon Fire OS -* Android -* BlackBerry 10 -* PrzeglÄ…darka -* Firefox OS ** -* iOS -* Windows Phone 7 i 8 * -* Windows 8 -* Windows - -* *Nie obsÅ‚ugujÄ… `onprogress` ani `abort()`* - -* * *Nie obsÅ‚ugujÄ… `onprogress`* - -# FileTransfer - -Obiekt `FileTransfer` zapewnia sposób wgrać pliki przy użyciu żądania HTTP wieloczęściowe POST i pobierania plików, jak również. - -## WÅ‚aÅ›ciwoÅ›ci - -* **OnProgress**: o nazwie `ProgressEvent` gdy nowy kawaÅ‚ek danych jest przenoszona. *(Funkcja)* - -## Metody - -* **wgraj**: wysyÅ‚a plik na serwer. - -* **do pobrania**: pliki do pobrania pliku z serwera. - -* **przerwać**: przerywa w toku transferu. - -## upload - -**Parametry**: - -* **fileURL**: URL plików reprezentujÄ…cych pliku na urzÄ…dzenie. Dla wstecznej kompatybilnoÅ›ci, to może również być peÅ‚nÄ… Å›cieżkÄ™ pliku na urzÄ…dzenie. (Zobacz [wstecz zgodnoÅ›ci zauważa] poniżej) - -* **serwer**: adres URL serwera, aby otrzymać plik, jak kodowane przez`encodeURI()`. - -* **successCallback**: wywoÅ‚ania zwrotnego, który jest przekazywany obiekt `FileUploadResult`. *(Funkcja)* - -* **errorCallback**: wywoÅ‚anie zwrotne, które wykonuje, jeżeli wystÄ…pi bÅ‚Ä…d pobierania `FileUploadResult`. WywoÅ‚ywany z obiektu `FileTransferError`. *(Funkcja)* - -* **Opcje**: parametry opcjonalne *(obiektu)*. Ważne klucze: - - * **fileKey**: nazwa elementu form. DomyÅ›lnie `file` . (DOMString) - * **Nazwa pliku**: nazwy pliku, aby użyć podczas zapisywania pliku na serwerze. DomyÅ›lnie `image.jpg` . (DOMString) - * **element httpMethod**: Metoda HTTP do użycia - `umieÅ›cić` lub `POST`. DomyÅ›lnie `POST`. (DOMString) - * **mimeType**: Typ mime danych do przesÅ‚ania. DomyÅ›lnie do `image/jpeg`. (DOMString) - * **params**: zestaw par opcjonalny klucz/wartość w żądaniu HTTP. (Obiekt) - * **chunkedMode**: czy przekazać dane w trybie pakietowego przesyÅ‚ania strumieniowego. WartoÅ›ciÄ… domyÅ›lnÄ… jest `true`. (Wartość logiczna) - * **headers**: Mapa wartoÅ›ci Nazwa/nagłówka nagłówek. Aby okreÅ›lić wiÄ™cej niż jednÄ… wartość, należy użyć tablicÄ™. (Obiekt) - -* **trustAllHosts**: parametr opcjonalny, domyÅ›lnie `false` . JeÅ›li zestaw `true` , to akceptuje wszystkie certyfikaty bezpieczeÅ„stwa. Jest to przydatne, ponieważ Android odrzuca Certyfikaty samopodpisane. Nie zaleca siÄ™ do użytku produkcyjnego. ObsÅ‚ugiwane na Androida i iOS. *(wartość logiczna)* - -### PrzykÅ‚ad - - // !! Assumes variable fileURL contains a valid URL to a text file on the device, - // for example, cdvfile://localhost/persistent/path/to/file.txt - - var win = function (r) { - console.log("Code = " + r.responseCode); - console.log("Response = " + r.response); - console.log("Sent = " + r.bytesSent); - } - - var fail = function (error) { - alert("An error has occurred: Code = " + error.code); - console.log("upload error source " + error.source); - console.log("upload error target " + error.target); - } - - var options = new FileUploadOptions(); - options.fileKey = "file"; - options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1); - options.mimeType = "text/plain"; - - var params = {}; - params.value1 = "test"; - params.value2 = "param"; - - options.params = params; - - var ft = new FileTransfer(); - ft.upload(fileURL, encodeURI("http://some.server.com/upload.php"), win, fail, options); - - -### PrzykÅ‚ad z PrzeÅ›lij nagłówki i zdarzeÅ„ postÄ™pu (Android i iOS tylko) - - function win(r) { - console.log("Code = " + r.responseCode); - console.log("Response = " + r.response); - console.log("Sent = " + r.bytesSent); - } - - function fail(error) { - alert("An error has occurred: Code = " + error.code); - console.log("upload error source " + error.source); - console.log("upload error target " + error.target); - } - - var uri = encodeURI("http://some.server.com/upload.php"); - - var options = new FileUploadOptions(); - options.fileKey="file"; - options.fileName=fileURL.substr(fileURL.lastIndexOf('/')+1); - options.mimeType="text/plain"; - - var headers={'headerParam':'headerValue'}; - - options.headers = headers; - - var ft = new FileTransfer(); - ft.onprogress = function(progressEvent) { - if (progressEvent.lengthComputable) { - loadingStatus.setPercentage(progressEvent.loaded / progressEvent.total); - } else { - loadingStatus.increment(); - } - }; - ft.upload(fileURL, uri, win, fail, options); - - -## FileUploadResult - -Obiekt `FileUploadResult` jest przekazywana do sukcesu wywoÅ‚ania zwrotnego metody `upload() sÅ‚użącÄ…` obiektu `FileTransfer`. - -### WÅ‚aÅ›ciwoÅ›ci - -* **bytesSent**: liczba bajtów wysÅ‚anych do serwera jako część upload. (dÅ‚ugie) - -* **responseCode**: kod odpowiedzi HTTP, zwracane przez serwer. (dÅ‚ugie) - -* **odpowiedź**: HTTP odpowiedzi zwracane przez serwer. (DOMString) - -* **nagłówki**: nagłówki HTTP odpowiedzi przez serwer. (Obiekt) - - * Obecnie obsÅ‚ugiwane na iOS tylko. - -### Dziwactwa iOS - -* Nie obsÅ‚uguje `responseCode` lub`bytesSent`. - -## download - -**Parametry**: - -* **ŹródÅ‚o**: adres URL serwera, aby pobrać plik, jak kodowane przez`encodeURI()`. - -* **cel**: url plików reprezentujÄ…cych pliku na urzÄ…dzenie. Dla wstecznej kompatybilnoÅ›ci, to może również być peÅ‚nÄ… Å›cieżkÄ™ pliku na urzÄ…dzenie. (Zobacz [wstecz zgodnoÅ›ci zauważa] poniżej) - -* **successCallback**: wywoÅ‚ania zwrotnego, który jest przekazywany `FileEntry` obiektu. *(Funkcja)* - -* **errorCallback**: wywoÅ‚anie zwrotne, które wykonuje, jeÅ›li wystÄ…pi bÅ‚Ä…d podczas pobierania `FileEntry`. WywoÅ‚ywany z obiektu `FileTransferError`. *(Funkcja)* - -* **trustAllHosts**: parametr opcjonalny, domyÅ›lnie `false` . JeÅ›li zestaw `true` , to akceptuje wszystkie certyfikaty bezpieczeÅ„stwa. Jest to przydatne, ponieważ Android odrzuca Certyfikaty samopodpisane. Nie zaleca siÄ™ do użytku produkcyjnego. ObsÅ‚ugiwane na Androida i iOS. *(wartość logiczna)* - -* **Opcje**: parametry opcjonalne, obecnie tylko obsÅ‚uguje nagłówki (takie jak autoryzacja (uwierzytelnianie podstawowe), itp.). - -### PrzykÅ‚ad - - // !! Assumes variable fileURL contains a valid URL to a path on the device, - // for example, cdvfile://localhost/persistent/path/to/downloads/ - - var fileTransfer = new FileTransfer(); - var uri = encodeURI("http://some.server.com/download.php"); - - fileTransfer.download( - uri, - fileURL, - function(entry) { - console.log("download complete: " + entry.toURL()); - }, - function(error) { - console.log("download error source " + error.source); - console.log("download error target " + error.target); - console.log("upload error code" + error.code); - }, - false, - { - headers: { - "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA==" - } - } - ); - - -## abort - -Przerywa w toku transferu. Onerror callback jest przekazywany obiekt FileTransferError, który kod bÅ‚Ä™du z FileTransferError.ABORT_ERR. - -### PrzykÅ‚ad - - // !! Assumes variable fileURL contains a valid URL to a text file on the device, - // for example, cdvfile://localhost/persistent/path/to/file.txt - - var win = function(r) { - console.log("Should not be called."); - } - - var fail = function(error) { - // error.code == FileTransferError.ABORT_ERR - alert("An error has occurred: Code = " + error.code); - console.log("upload error source " + error.source); - console.log("upload error target " + error.target); - } - - var options = new FileUploadOptions(); - options.fileKey="file"; - options.fileName="myphoto.jpg"; - options.mimeType="image/jpeg"; - - var ft = new FileTransfer(); - ft.upload(fileURL, encodeURI("http://some.server.com/upload.php"), win, fail, options); - ft.abort(); - - -## FileTransferError - -Obiekt `FileTransferError` jest przekazywana do bÅ‚Ä…d wywoÅ‚ania zwrotnego, gdy wystÄ…pi bÅ‚Ä…d. - -### WÅ‚aÅ›ciwoÅ›ci - -* **Kod**: jeden z kodów bÅ‚Ä™dów wstÄ™pnie zdefiniowanych poniżej. (Liczba) - -* **ŹródÅ‚o**: URL do źródÅ‚a. (String) - -* **cel**: adres URL do docelowego. (String) - -* **HTTP_STATUS**: kod stanu HTTP. Ten atrybut jest dostÄ™pna tylko po otrzymaniu kodu odpowiedzi z poÅ‚Ä…czenia HTTP. (Liczba) - -* **body** Treść odpowiedzi. Ten atrybut jest dostÄ™pna tylko wtedy, gdy odpowiedź jest otrzymanych od poÅ‚Ä…czenia HTTP. (String) - -* **exception**: albo e.getMessage lub e.toString (String) - -### StaÅ‚e - -* 1 = `FileTransferError.FILE_NOT_FOUND_ERR` -* 2 = `FileTransferError.INVALID_URL_ERR` -* 3 = `FileTransferError.CONNECTION_ERR` -* 4 = `FileTransferError.ABORT_ERR` -* 5 = `FileTransferError.NOT_MODIFIED_ERR` - -## Do tyÅ‚u zgodnoÅ›ci stwierdza - -Poprzednie wersje tego pluginu tylko zaakceptować urzÄ…dzenia bezwzglÄ™dnych Å›cieżek jako źródÅ‚o dla przekazywania, lub w celu pobrania. Te Å›cieżki bÄ™dzie zazwyczaj formy - - /var/mobile/Applications//Documents/path/to/file (iOS) - /storage/emulated/0/path/to/file (Android) - - -Do tyÅ‚u zgodnoÅ›ci, akceptowane sÄ… jeszcze te Å›cieżki, i jeÅ›li aplikacja nagraÅ‚ Å›cieżki, jak te w trwaÅ‚ej pamiÄ™ci, nastÄ™pnie można nadal stosować. - -Te Å›cieżki byÅ‚y narażone wczeÅ›niej we wÅ‚aÅ›ciwoÅ›ci `fullPath` `FileEntry` i `DirectoryEntry` obiektów zwróconych przez wtyczki pliku. Nowe wersje pliku plugin, jednak już wystawiać te Å›cieżki do JavaScript. - -JeÅ›li uaktualniasz nowy (1.0.0 lub nowsza) wersja pliku i mieć wczeÅ›niej przy `entry.fullPath` jako argumenty `download()` lub `upload() sÅ‚użącÄ…`, a nastÄ™pnie trzeba bÄ™dzie zmienić kod aby używać adresów URL plików zamiast. - -`FileEntry.toURL()` i `DirectoryEntry.toURL()` zwraca adres URL plików formularza - - cdvfile://localhost/persistent/path/to/file - - -które mogÄ… być używane zamiast bezwzglÄ™dna Å›cieżka zarówno `download()` i `metody upload()` metody. diff --git a/plugins/cordova-plugin-file-transfer/doc/ru/index.md b/plugins/cordova-plugin-file-transfer/doc/ru/index.md deleted file mode 100644 index cdd5a15..0000000 --- a/plugins/cordova-plugin-file-transfer/doc/ru/index.md +++ /dev/null @@ -1,290 +0,0 @@ - - -# cordova-plugin-file-transfer - -Этот плагин позволÑет вам загружать и Ñкачивать файлы. - -## УÑтановка - - cordova plugin add cordova-plugin-file-transfer - - -## Поддерживаемые платформы - -* Amazon Fire OS -* Android -* BlackBerry 10 -* Firefox OS ** -* iOS -* Windows Phone 7 и 8 * -* Windows 8 ***| -* Windows ***| - -* *Ðе поддерживают `onprogress` , ни `abort()` * - -** *Ðе поддерживает `onprogress` * - -ЧаÑÑ‚Ð¸Ñ‡Ð½Ð°Ñ Ð¿Ð¾Ð´Ð´ÐµÑ€Ð¶ÐºÐ° `onprogress` Ð´Ð»Ñ Ð·Ð°ÐºÐ°Ñ‡ÐºÐ¸ метод. `onprogress` вызываетÑÑ Ñ Ð¿ÑƒÑтой ход Ñобытий Ð±Ð»Ð°Ð³Ð¾Ð´Ð°Ñ€Ñ Windows limitations_ - -# FileTransfer - -`FileTransfer`Объект предоÑтавлÑет ÑпоÑоб Ð´Ð»Ñ Ð·Ð°Ð³Ñ€ÑƒÐ·ÐºÐ¸ файлов Ñ Ð¿Ð¾Ð¼Ð¾Ñ‰ÑŒÑŽ неÑкольких чаÑтей запроÑа POST HTTP и Ð´Ð»Ñ Ð·Ð°Ð³Ñ€ÑƒÐ·ÐºÐ¸ файлов, а также. - -## Параметры - -* **OnProgress**: называетÑÑ Ñ `ProgressEvent` вÑÑкий раз, когда новый фрагмент данных передаетÑÑ. *(ФункциÑ)* - -## Методы - -* **добавлено**: отправлÑет файл на Ñервер. - -* **Ñкачать**: Скачать файл Ñ Ñервера. - -* **прервать**: прерывает передачу в прогреÑÑ. - -## загрузить - -**Параметры**: - -* **fileURL**: файловой ÑиÑтемы URL-адреÑ, предÑтавлÑющий файл на уÑтройÑтве. Ð”Ð»Ñ Ð¾Ð±Ñ€Ð°Ñ‚Ð½Ð¾Ð¹ ÑовмеÑтимоÑти, Ñто также может быть полный путь к файлу на уÑтройÑтве. (См. [обратной ÑовмеÑтимоÑти отмечает] ниже) - -* **Ñервер**: URL-Ð°Ð´Ñ€ÐµÑ Ñервера, чтобы получить файл, как закодированные`encodeURI()`. - -* **successCallback**: обратного вызова, передаваемого `Metadata` объект. *(ФункциÑ)* - -* **errorCallback**: обратного вызова, который выполнÑетÑÑ Ð² Ñлучае Ð¿Ð¾Ð»ÑƒÑ‡ÐµÐ½Ð¸Ñ Ð¾ÑˆÐ¸Ð±ÐºÐ¸ `Metadata` . Вызываемый Ñ `FileTransferError` объект. *(ФункциÑ)* - -* **опции**: необÑзательные параметры *(объект)*. ДопуÑтимые ключи: - - * **fileKey**: Ð¸Ð¼Ñ Ñлемента form. По умолчанию `file` . (DOMString) - * **Ð¸Ð¼Ñ Ñ„Ð°Ð¹Ð»Ð°**: Ð¸Ð¼Ñ Ñ„Ð°Ð¹Ð»Ð° Ð´Ð»Ñ Ð¸ÑÐ¿Ð¾Ð»ÑŒÐ·Ð¾Ð²Ð°Ð½Ð¸Ñ Ð¿Ñ€Ð¸ Ñохранении файла на Ñервере. По умолчанию `image.jpg` . (DOMString) - * **mimeType**: mime-тип данных Ð´Ð»Ñ Ð·Ð°Ð³Ñ€ÑƒÐ·ÐºÐ¸. По умолчанию `image/jpeg` . (DOMString) - * **params**: набор пар дополнительный ключ/значение Ð´Ð»Ñ Ð¿ÐµÑ€ÐµÐ´Ð°Ñ‡Ð¸ в HTTP-запроÑе. (Объект) - * **chunkedMode**: Ñледует ли загружать данные в фрагментарноÑти потоковом режиме. По умолчанию `true` . (ЛогичеÑкое значение) - * **заголовки**: Карта значений заголовок Ð¸Ð¼Ñ Ð·Ð°Ð³Ð¾Ð»Ð¾Ð²ÐºÐ°. ИÑпользуйте маÑÑив Ð´Ð»Ñ ÑƒÐºÐ°Ð·Ð°Ð½Ð¸Ñ Ð±Ð¾Ð»ÐµÐµ одного значениÑ. (Объект) - -* **trustAllHosts**: необÑзательный параметр, по умолчанию `false` . ЕÑли значение `true` , она принимает вÑе Ñертификаты безопаÑноÑти. Это полезно, поÑкольку Android отвергает ÑамозаверÑющие Ñертификаты. Ðе рекомендуетÑÑ Ð´Ð»Ñ Ð¸ÑÐ¿Ð¾Ð»ÑŒÐ·Ð¾Ð²Ð°Ð½Ð¸Ñ Ð² производÑтве. ПоддерживаетÑÑ Ð½Ð° Android и iOS. *(логичеÑкое значение)* - -### Пример - - // !! Assumes variable fileURL contains a valid URL to a text file on the device, - // for example, cdvfile://localhost/persistent/path/to/file.txt - - var win = function (r) { - console.log("Code = " + r.responseCode); - console.log("Response = " + r.response); - console.log("Sent = " + r.bytesSent); - } - - var fail = function (error) { - alert("An error has occurred: Code = " + error.code); - console.log("upload error source " + error.source); - console.log("upload error target " + error.target); - } - - var options = new FileUploadOptions(); - options.fileKey = "file"; - options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1); - options.mimeType = "text/plain"; - - var params = {}; - params.value1 = "test"; - params.value2 = "param"; - - options.params = params; - - var ft = new FileTransfer(); - ft.upload(fileURL, encodeURI("http://some.server.com/upload.php"), win, fail, options); - - -### Пример Ñ Ð·Ð°Ð³Ñ€ÑƒÐ¶Ð°Ñ‚ÑŒ заголовки и ÑÐ¾Ð±Ñ‹Ñ‚Ð¸Ñ Progress (Android и iOS только) - - function win(r) { - console.log("Code = " + r.responseCode); - console.log("Response = " + r.response); - console.log("Sent = " + r.bytesSent); - } - - function fail(error) { - alert("An error has occurred: Code = " + error.code); - console.log("upload error source " + error.source); - console.log("upload error target " + error.target); - } - - var uri = encodeURI("http://some.server.com/upload.php"); - - var options = new FileUploadOptions(); - options.fileKey="file"; - options.fileName=fileURL.substr(fileURL.lastIndexOf('/')+1); - options.mimeType="text/plain"; - - var headers={'headerParam':'headerValue'}; - - options.headers = headers; - - var ft = new FileTransfer(); - ft.onprogress = function(progressEvent) { - if (progressEvent.lengthComputable) { - loadingStatus.setPercentage(progressEvent.loaded / progressEvent.total); - } else { - loadingStatus.increment(); - } - }; - ft.upload(fileURL, uri, win, fail, options); - - -## FileUploadResult - -Объект `FileUploadResult` передаетÑÑ Ð½Ð° уÑпех обратного вызова метода `upload()` объекта `FileTransfer`. - -### Параметры - -* **bytesSent**: количеÑтво байт, отправленных на Ñервер как чаÑÑ‚ÑŒ загрузки. (длиннаÑ) - -* **responseCode**: код ответа HTTP, возвращаемых Ñервером. (длиннаÑ) - -* **ответ**: ответ HTTP, возвращаемых Ñервером. (DOMString) - -* **заголовки**: заголовки ответов HTTP-Ñервером. (Объект) - - * Ð’ наÑтоÑщее Ð²Ñ€ÐµÐ¼Ñ Ð¿Ð¾Ð´Ð´ÐµÑ€Ð¶Ð¸Ð²Ð°ÐµÑ‚ÑÑ Ñ‚Ð¾Ð»ÑŒÐºÐ¾ Ð´Ð»Ñ iOS. - -### ОÑобенноÑти iOS - -* Ðе поддерживает `responseCode` или`bytesSent`. - -## Скачать - -**Параметры**: - -* **иÑточник**: URL-Ð°Ð´Ñ€ÐµÑ Ñервера Ð´Ð»Ñ Ð·Ð°Ð³Ñ€ÑƒÐ·ÐºÐ¸ файла, как закодированные`encodeURI()`. - -* **Цель**: файловой ÑиÑтемы URL-адреÑ, предÑтавлÑющий файл на уÑтройÑтве. Ð”Ð»Ñ Ð¾Ð±Ñ€Ð°Ñ‚Ð½Ð¾Ð¹ ÑовмеÑтимоÑти, Ñто также может быть полный путь к файлу на уÑтройÑтве. (См. [обратной ÑовмеÑтимоÑти отмечает] ниже) - -* **successCallback**: обратного вызова, передаваемого `FileEntry` объект. *(ФункциÑ)* - -* **errorCallback**: обратного вызова, который выполнÑетÑÑ, еÑли возникает ошибка при получении `Metadata` . Вызываемый Ñ `FileTransferError` объект. *(ФункциÑ)* - -* **trustAllHosts**: необÑзательный параметр, по умолчанию `false` . ЕÑли значение `true` , она принимает вÑе Ñертификаты безопаÑноÑти. Это полезно, потому что Android отвергает ÑамозаверÑющие Ñертификаты. Ðе рекомендуетÑÑ Ð´Ð»Ñ Ð¸ÑÐ¿Ð¾Ð»ÑŒÐ·Ð¾Ð²Ð°Ð½Ð¸Ñ Ð² производÑтве. ПоддерживаетÑÑ Ð½Ð° Android и iOS. *(логичеÑкое значение)* - -* **опции**: необÑзательные параметры, в наÑтоÑщее Ð²Ñ€ÐµÐ¼Ñ Ñ‚Ð¾Ð»ÑŒÐºÐ¾ поддерживает заголовки (например авторизации (Ð±Ð°Ð·Ð¾Ð²Ð°Ñ Ð°ÑƒÑ‚ÐµÐ½Ñ‚Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸Ñ) и Ñ‚.д.). - -### Пример - - // !! Assumes variable fileURL contains a valid URL to a path on the device, - // for example, cdvfile://localhost/persistent/path/to/downloads/ - - var fileTransfer = new FileTransfer(); - var uri = encodeURI("http://some.server.com/download.php"); - - fileTransfer.download( - uri, - fileURL, - function(entry) { - console.log("download complete: " + entry.toURL()); - }, - function(error) { - console.log("download error source " + error.source); - console.log("download error target " + error.target); - console.log("upload error code" + error.code); - }, - false, - { - headers: { - "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA==" - } - } - ); - - -## прервать - -Прерывает передачу в прогреÑÑ. Onerror обратного вызова передаетÑÑ Ð¾Ð±ÑŠÐµÐºÑ‚ FileTransferError, который имеет код ошибки FileTransferError.ABORT_ERR. - -### Пример - - // !! Assumes variable fileURL contains a valid URL to a text file on the device, - // for example, cdvfile://localhost/persistent/path/to/file.txt - - var win = function(r) { - console.log("Should not be called."); - } - - var fail = function(error) { - // error.code == FileTransferError.ABORT_ERR - alert("An error has occurred: Code = " + error.code); - console.log("upload error source " + error.source); - console.log("upload error target " + error.target); - } - - var options = new FileUploadOptions(); - options.fileKey="file"; - options.fileName="myphoto.jpg"; - options.mimeType="image/jpeg"; - - var ft = new FileTransfer(); - ft.upload(fileURL, encodeURI("http://some.server.com/upload.php"), win, fail, options); - ft.abort(); - - -## FileTransferError - -A `FileTransferError` при ошибке обратного вызова передаетÑÑ Ð¾Ð±ÑŠÐµÐºÑ‚, при возникновении ошибки. - -### Параметры - -* **код**: один из кодов Ñтандартных ошибок, перечиÑленные ниже. (ЧиÑло) - -* **иÑточник**: URL-Ð°Ð´Ñ€ÐµÑ Ð¸Ñточника. (Строка) - -* **Цель**: URL-Ð°Ð´Ñ€ÐµÑ Ðº целевому объекту. (Строка) - -* **http_status**: код ÑоÑтоÑÐ½Ð¸Ñ HTTP. Этот атрибут доÑтупен только при код ответа от HTTP-ÑоединениÑ. (ЧиÑло) - -* **иÑключение**: либо e.getMessage или e.toString (Ñтрока) - -### КонÑтанты - -* 1 = `FileTransferError.FILE_NOT_FOUND_ERR` -* 2 = `FileTransferError.INVALID_URL_ERR` -* 3 = `FileTransferError.CONNECTION_ERR` -* 4 = `FileTransferError.ABORT_ERR` -* 5 = `FileTransferError.NOT_MODIFIED_ERR` - -## Обратной ÑовмеÑтимоÑти отмечает - -Предыдущие верÑии Ñтого плагина будет принимать только уÑтройÑтва ÐбÑолют файлам как иÑточник Ð´Ð»Ñ Ð·Ð°ÐºÐ°Ñ‡ÐºÐ¸, или как целевых Ð´Ð»Ñ Ð·Ð°Ð³Ñ€ÑƒÐ·Ð¾Ðº. Обычно Ñти пути бы формы - - /var/mobile/Applications//Documents/path/to/file (iOS) - /storage/emulated/0/path/to/file (Android) - - -Ð”Ð»Ñ Ð¾Ð±Ñ€Ð°Ñ‚Ð½Ð¾Ð¹ ÑовмеÑтимоÑти, по-прежнему принимаютÑÑ Ñти пути, и еÑли ваше приложение зарегиÑтрировано пути как в поÑтоÑнное хранилище, то они могут продолжать иÑпользоватьÑÑ. - -Эти пути ранее были видны в `fullPath` ÑвойÑтва `FileEntry` и `DirectoryEntry` объекты, возвращаемые файл плагина. Ðовые верÑии файла плагина, однако, не подвергать Ñти пути в JavaScript. - -ЕÑли вы переходите на новый (1.0.0 или новее) верÑию файла и вы ранее иÑпользовали `entry.fullPath` в качеÑтве аргументов `download()` или `upload()` , то вам необходимо будет изменить код Ð´Ð»Ñ Ð¸ÑÐ¿Ð¾Ð»ÑŒÐ·Ð¾Ð²Ð°Ð½Ð¸Ñ Ñ„Ð°Ð¹Ð»Ð¾Ð²Ð¾Ð¹ ÑиÑтемы URL вмеÑто. - -`FileEntry.toURL()`и `DirectoryEntry.toURL()` возвращает URL-Ð°Ð´Ñ€ÐµÑ Ñ„Ð¾Ñ€Ð¼Ñ‹ файловой ÑиÑтемы - - cdvfile://localhost/persistent/path/to/file - - -которые могут быть иÑпользованы вмеÑто абÑолютного пути в обоих `download()` и `upload()` методы. diff --git a/plugins/cordova-plugin-file-transfer/doc/zh/README.md b/plugins/cordova-plugin-file-transfer/doc/zh/README.md deleted file mode 100644 index 5399b04..0000000 --- a/plugins/cordova-plugin-file-transfer/doc/zh/README.md +++ /dev/null @@ -1,311 +0,0 @@ - - -# cordova-plugin-file-transfer - -[![Build Status](https://travis-ci.org/apache/cordova-plugin-file-transfer.svg)](https://travis-ci.org/apache/cordova-plugin-file-transfer) - -外掛程å¼æª”: - -這個外掛程å¼å…許你上傳和下載檔案。 - -這個外掛程å¼å®šç¾©å…¨åŸŸ `FileTransfer`,`FileUploadOptions` 的建構函å¼ã€‚ - -雖然在全çƒç¯„åœå…§ï¼Œä»–們ä¸å¯ç”¨ç›´åˆ° `deviceready` 事件之後。 - - document.addEventListener("deviceready", onDeviceReady, false); - function onDeviceReady() { - console.log(FileTransfer); - } - - -## å®‰è£ - - cordova plugin add cordova-plugin-file-transfer - - -## 支æ´çš„平臺 - - * 亞馬éœç« OS - * Android 系統 - * 黑莓 10 - * ç€è¦½å™¨ - * ç«ç‹ç€è¦½å™¨çš„作業系統 * * - * iOS - * Windows Phone 7 å’Œ 8 * - * Windows 8 - * Windows - -\ **ä¸æ”¯æ´`onprogress`也`abort()` * - -\ * **ä¸æ”¯æ´`onprogress` * - -# 檔案傳輸 - -`FileTransfer`物件æ供上傳檔使用 HTTP 多部分è·ä½æˆ–付諸表決的請求,並將檔以åŠä¸‹è¼‰çš„æ–¹å¼ã€‚ - -## 屬性 - - * **onprogress**: 使用調用 `ProgressEvent` æ¯ç•¶ä¸€å¡Šæ–°çš„資料傳輸。*(函數)* - -## 方法 - - * **upload**: 將檔發é€åˆ°ä¼ºæœå™¨ã€‚ - - * **download**: 從伺æœå™¨ä¸Šä¸‹è¼‰æª”案。 - - * **abort**: 中止正在進行轉讓。 - -## upload - -**åƒæ•¸**: - - * **fileURL**: 表示檔在設備上的檔案系統 URL。 為å‘後相容性,這也å¯ä»¥å°‡è¨­å‚™ä¸Šçš„檔的完整路徑。 (請åƒè¦‹ [å‘後相容性注æ„到] 下é¢) - - * **server**: 伺æœå™¨ä»¥æŽ¥æ”¶è©²æª”,由編碼的 URL`encodeURI()`. - - * **successCallback**: 一個通éŽä¸€å€‹ `FileUploadResult` 物件的回檔。*(函數)* - - * **errorCallback**: 如果發生錯誤,檢索 `FileUploadResult` 執行一個回檔。使用 `FileTransferError` 物件調用。*(函數)* - - * **options**: å¯é¸åƒæ•¸*(物件)*。有效的金鑰: - - * **fileKey**: 表單元素的å稱。é è¨­å€¼ç‚º `file` 。() DOMString - * **fileName**: è¦ä¿å­˜åœ¨ä¼ºæœå™¨ä¸Šçš„檔時使用的檔案å稱。é è¨­å€¼ç‚º `image.jpg` 。() DOMString - * **httpMethod**: HTTP 方法使用-`PUT` 或 `POST`。é è¨­å€¼ç‚º `POST`。() DOMString - * **mimeType**: è¦ä¸Šè¼‰çš„資料的 mime 類型。é è¨­è¨­ç½®ç‚º `image/jpeg`。() DOMString - * **params**: 一組è¦åœ¨ HTTP è¦æ±‚中傳éžçš„å¯é¸çš„éµå€¼å°ã€‚(物件) - * **chunkedMode**: 是å¦è¦åˆ†å¡Šçš„æµå¼è™•ç†æ¨¡å¼ä¸­çš„資料上載。é è¨­å€¼ç‚º `true`。(布林值) - * **headers**: 地圖的標頭å稱/標頭值。 使用陣列來指定多個值。 IOS〠FireOS,和安å“系統,如果已命å的內容類型標頭存在,多部分表單資料ä¸è¢«ä½¿ç”¨ã€‚ (Object) - * **httpMethod**: HTTP 方法,例如使用張貼或放。 é è¨­ç‚º`開機自檢`。() DOMString - - * **trustAllHosts**: å¯é¸åƒæ•¸ï¼Œé è¨­å€¼ç‚º `false` 。 如果設置為 `true` ,它å¯ä»¥æŽ¥å—的所有安全證書。 這是有用的因為 android 系統拒絕自簽å的安全證書。 ä¸å»ºè­°ä¾›ç”Ÿç”¢ä½¿ç”¨ã€‚ 在 Android å’Œ iOS 上å—支æ´ã€‚ *(布林值)* - -### 示例 - - // !! Assumes variable fileURL contains a valid URL to a text file on the device, - // for example, cdvfile://localhost/persistent/path/to/file.txt - - var win = function (r) { - console.log("Code = " + r.responseCode); - console.log("Response = " + r.response); - console.log("Sent = " + r.bytesSent); - } - - var fail = function (error) { - alert("An error has occurred: Code = " + error.code); - console.log("upload error source " + error.source); - console.log("upload error target " + error.target); - } - - var options = new FileUploadOptions(); - options.fileKey = "file"; - options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1); - options.mimeType = "text/plain"; - - var params = {}; - params.value1 = "test"; - params.value2 = "param"; - - options.params = params; - - var ft = new FileTransfer(); - ft.upload(fileURL, encodeURI("http://some.server.com/upload.php"), win, fail, options); - - -### 與上傳的標頭和進度事件 (Android å’Œ iOS åªï¼‰ 的示例 - - function win(r) { - console.log("Code = " + r.responseCode); - console.log("Response = " + r.response); - console.log("Sent = " + r.bytesSent); - } - - function fail(error) { - alert("An error has occurred: Code = " + error.code); - console.log("upload error source " + error.source); - console.log("upload error target " + error.target); - } - - var uri = encodeURI("http://some.server.com/upload.php"); - - var options = new FileUploadOptions(); - options.fileKey="file"; - options.fileName=fileURL.substr(fileURL.lastIndexOf('/')+1); - options.mimeType="text/plain"; - - var headers={'headerParam':'headerValue'}; - - options.headers = headers; - - var ft = new FileTransfer(); - ft.onprogress = function(progressEvent) { - if (progressEvent.lengthComputable) { - loadingStatus.setPercentage(progressEvent.loaded / progressEvent.total); - } else { - loadingStatus.increment(); - } - }; - ft.upload(fileURL, uri, win, fail, options); - - -## FileUploadResult - -`FileUploadResult` 物件將傳éžçµ¦è©² `檔案傳輸` 物件的 `upload()` 方法的æˆåŠŸå›žæª”。 - -### 屬性 - - * **bytesSent**: 作為上載的一部分發é€åˆ°ä¼ºæœå™¨çš„ä½å…ƒçµ„數。(é•·) - - * **responseCode**: 由伺æœå™¨è¿”回的 HTTP 回應代碼。(é•·) - - * **response**: 由伺æœå™¨è¿”回的 HTTP 回應。() DOMString - - * **headers**: 由伺æœå™¨çš„ HTTP 回應標頭。(物件) - - * ç›®å‰æ”¯æ´çš„ iOS åªã€‚ - -### iOS 的怪癖 - - * ä¸æ”¯æ´ `responseCode` 或`bytesSent`. - -## download - -**åƒæ•¸**: - - * **source**: è¦ä¸‹è¼‰çš„檔,如由編碼的伺æœå™¨çš„ URL`encodeURI()`. - - * **target**: 表示檔在設備上的檔案系統 url。 為å‘後相容性,這也å¯ä»¥å°‡è¨­å‚™ä¸Šçš„檔的完整路徑。 (請åƒè¦‹ [å‘後相容性注æ„到] 下é¢) - - * **successCallback**: 傳éžä¸€å€‹å›žæª” `FileEntry` 物件。*(函數)* - - * **errorCallback**: 如果檢索 `FileEntry` 時發生錯誤,則執行一個回檔。使用 `FileTransferError` 物件調用。*(函數)* - - * **trustAllHosts**: å¯é¸åƒæ•¸ï¼Œé è¨­å€¼ç‚º `false` 。 如果設置為 `true` ,它å¯ä»¥æŽ¥å—的所有安全證書。 這是有用的因為 Android 拒絕自行簽署å¼å®‰å…¨è­‰æ›¸ã€‚ ä¸å»ºè­°ä¾›ç”Ÿç”¢ä½¿ç”¨ã€‚ 在 Android å’Œ iOS 上å—支æ´ã€‚ *(布林值)* - - * **options**: å¯é¸åƒæ•¸ï¼Œç›®å‰åªæ”¯æ´æ¨™é¡Œ (如授權 (基本驗證) 等)。 - -### 示例 - - // !! Assumes variable fileURL contains a valid URL to a path on the device, - // for example, cdvfile://localhost/persistent/path/to/downloads/ - - var fileTransfer = new FileTransfer(); - var uri = encodeURI("http://some.server.com/download.php"); - - fileTransfer.download( - uri, - fileURL, - function(entry) { - console.log("download complete: " + entry.toURL()); - }, - function(error) { - console.log("download error source " + error.source); - console.log("download error target " + error.target); - console.log("upload error code" + error.code); - }, - false, - { - headers: { - "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA==" - } - } - ); - - -### WP8 的怪癖 - - * 下載請求由本機實ç¾è¢«ç·©å­˜ã€‚è‹¥è¦é¿å…緩存,傳éž`如果修改自`郵件頭以下載方法。 - -## abort - -中止正在進行轉讓。Onerror 回檔傳éžä¸€å€‹ FileTransferError 物件具有 FileTransferError.ABORT_ERR 錯誤代碼。 - -### 示例 - - // !! Assumes variable fileURL contains a valid URL to a text file on the device, - // for example, cdvfile://localhost/persistent/path/to/file.txt - - var win = function(r) { - console.log("Should not be called."); - } - - var fail = function(error) { - // error.code == FileTransferError.ABORT_ERR - alert("An error has occurred: Code = " + error.code); - console.log("upload error source " + error.source); - console.log("upload error target " + error.target); - } - - var options = new FileUploadOptions(); - options.fileKey="file"; - options.fileName="myphoto.jpg"; - options.mimeType="image/jpeg"; - - var ft = new FileTransfer(); - ft.upload(fileURL, encodeURI("http://some.server.com/upload.php"), win, fail, options); - ft.abort(); - - -## FileTransferError - -當發生錯誤時,`FileTransferError` 物件將傳éžçµ¦éŒ¯èª¤å›žæª”。 - -### 屬性 - - * **code**: 下é¢åˆ—出的é å®šç¾©çš„錯誤代碼之一。(人數) - - * **source**: æºçš„ URL。(字串) - - * **target**: 到目標 URL。(字串) - - * **HTTP_status**: HTTP 狀態碼。從 HTTP 連接收到一個回應代碼時,此屬性æ‰å¯ç”¨ã€‚(人數) - - * **body**回應正文。此屬性åªèƒ½æ˜¯å¯ç”¨çš„當該 HTTP 連接收到答覆。(字串) - - * **exception**: è¦éº¼ e.getMessage 或 e.toString (字串) - -### å¸¸é‡ - - * 1 = `FileTransferError.FILE_NOT_FOUND_ERR` - * 2 = `FileTransferError.INVALID_URL_ERR` - * 3 = `FileTransferError.CONNECTION_ERR` - * 4 = `FileTransferError.ABORT_ERR` - * 5 = `FileTransferError.NOT_MODIFIED_ERR` - -## å‘後相容性注æ„到 - -以å‰ç‰ˆæœ¬çš„這個外掛程å¼æ‰æœƒæŽ¥å—設備-絕å°æª”路徑作為æºå°æ–¼ä¸Šè¼‰ï¼Œæˆ–用於下載的目標。這些路徑通常會在表單 - - /var/mobile/Applications//Documents/path/to/file (iOS) - /storage/emulated/0/path/to/file (Android) - - -為å‘後相容性,這些路徑ä»æœƒè¢«æŽ¥å—,和如果您的應用程å¼å·²éŒ„å¾—åƒé€™äº›åœ¨æŒä¹…性存儲的路徑,然後他們å¯ä»¥ç¹¼çºŒä½¿ç”¨ã€‚ - -這些路徑被以å‰æš´éœ²åœ¨ `FileEntry` 和由檔外掛程å¼è¿”回的 `DirectoryEntry` 物件的 `fullPath` 屬性中。 新版本的檔的外掛程å¼ï¼Œä½†æ˜¯ï¼Œä¸å†å…¬é–‹é€™äº› JavaScript 的路徑。 - -如果您è¦å‡ç´šåˆ°æ–° (1.0.0 或更高版本) 版本的檔,和你以å‰ä¸€ç›´åœ¨ä½¿ç”¨ `entry.fullPath` 作為åƒæ•¸åˆ° `download()` 或 `upload()`,那麼你將需è¦æ›´æ”¹ä»£ç¢¼ä»¥ä½¿ç”¨æª”案系統的 Url 來代替。 - -`FileEntry.toURL()` å’Œ `DirectoryEntry.toURL()` 返回的表單檔案 URL - - cdvfile://localhost/persistent/path/to/file - - -它å¯ä»¥ç”¨åœ¨ `download()` å’Œ `upload()` 兩種方法中的絕å°æª”路徑ä½ç½®ã€‚ \ No newline at end of file diff --git a/plugins/cordova-plugin-file-transfer/doc/zh/index.md b/plugins/cordova-plugin-file-transfer/doc/zh/index.md deleted file mode 100644 index b3af1eb..0000000 --- a/plugins/cordova-plugin-file-transfer/doc/zh/index.md +++ /dev/null @@ -1,302 +0,0 @@ - - -# cordova-plugin-file-transfer - -這個外掛程å¼å…許你上傳和下載檔案。 - -這個外掛程å¼å®šç¾©å…¨åŸŸ `FileTransfer`,`FileUploadOptions` 的建構函å¼ã€‚ - -雖然在全çƒç¯„åœå…§ï¼Œä»–們ä¸å¯ç”¨ç›´åˆ° `deviceready` 事件之後。 - - document.addEventListener("deviceready", onDeviceReady, false); - function onDeviceReady() { - console.log(FileTransfer); - } - - -## å®‰è£ - - cordova plugin add cordova-plugin-file-transfer - - -## 支æ´çš„平臺 - -* 亞馬éœç« OS -* Android 系統 -* 黑莓 10 -* ç€è¦½å™¨ -* ç«ç‹ç€è¦½å™¨çš„作業系統 * * -* iOS -* Windows Phone 7 å’Œ 8 * -* Windows 8 -* Windows - -* *ä¸æ”¯æ´ `onprogress` 也 `abort()`* - -* * *ä¸æ”¯æ´ `onprogress`* - -# FileTransfer - -`FileTransfer` 物件æ供一種使用 HTTP 多部分 POST 請求的檔上傳,下載檔案以åŠæ–¹å¼ã€‚ - -## 屬性 - -* **onprogress**: 使用調用 `ProgressEvent` æ¯ç•¶ä¸€å¡Šæ–°çš„資料傳輸。*(函數)* - -## 方法 - -* **upload**: 將檔發é€åˆ°ä¼ºæœå™¨ã€‚ - -* **download**: 從伺æœå™¨ä¸Šä¸‹è¼‰æª”案。 - -* **abort**: 中止正在進行轉讓。 - -## upload - -**åƒæ•¸**: - -* **fileURL**: 表示檔在設備上的檔案系統 URL。 為å‘後相容性,這也å¯ä»¥å°‡è¨­å‚™ä¸Šçš„檔的完整路徑。 (請åƒè¦‹ [å‘後相容性注æ„到] 下é¢) - -* **server**: 伺æœå™¨ä»¥æŽ¥æ”¶è©²æª”,由編碼的 URL`encodeURI()`. - -* **successCallback**: 一個通éŽä¸€å€‹ `FileUploadResult` 物件的回檔。*(函數)* - -* **errorCallback**: 如果發生錯誤,檢索 `FileUploadResult` 執行一個回檔。使用 `FileTransferError` 物件調用。*(函數)* - -* **options**: å¯é¸åƒæ•¸*(物件)*。有效的金鑰: - - * **fileKey**: 表單元素的å稱。é è¨­å€¼ç‚º `file` 。() DOMString - * **fileName**: è¦ä¿å­˜åœ¨ä¼ºæœå™¨ä¸Šçš„檔時使用的檔案å稱。é è¨­å€¼ç‚º `image.jpg` 。() DOMString - * **httpMethod**: HTTP 方法使用-`PUT` 或 `POST`。é è¨­å€¼ç‚º `POST`。() DOMString - * **mimeType**: è¦ä¸Šè¼‰çš„資料的 mime 類型。é è¨­è¨­ç½®ç‚º `image/jpeg`。() DOMString - * **params**: 一組è¦åœ¨ HTTP è¦æ±‚中傳éžçš„å¯é¸çš„éµå€¼å°ã€‚(物件) - * **chunkedMode**: 是å¦è¦åˆ†å¡Šçš„æµå¼è™•ç†æ¨¡å¼ä¸­çš„資料上載。é è¨­å€¼ç‚º `true`。(布林值) - * **headers**: 地圖的標頭å稱/標頭值。使用陣列來指定多個值。(物件) - -* **trustAllHosts**: å¯é¸åƒæ•¸ï¼Œé è¨­å€¼ç‚º `false` 。 如果設置為 `true` ,它接å—的所有安全證書。 這是有用的因為 android 系統拒絕自簽å的安全證書。 ä¸å»ºè­°ä¾›ç”Ÿç”¢ä½¿ç”¨ã€‚ æ”¯æ´ Android å’Œ iOS。 *(布林值)* - -### 示例 - - // !! Assumes variable fileURL contains a valid URL to a text file on the device, - // for example, cdvfile://localhost/persistent/path/to/file.txt - - var win = function (r) { - console.log("Code = " + r.responseCode); - console.log("Response = " + r.response); - console.log("Sent = " + r.bytesSent); - } - - var fail = function (error) { - alert("An error has occurred: Code = " + error.code); - console.log("upload error source " + error.source); - console.log("upload error target " + error.target); - } - - var options = new FileUploadOptions(); - options.fileKey = "file"; - options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1); - options.mimeType = "text/plain"; - - var params = {}; - params.value1 = "test"; - params.value2 = "param"; - - options.params = params; - - var ft = new FileTransfer(); - ft.upload(fileURL, encodeURI("http://some.server.com/upload.php"), win, fail, options); - - -### 與上傳的標頭和進度事件 (Android å’Œ iOS åªï¼‰ 的示例 - - function win(r) { - console.log("Code = " + r.responseCode); - console.log("Response = " + r.response); - console.log("Sent = " + r.bytesSent); - } - - function fail(error) { - alert("An error has occurred: Code = " + error.code); - console.log("upload error source " + error.source); - console.log("upload error target " + error.target); - } - - var uri = encodeURI("http://some.server.com/upload.php"); - - var options = new FileUploadOptions(); - options.fileKey="file"; - options.fileName=fileURL.substr(fileURL.lastIndexOf('/')+1); - options.mimeType="text/plain"; - - var headers={'headerParam':'headerValue'}; - - options.headers = headers; - - var ft = new FileTransfer(); - ft.onprogress = function(progressEvent) { - if (progressEvent.lengthComputable) { - loadingStatus.setPercentage(progressEvent.loaded / progressEvent.total); - } else { - loadingStatus.increment(); - } - }; - ft.upload(fileURL, uri, win, fail, options); - - -## FileUploadResult - -`FileUploadResult` 物件將傳éžçµ¦è©² `檔案傳輸` 物件的 `upload()` 方法的æˆåŠŸå›žæª”。 - -### 屬性 - -* **bytesSent**: 作為上載的一部分發é€åˆ°ä¼ºæœå™¨çš„ä½å…ƒçµ„數。(é•·) - -* **responseCode**: 由伺æœå™¨è¿”回的 HTTP 回應代碼。(é•·) - -* **response**: 由伺æœå™¨è¿”回的 HTTP 回應。() DOMString - -* **headers**: 由伺æœå™¨çš„ HTTP 回應標頭。(物件) - - * ç›®å‰æ”¯æ´çš„ iOS åªã€‚ - -### iOS 的怪癖 - -* ä¸æ”¯æ´ `responseCode` 或`bytesSent`. - -## download - -**åƒæ•¸**: - -* **source**: è¦ä¸‹è¼‰çš„檔,如由編碼的伺æœå™¨çš„ URL`encodeURI()`. - -* **target**: 表示檔在設備上的檔案系統 url。 為å‘後相容性,這也å¯ä»¥å°‡è¨­å‚™ä¸Šçš„檔的完整路徑。 (請åƒè¦‹ [å‘後相容性注æ„到] 下é¢) - -* **successCallback**: 傳éžä¸€å€‹å›žæª” `FileEntry` 物件。*(函數)* - -* **errorCallback**: 如果檢索 `FileEntry` 時發生錯誤,則執行一個回檔。使用 `FileTransferError` 物件調用。*(函數)* - -* **trustAllHosts**: å¯é¸åƒæ•¸ï¼Œé è¨­å€¼ç‚º `false` 。 如果設置為 `true` ,它å¯ä»¥æŽ¥å—的所有安全證書。 這是有用的因為 Android 拒絕自行簽署å¼å®‰å…¨è­‰æ›¸ã€‚ ä¸å»ºè­°ä¾›ç”Ÿç”¢ä½¿ç”¨ã€‚ 在 Android å’Œ iOS 上å—支æ´ã€‚ *(布林值)* - -* **options**: å¯é¸åƒæ•¸ï¼Œç›®å‰åªæ”¯æ´æ¨™é¡Œ (如授權 (基本驗證) 等)。 - -### 示例 - - // !! Assumes variable fileURL contains a valid URL to a path on the device, - // for example, cdvfile://localhost/persistent/path/to/downloads/ - - var fileTransfer = new FileTransfer(); - var uri = encodeURI("http://some.server.com/download.php"); - - fileTransfer.download( - uri, - fileURL, - function(entry) { - console.log("download complete: " + entry.toURL()); - }, - function(error) { - console.log("download error source " + error.source); - console.log("download error target " + error.target); - console.log("upload error code" + error.code); - }, - false, - { - headers: { - "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA==" - } - } - ); - - -## abort - -中止正在進行轉讓。Onerror 回檔傳éžä¸€å€‹ FileTransferError 物件具有 FileTransferError.ABORT_ERR 錯誤代碼。 - -### 示例 - - // !! Assumes variable fileURL contains a valid URL to a text file on the device, - // for example, cdvfile://localhost/persistent/path/to/file.txt - - var win = function(r) { - console.log("Should not be called."); - } - - var fail = function(error) { - // error.code == FileTransferError.ABORT_ERR - alert("An error has occurred: Code = " + error.code); - console.log("upload error source " + error.source); - console.log("upload error target " + error.target); - } - - var options = new FileUploadOptions(); - options.fileKey="file"; - options.fileName="myphoto.jpg"; - options.mimeType="image/jpeg"; - - var ft = new FileTransfer(); - ft.upload(fileURL, encodeURI("http://some.server.com/upload.php"), win, fail, options); - ft.abort(); - - -## FileTransferError - -當發生錯誤時,`FileTransferError` 物件將傳éžçµ¦éŒ¯èª¤å›žæª”。 - -### 屬性 - -* **code**: 下é¢åˆ—出的é å®šç¾©çš„錯誤代碼之一。(人數) - -* **source**: æºçš„ URL。(字串) - -* **target**: 到目標 URL。(字串) - -* **HTTP_status**: HTTP 狀態碼。從 HTTP 連接收到一個回應代碼時,此屬性æ‰å¯ç”¨ã€‚(人數) - -* **body**回應正文。此屬性åªèƒ½æ˜¯å¯ç”¨çš„當該 HTTP 連接收到答覆。(字串) - -* **exception**: è¦éº¼ e.getMessage 或 e.toString (字串) - -### å¸¸é‡ - -* 1 = `FileTransferError.FILE_NOT_FOUND_ERR` -* 2 = `FileTransferError.INVALID_URL_ERR` -* 3 = `FileTransferError.CONNECTION_ERR` -* 4 = `FileTransferError.ABORT_ERR` -* 5 = `FileTransferError.NOT_MODIFIED_ERR` - -## å‘後相容性注æ„到 - -以å‰ç‰ˆæœ¬çš„這個外掛程å¼æ‰æœƒæŽ¥å—設備-絕å°æª”路徑作為æºå°æ–¼ä¸Šè¼‰ï¼Œæˆ–用於下載的目標。這些路徑通常會在表單 - - /var/mobile/Applications//Documents/path/to/file (iOS) - /storage/emulated/0/path/to/file (Android) - - -為å‘後相容性,這些路徑ä»æœƒè¢«æŽ¥å—,和如果您的應用程å¼å·²éŒ„å¾—åƒé€™äº›åœ¨æŒä¹…性存儲的路徑,然後他們å¯ä»¥ç¹¼çºŒä½¿ç”¨ã€‚ - -這些路徑被以å‰æš´éœ²åœ¨ `FileEntry` 和由檔外掛程å¼è¿”回的 `DirectoryEntry` 物件的 `fullPath` 屬性中。 新版本的檔的外掛程å¼ï¼Œä½†æ˜¯ï¼Œä¸å†å…¬é–‹é€™äº› JavaScript 的路徑。 - -如果您è¦å‡ç´šåˆ°æ–° (1.0.0 或更高版本) 版本的檔,和你以å‰ä¸€ç›´åœ¨ä½¿ç”¨ `entry.fullPath` 作為åƒæ•¸åˆ° `download()` 或 `upload()`,那麼你將需è¦æ›´æ”¹ä»£ç¢¼ä»¥ä½¿ç”¨æª”案系統的 Url 來代替。 - -`FileEntry.toURL()` å’Œ `DirectoryEntry.toURL()` 返回的表單檔案 URL - - cdvfile://localhost/persistent/path/to/file - - -它å¯ä»¥ç”¨åœ¨ `download()` å’Œ `upload()` 兩種方法中的絕å°æª”路徑ä½ç½®ã€‚ diff --git a/plugins/cordova-plugin-file-transfer/package.json b/plugins/cordova-plugin-file-transfer/package.json deleted file mode 100644 index 2b5a342..0000000 --- a/plugins/cordova-plugin-file-transfer/package.json +++ /dev/null @@ -1,93 +0,0 @@ -{ - "_from": "cordova-plugin-file-transfer@^1.7.1", - "_id": "cordova-plugin-file-transfer@1.7.1", - "_inBundle": false, - "_integrity": "sha1-p12L4uvDu5sjxbG70ZkhTsJnWGs=", - "_location": "/cordova-plugin-file-transfer", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "cordova-plugin-file-transfer@^1.7.1", - "name": "cordova-plugin-file-transfer", - "escapedName": "cordova-plugin-file-transfer", - "rawSpec": "^1.7.1", - "saveSpec": null, - "fetchSpec": "^1.7.1" - }, - "_requiredBy": [ - "#USER", - "/" - ], - "_resolved": "https://registry.npmjs.org/cordova-plugin-file-transfer/-/cordova-plugin-file-transfer-1.7.1.tgz", - "_shasum": "a75d8be2ebc3bb9b23c5b1bbd199214ec267586b", - "_spec": "cordova-plugin-file-transfer@^1.7.1", - "_where": "/home/thrrgilag/workspace/cordova/Goober", - "author": { - "name": "Apache Software Foundation" - }, - "bugs": { - "url": "https://issues.apache.org/jira/browse/CB" - }, - "bundleDependencies": false, - "cordova": { - "id": "cordova-plugin-file-transfer", - "platforms": [ - "android", - "amazon-fireos", - "ubuntu", - "blackberry10", - "ios", - "wp7", - "wp8", - "windows8", - "windows", - "firefoxos", - "browser" - ] - }, - "deprecated": false, - "description": "Cordova File Transfer Plugin", - "devDependencies": { - "jscs": "^2.6.0", - "jshint": "^2.8.0" - }, - "engines": { - "cordovaDependencies": { - "2.0.0": { - "cordova": ">100" - } - } - }, - "homepage": "https://github.com/apache/cordova-plugin-file-transfer#readme", - "keywords": [ - "cordova", - "file", - "transfer", - "ecosystem:cordova", - "cordova-android", - "cordova-amazon-fireos", - "cordova-ubuntu", - "cordova-blackberry10", - "cordova-ios", - "cordova-wp7", - "cordova-wp8", - "cordova-windows8", - "cordova-windows", - "cordova-firefoxos", - "cordova-browser" - ], - "license": "Apache-2.0", - "name": "cordova-plugin-file-transfer", - "repository": { - "type": "git", - "url": "git+https://github.com/apache/cordova-plugin-file-transfer.git" - }, - "scripts": { - "lint": "jshint www && jshint src && jshint tests", - "style": "jscs tests/tests.js", - "test": "npm run lint && npm run style" - }, - "types": "./types/index.d.ts", - "version": "1.7.1" -} diff --git a/plugins/cordova-plugin-file-transfer/plugin.xml b/plugins/cordova-plugin-file-transfer/plugin.xml deleted file mode 100644 index bfacbb1..0000000 --- a/plugins/cordova-plugin-file-transfer/plugin.xml +++ /dev/null @@ -1,170 +0,0 @@ - - - - - File Transfer - Cordova File Transfer Plugin - Apache 2.0 - cordova,file,transfer - https://git-wip-us.apache.org/repos/asf/cordova-plugin-file-transfer.git - https://issues.apache.org/jira/browse/CB/component/12320650 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/plugins/cordova-plugin-file-transfer/src/amazon/FileTransfer.java b/plugins/cordova-plugin-file-transfer/src/amazon/FileTransfer.java deleted file mode 100644 index 1563a39..0000000 --- a/plugins/cordova-plugin-file-transfer/src/amazon/FileTransfer.java +++ /dev/null @@ -1,898 +0,0 @@ -/* - 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.filetransfer; - -import java.io.BufferedReader; -import java.io.ByteArrayOutputStream; -import java.io.Closeable; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FilterInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.UnsupportedEncodingException; -import java.net.HttpURLConnection; -import java.net.URLConnection; -import java.net.URLDecoder; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; -import java.util.HashMap; -import java.util.Iterator; -import java.util.zip.GZIPInputStream; -import java.util.zip.Inflater; - -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.HttpsURLConnection; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSession; -import javax.net.ssl.SSLSocketFactory; -import javax.net.ssl.TrustManager; -import javax.net.ssl.X509TrustManager; - -import org.apache.cordova.Config; -import org.apache.cordova.CallbackContext; -import org.apache.cordova.CordovaPlugin; -import org.apache.cordova.CordovaResourceApi; -import org.apache.cordova.CordovaResourceApi.OpenForReadResult; -import org.apache.cordova.PluginResult; -import org.apache.cordova.file.FileUtils; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import android.net.Uri; -import android.os.Build; -import android.util.Log; -import com.amazon.android.webkit.AmazonCookieManager; - -public class FileTransfer extends CordovaPlugin { - - private static final String LOG_TAG = "FileTransfer"; - private static final String LINE_START = "--"; - private static final String LINE_END = "\r\n"; - private static final String BOUNDARY = "+++++"; - - public static int FILE_NOT_FOUND_ERR = 1; - public static int INVALID_URL_ERR = 2; - public static int CONNECTION_ERR = 3; - public static int ABORTED_ERR = 4; - - private static HashMap activeRequests = new HashMap(); - private static final int MAX_BUFFER_SIZE = 16 * 1024; - - private static final class RequestContext { - String source; - String target; - File targetFile; - CallbackContext callbackContext; - InputStream currentInputStream; - OutputStream currentOutputStream; - boolean aborted; - RequestContext(String source, String target, CallbackContext callbackContext) { - this.source = source; - this.target = target; - this.callbackContext = callbackContext; - } - void sendPluginResult(PluginResult pluginResult) { - synchronized (this) { - if (!aborted) { - callbackContext.sendPluginResult(pluginResult); - } - } - } - } - - /** - * Adds an interface method to an InputStream to return the number of bytes - * read from the raw stream. This is used to track total progress against - * the HTTP Content-Length header value from the server. - */ - private static abstract class TrackingInputStream extends FilterInputStream { - public TrackingInputStream(final InputStream in) { - super(in); - } - public abstract long getTotalRawBytesRead(); - } - - private static class ExposedGZIPInputStream extends GZIPInputStream { - public ExposedGZIPInputStream(final InputStream in) throws IOException { - super(in); - } - public Inflater getInflater() { - return inf; - } - } - - /** - * Provides raw bytes-read tracking for a GZIP input stream. Reports the - * total number of compressed bytes read from the input, rather than the - * number of uncompressed bytes. - */ - private static class TrackingGZIPInputStream extends TrackingInputStream { - private ExposedGZIPInputStream gzin; - public TrackingGZIPInputStream(final ExposedGZIPInputStream gzin) throws IOException { - super(gzin); - this.gzin = gzin; - } - public long getTotalRawBytesRead() { - return gzin.getInflater().getBytesRead(); - } - } - - /** - * Provides simple total-bytes-read tracking for an existing InputStream - */ - private static class SimpleTrackingInputStream extends TrackingInputStream { - private long bytesRead = 0; - public SimpleTrackingInputStream(InputStream stream) { - super(stream); - } - - private int updateBytesRead(int newBytesRead) { - if (newBytesRead != -1) { - bytesRead += newBytesRead; - } - return newBytesRead; - } - - @Override - public int read() throws IOException { - return updateBytesRead(super.read()); - } - - // Note: FilterInputStream delegates read(byte[] bytes) to the below method, - // so we don't override it or else double count (CB-5631). - @Override - public int read(byte[] bytes, int offset, int count) throws IOException { - return updateBytesRead(super.read(bytes, offset, count)); - } - - public long getTotalRawBytesRead() { - return bytesRead; - } - } - - @Override - public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException { - if (action.equals("upload") || action.equals("download")) { - String source = args.getString(0); - String target = args.getString(1); - - if (action.equals("upload")) { - try { - source = URLDecoder.decode(source, "UTF-8"); - upload(source, target, args, callbackContext); - } catch (UnsupportedEncodingException e) { - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.MALFORMED_URL_EXCEPTION, "UTF-8 error.")); - } - } else { - download(source, target, args, callbackContext); - } - return true; - } else if (action.equals("abort")) { - String objectId = args.getString(0); - abort(objectId); - callbackContext.success(); - return true; - } - return false; - } - - private static void addHeadersToRequest(URLConnection connection, JSONObject headers) { - try { - for (Iterator iter = headers.keys(); iter.hasNext(); ) { - String headerKey = iter.next().toString(); - JSONArray headerValues = headers.optJSONArray(headerKey); - if (headerValues == null) { - headerValues = new JSONArray(); - headerValues.put(headers.getString(headerKey)); - } - connection.setRequestProperty(headerKey, headerValues.getString(0)); - for (int i = 1; i < headerValues.length(); ++i) { - connection.addRequestProperty(headerKey, headerValues.getString(i)); - } - } - } catch (JSONException e1) { - // No headers to be manipulated! - } - } - - /** - * Uploads the specified file to the server URL provided using an HTTP multipart request. - * @param source Full path of the file on the file system - * @param target URL of the server to receive the file - * @param args JSON Array of args - * @param callbackContext callback id for optional progress reports - * - * args[2] fileKey Name of file request parameter - * args[3] fileName File name to be used on server - * args[4] mimeType Describes file content type - * args[5] params key:value pairs of user-defined parameters - * @return FileUploadResult containing result of upload request - */ - private void upload(final String source, final String target, JSONArray args, CallbackContext callbackContext) throws JSONException { - Log.d(LOG_TAG, "upload " + source + " to " + target); - - // Setup the options - final String fileKey = getArgument(args, 2, "file"); - final String fileName = getArgument(args, 3, "image.jpg"); - final String mimeType = getArgument(args, 4, "image/jpeg"); - final JSONObject params = args.optJSONObject(5) == null ? new JSONObject() : args.optJSONObject(5); - final boolean trustEveryone = args.optBoolean(6); - // Always use chunked mode unless set to false as per API - final boolean chunkedMode = args.optBoolean(7) || args.isNull(7); - // Look for headers on the params map for backwards compatibility with older Cordova versions. - final JSONObject headers = args.optJSONObject(8) == null ? params.optJSONObject("headers") : args.optJSONObject(8); - final String objectId = args.getString(9); - final String httpMethod = getArgument(args, 10, "POST"); - - final CordovaResourceApi resourceApi = webView.getResourceApi(); - - Log.d(LOG_TAG, "fileKey: " + fileKey); - Log.d(LOG_TAG, "fileName: " + fileName); - Log.d(LOG_TAG, "mimeType: " + mimeType); - Log.d(LOG_TAG, "params: " + params); - Log.d(LOG_TAG, "trustEveryone: " + trustEveryone); - Log.d(LOG_TAG, "chunkedMode: " + chunkedMode); - Log.d(LOG_TAG, "headers: " + headers); - Log.d(LOG_TAG, "objectId: " + objectId); - Log.d(LOG_TAG, "httpMethod: " + httpMethod); - - final Uri targetUri = resourceApi.remapUri(Uri.parse(target)); - // Accept a path or a URI for the source. - Uri tmpSrc = Uri.parse(source); - final Uri sourceUri = resourceApi.remapUri( - tmpSrc.getScheme() != null ? tmpSrc : Uri.fromFile(new File(source))); - - int uriType = CordovaResourceApi.getUriType(targetUri); - final boolean useHttps = uriType == CordovaResourceApi.URI_TYPE_HTTPS; - if (uriType != CordovaResourceApi.URI_TYPE_HTTP && !useHttps) { - JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, null, 0); - Log.e(LOG_TAG, "Unsupported URI: " + targetUri); - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error)); - return; - } - - final RequestContext context = new RequestContext(source, target, callbackContext); - synchronized (activeRequests) { - activeRequests.put(objectId, context); - } - - cordova.getThreadPool().execute(new Runnable() { - public void run() { - if (context.aborted) { - return; - } - HttpURLConnection conn = null; - HostnameVerifier oldHostnameVerifier = null; - SSLSocketFactory oldSocketFactory = null; - int totalBytes = 0; - int fixedLength = -1; - try { - // Create return object - FileUploadResult result = new FileUploadResult(); - FileProgressResult progress = new FileProgressResult(); - - //------------------ CLIENT REQUEST - // Open a HTTP connection to the URL based on protocol - conn = resourceApi.createHttpConnection(targetUri); - if (useHttps && trustEveryone) { - // Setup the HTTPS connection class to trust everyone - HttpsURLConnection https = (HttpsURLConnection)conn; - oldSocketFactory = trustAllHosts(https); - // Save the current hostnameVerifier - oldHostnameVerifier = https.getHostnameVerifier(); - // Setup the connection not to verify hostnames - https.setHostnameVerifier(DO_NOT_VERIFY); - } - - // Allow Inputs - conn.setDoInput(true); - - // Allow Outputs - conn.setDoOutput(true); - - // Don't use a cached copy. - conn.setUseCaches(false); - - // Use a post method. - conn.setRequestMethod(httpMethod); - - // if we specified a Content-Type header, don't do multipart form upload - boolean multipartFormUpload = (headers == null) || !headers.has("Content-Type"); - if (multipartFormUpload) { - conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); - } - // Set the cookies on the response - String cookie = AmazonCookieManager.getInstance().getCookie(target); - if (cookie != null) { - conn.setRequestProperty("Cookie", cookie); - } - - // Handle the other headers - if (headers != null) { - addHeadersToRequest(conn, headers); - } - - /* - * Store the non-file portions of the multipart data as a string, so that we can add it - * to the contentSize, since it is part of the body of the HTTP request. - */ - StringBuilder beforeData = new StringBuilder(); - try { - for (Iterator iter = params.keys(); iter.hasNext();) { - Object key = iter.next(); - if(!String.valueOf(key).equals("headers")) - { - beforeData.append(LINE_START).append(BOUNDARY).append(LINE_END); - beforeData.append("Content-Disposition: form-data; name=\"").append(key.toString()).append('"'); - beforeData.append(LINE_END).append(LINE_END); - beforeData.append(params.getString(key.toString())); - beforeData.append(LINE_END); - } - } - } catch (JSONException e) { - Log.e(LOG_TAG, e.getMessage(), e); - } - - beforeData.append(LINE_START).append(BOUNDARY).append(LINE_END); - beforeData.append("Content-Disposition: form-data; name=\"").append(fileKey).append("\";"); - beforeData.append(" filename=\"").append(fileName).append('"').append(LINE_END); - beforeData.append("Content-Type: ").append(mimeType).append(LINE_END).append(LINE_END); - byte[] beforeDataBytes = beforeData.toString().getBytes("UTF-8"); - byte[] tailParamsBytes = (LINE_END + LINE_START + BOUNDARY + LINE_START + LINE_END).getBytes("UTF-8"); - - - // Get a input stream of the file on the phone - OpenForReadResult readResult = resourceApi.openForRead(sourceUri); - - int stringLength = beforeDataBytes.length + tailParamsBytes.length; - if (readResult.length >= 0) { - fixedLength = (int)readResult.length; - if (multipartFormUpload) - fixedLength += stringLength; - progress.setLengthComputable(true); - progress.setTotal(fixedLength); - } - Log.d(LOG_TAG, "Content Length: " + fixedLength); - // setFixedLengthStreamingMode causes and OutOfMemoryException on pre-Froyo devices. - // http://code.google.com/p/android/issues/detail?id=3164 - // It also causes OOM if HTTPS is used, even on newer devices. - boolean useChunkedMode = chunkedMode && (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO || useHttps); - useChunkedMode = useChunkedMode || (fixedLength == -1); - - if (useChunkedMode) { - conn.setChunkedStreamingMode(MAX_BUFFER_SIZE); - // Although setChunkedStreamingMode sets this header, setting it explicitly here works - // around an OutOfMemoryException when using https. - conn.setRequestProperty("Transfer-Encoding", "chunked"); - } else { - conn.setFixedLengthStreamingMode(fixedLength); - } - - conn.connect(); - - OutputStream sendStream = null; - try { - sendStream = conn.getOutputStream(); - synchronized (context) { - if (context.aborted) { - return; - } - context.currentOutputStream = sendStream; - } - - if (multipartFormUpload) { - //We don't want to change encoding, we just want this to write for all Unicode. - sendStream.write(beforeDataBytes); - totalBytes += beforeDataBytes.length; - } - // create a buffer of maximum size - int bytesAvailable = readResult.inputStream.available(); - int bufferSize = Math.min(bytesAvailable, MAX_BUFFER_SIZE); - byte[] buffer = new byte[bufferSize]; - - // read file and write it into form... - int bytesRead = readResult.inputStream.read(buffer, 0, bufferSize); - - long prevBytesRead = 0; - while (bytesRead > 0) { - result.setBytesSent(totalBytes); - sendStream.write(buffer, 0, bytesRead); - totalBytes += bytesRead; - if (totalBytes > prevBytesRead + 102400) { - prevBytesRead = totalBytes; - Log.d(LOG_TAG, "Uploaded " + totalBytes + " of " + fixedLength + " bytes"); - } - bytesAvailable = readResult.inputStream.available(); - bufferSize = Math.min(bytesAvailable, MAX_BUFFER_SIZE); - bytesRead = readResult.inputStream.read(buffer, 0, bufferSize); - - // Send a progress event. - progress.setLoaded(totalBytes); - PluginResult progressResult = new PluginResult(PluginResult.Status.OK, progress.toJSONObject()); - progressResult.setKeepCallback(true); - context.sendPluginResult(progressResult); - } - - if (multipartFormUpload) { - // send multipart form data necessary after file data... - sendStream.write(tailParamsBytes); - totalBytes += tailParamsBytes.length; - } - sendStream.flush(); - } finally { - safeClose(readResult.inputStream); - safeClose(sendStream); - } - context.currentOutputStream = null; - Log.d(LOG_TAG, "Sent " + totalBytes + " of " + fixedLength); - - //------------------ read the SERVER RESPONSE - String responseString; - int responseCode = conn.getResponseCode(); - Log.d(LOG_TAG, "response code: " + responseCode); - Log.d(LOG_TAG, "response headers: " + conn.getHeaderFields()); - TrackingInputStream inStream = null; - try { - inStream = getInputStream(conn); - synchronized (context) { - if (context.aborted) { - return; - } - context.currentInputStream = inStream; - } - - ByteArrayOutputStream out = new ByteArrayOutputStream(Math.max(1024, conn.getContentLength())); - byte[] buffer = new byte[1024]; - int bytesRead = 0; - // write bytes to file - while ((bytesRead = inStream.read(buffer)) > 0) { - out.write(buffer, 0, bytesRead); - } - responseString = out.toString("UTF-8"); - } finally { - context.currentInputStream = null; - safeClose(inStream); - } - - Log.d(LOG_TAG, "got response from server"); - Log.d(LOG_TAG, responseString.substring(0, Math.min(256, responseString.length()))); - - // send request and retrieve response - result.setResponseCode(responseCode); - result.setResponse(responseString); - - context.sendPluginResult(new PluginResult(PluginResult.Status.OK, result.toJSONObject())); - } catch (FileNotFoundException e) { - JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, conn); - Log.e(LOG_TAG, error.toString(), e); - context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error)); - } catch (IOException e) { - JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn); - Log.e(LOG_TAG, error.toString(), e); - Log.e(LOG_TAG, "Failed after uploading " + totalBytes + " of " + fixedLength + " bytes."); - context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error)); - } catch (JSONException e) { - Log.e(LOG_TAG, e.getMessage(), e); - context.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); - } catch (Throwable t) { - // Shouldn't happen, but will - JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn); - Log.e(LOG_TAG, error.toString(), t); - context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error)); - } finally { - synchronized (activeRequests) { - activeRequests.remove(objectId); - } - - if (conn != null) { - // Revert back to the proper verifier and socket factories - // Revert back to the proper verifier and socket factories - if (trustEveryone && useHttps) { - HttpsURLConnection https = (HttpsURLConnection) conn; - https.setHostnameVerifier(oldHostnameVerifier); - https.setSSLSocketFactory(oldSocketFactory); - } - } - } - } - }); - } - - private static void safeClose(Closeable stream) { - if (stream != null) { - try { - stream.close(); - } catch (IOException e) { - } - } - } - - private static TrackingInputStream getInputStream(URLConnection conn) throws IOException { - String encoding = conn.getContentEncoding(); - if (encoding != null && encoding.equalsIgnoreCase("gzip")) { - return new TrackingGZIPInputStream(new ExposedGZIPInputStream(conn.getInputStream())); - } - return new SimpleTrackingInputStream(conn.getInputStream()); - } - - // always verify the host - don't check for certificate - private static final HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() { - public boolean verify(String hostname, SSLSession session) { - return true; - } - }; - // Create a trust manager that does not validate certificate chains - private static final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { - public java.security.cert.X509Certificate[] getAcceptedIssuers() { - return new java.security.cert.X509Certificate[] {}; - } - - public void checkClientTrusted(X509Certificate[] chain, - String authType) throws CertificateException { - } - - public void checkServerTrusted(X509Certificate[] chain, - String authType) throws CertificateException { - } - } }; - - /** - * This function will install a trust manager that will blindly trust all SSL - * certificates. The reason this code is being added is to enable developers - * to do development using self signed SSL certificates on their web server. - * - * The standard HttpsURLConnection class will throw an exception on self - * signed certificates if this code is not run. - */ - private static SSLSocketFactory trustAllHosts(HttpsURLConnection connection) { - // Install the all-trusting trust manager - SSLSocketFactory oldFactory = connection.getSSLSocketFactory(); - try { - // Install our all trusting manager - SSLContext sc = SSLContext.getInstance("TLS"); - sc.init(null, trustAllCerts, new java.security.SecureRandom()); - SSLSocketFactory newFactory = sc.getSocketFactory(); - connection.setSSLSocketFactory(newFactory); - } catch (Exception e) { - Log.e(LOG_TAG, e.getMessage(), e); - } - return oldFactory; - } - - private static JSONObject createFileTransferError(int errorCode, String source, String target, URLConnection connection) { - - int httpStatus = 0; - StringBuilder bodyBuilder = new StringBuilder(); - String body = null; - if (connection != null) { - try { - if (connection instanceof HttpURLConnection) { - httpStatus = ((HttpURLConnection)connection).getResponseCode(); - InputStream err = ((HttpURLConnection) connection).getErrorStream(); - if(err != null) - { - BufferedReader reader = new BufferedReader(new InputStreamReader(err, "UTF-8")); - try { - String line = reader.readLine(); - while(line != null) { - bodyBuilder.append(line); - line = reader.readLine(); - if(line != null) { - bodyBuilder.append('\n'); - } - } - body = bodyBuilder.toString(); - } finally { - reader.close(); - } - } - } - // IOException can leave connection object in a bad state, so catch all exceptions. - } catch (Throwable e) { - Log.w(LOG_TAG, "Error getting HTTP status code from connection.", e); - } - } - - return createFileTransferError(errorCode, source, target, body, httpStatus); - } - - /** - * Create an error object based on the passed in errorCode - * @param errorCode the error - * @return JSONObject containing the error - */ - private static JSONObject createFileTransferError(int errorCode, String source, String target, String body, Integer httpStatus) { - JSONObject error = null; - try { - error = new JSONObject(); - error.put("code", errorCode); - error.put("source", source); - error.put("target", target); - if(body != null) - { - error.put("body", body); - } - if (httpStatus != null) { - error.put("http_status", httpStatus); - } - } catch (JSONException e) { - Log.e(LOG_TAG, e.getMessage(), e); - } - return error; - } - - /** - * Convenience method to read a parameter from the list of JSON args. - * @param args the args passed to the Plugin - * @param position the position to retrieve the arg from - * @param defaultString the default to be used if the arg does not exist - * @return String with the retrieved value - */ - private static String getArgument(JSONArray args, int position, String defaultString) { - String arg = defaultString; - if (args.length() > position) { - arg = args.optString(position); - if (arg == null || "null".equals(arg)) { - arg = defaultString; - } - } - return arg; - } - - /** - * Downloads a file form a given URL and saves it to the specified directory. - * - * @param source URL of the server to receive the file - * @param target Full path of the file on the file system - */ - private void download(final String source, final String target, JSONArray args, CallbackContext callbackContext) throws JSONException { - Log.d(LOG_TAG, "download " + source + " to " + target); - - final CordovaResourceApi resourceApi = webView.getResourceApi(); - - final boolean trustEveryone = args.optBoolean(2); - final String objectId = args.getString(3); - final JSONObject headers = args.optJSONObject(4); - - final Uri sourceUri = resourceApi.remapUri(Uri.parse(source)); - // Accept a path or a URI for the source. - Uri tmpTarget = Uri.parse(target); - final Uri targetUri = resourceApi.remapUri( - tmpTarget.getScheme() != null ? tmpTarget : Uri.fromFile(new File(target))); - - int uriType = CordovaResourceApi.getUriType(sourceUri); - final boolean useHttps = uriType == CordovaResourceApi.URI_TYPE_HTTPS; - final boolean isLocalTransfer = !useHttps && uriType != CordovaResourceApi.URI_TYPE_HTTP; - if (uriType == CordovaResourceApi.URI_TYPE_UNKNOWN) { - JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, null, 0); - Log.e(LOG_TAG, "Unsupported URI: " + targetUri); - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error)); - return; - } - - // TODO: refactor to also allow resources & content: - if (!isLocalTransfer && !Config.isUrlWhiteListed(source)) { - Log.w(LOG_TAG, "Source URL is not in white list: '" + source + "'"); - JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, null, 401); - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error)); - return; - } - - - final RequestContext context = new RequestContext(source, target, callbackContext); - synchronized (activeRequests) { - activeRequests.put(objectId, context); - } - - cordova.getThreadPool().execute(new Runnable() { - public void run() { - if (context.aborted) { - return; - } - HttpURLConnection connection = null; - HostnameVerifier oldHostnameVerifier = null; - SSLSocketFactory oldSocketFactory = null; - File file = null; - PluginResult result = null; - TrackingInputStream inputStream = null; - - OutputStream outputStream = null; - try { - OpenForReadResult readResult = null; - outputStream = resourceApi.openOutputStream(targetUri); - - file = resourceApi.mapUriToFile(targetUri); - context.targetFile = file; - - Log.d(LOG_TAG, "Download file:" + sourceUri); - - FileProgressResult progress = new FileProgressResult(); - - if (isLocalTransfer) { - readResult = resourceApi.openForRead(sourceUri); - if (readResult.length != -1) { - progress.setLengthComputable(true); - progress.setTotal(readResult.length); - } - inputStream = new SimpleTrackingInputStream(readResult.inputStream); - } else { - // connect to server - // Open a HTTP connection to the URL based on protocol - connection = resourceApi.createHttpConnection(sourceUri); - if (useHttps && trustEveryone) { - // Setup the HTTPS connection class to trust everyone - HttpsURLConnection https = (HttpsURLConnection)connection; - oldSocketFactory = trustAllHosts(https); - // Save the current hostnameVerifier - oldHostnameVerifier = https.getHostnameVerifier(); - // Setup the connection not to verify hostnames - https.setHostnameVerifier(DO_NOT_VERIFY); - } - - connection.setRequestMethod("GET"); - - // TODO: Make OkHttp use this AmazonCookieManager by default. - String cookie = AmazonCookieManager.getInstance().getCookie(sourceUri.toString()); - if(cookie != null) - { - connection.setRequestProperty("cookie", cookie); - } - - // This must be explicitly set for gzip progress tracking to work. - connection.setRequestProperty("Accept-Encoding", "gzip"); - - // Handle the other headers - if (headers != null) { - addHeadersToRequest(connection, headers); - } - - connection.connect(); - - if (connection.getContentEncoding() == null || connection.getContentEncoding().equalsIgnoreCase("gzip")) { - // Only trust content-length header if we understand - // the encoding -- identity or gzip - if (connection.getContentLength() != -1) { - progress.setLengthComputable(true); - progress.setTotal(connection.getContentLength()); - } - } - inputStream = getInputStream(connection); - } - - try { - synchronized (context) { - if (context.aborted) { - return; - } - context.currentInputStream = inputStream; - } - - // write bytes to file - byte[] buffer = new byte[MAX_BUFFER_SIZE]; - int bytesRead = 0; - while ((bytesRead = inputStream.read(buffer)) > 0) { - outputStream.write(buffer, 0, bytesRead); - // Send a progress event. - progress.setLoaded(inputStream.getTotalRawBytesRead()); - PluginResult progressResult = new PluginResult(PluginResult.Status.OK, progress.toJSONObject()); - progressResult.setKeepCallback(true); - context.sendPluginResult(progressResult); - } - } finally { - context.currentInputStream = null; - safeClose(inputStream); - safeClose(outputStream); - } - - Log.d(LOG_TAG, "Saved file: " + target); - - // create FileEntry object - FileUtils filePlugin = (FileUtils)webView.pluginManager.getPlugin("File"); - if (filePlugin != null) { - JSONObject fileEntry = filePlugin.getEntryForFile(file); - if (fileEntry != null) { - result = new PluginResult(PluginResult.Status.OK, fileEntry); - } else { - JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, connection); - Log.e(LOG_TAG, "File plugin cannot represent download path"); - result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error); - } - } else { - Log.e(LOG_TAG, "File plugin not found; cannot save downloaded file"); - result = new PluginResult(PluginResult.Status.ERROR, "File plugin not found; cannot save downloaded file"); - } - - } catch (FileNotFoundException e) { - JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, connection); - Log.e(LOG_TAG, error.toString(), e); - result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error); - } catch (IOException e) { - JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, connection); - Log.e(LOG_TAG, error.toString(), e); - result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error); - } catch (JSONException e) { - Log.e(LOG_TAG, e.getMessage(), e); - result = new PluginResult(PluginResult.Status.JSON_EXCEPTION); - } catch (Throwable e) { - JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, connection); - Log.e(LOG_TAG, error.toString(), e); - result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error); - } finally { - safeClose(outputStream); - synchronized (activeRequests) { - activeRequests.remove(objectId); - } - - if (connection != null) { - // Revert back to the proper verifier and socket factories - if (trustEveryone && useHttps) { - HttpsURLConnection https = (HttpsURLConnection) connection; - https.setHostnameVerifier(oldHostnameVerifier); - https.setSSLSocketFactory(oldSocketFactory); - } - } - - if (result == null) { - result = new PluginResult(PluginResult.Status.ERROR, createFileTransferError(CONNECTION_ERR, source, target, connection)); - } - // Remove incomplete download. - if (result.getStatus() != PluginResult.Status.OK.ordinal() && file != null) { - file.delete(); - } - context.sendPluginResult(result); - } - } - }); - } - - /** - * Abort an ongoing upload or download. - */ - private void abort(String objectId) { - final RequestContext context; - synchronized (activeRequests) { - context = activeRequests.remove(objectId); - } - if (context != null) { - File file = context.targetFile; - if (file != null) { - file.delete(); - } - // Trigger the abort callback immediately to minimize latency between it and abort() being called. - JSONObject error = createFileTransferError(ABORTED_ERR, context.source, context.target, null, -1); - synchronized (context) { - context.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, error)); - context.aborted = true; - } - // Closing the streams can block, so execute on a background thread. - cordova.getThreadPool().execute(new Runnable() { - public void run() { - synchronized (context) { - safeClose(context.currentInputStream); - safeClose(context.currentOutputStream); - } - } - }); - } - } -} diff --git a/plugins/cordova-plugin-file-transfer/src/android/FileProgressResult.java b/plugins/cordova-plugin-file-transfer/src/android/FileProgressResult.java deleted file mode 100644 index 76a7b13..0000000 --- a/plugins/cordova-plugin-file-transfer/src/android/FileProgressResult.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - 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.filetransfer; - -import org.json.JSONException; -import org.json.JSONObject; - -/** - * Encapsulates in-progress status of uploading or downloading a file to a remote server. - */ -public class FileProgressResult { - - private boolean lengthComputable = false; // declares whether total is known - private long loaded = 0; // bytes sent so far - private long total = 0; // bytes total, if known - - public boolean getLengthComputable() { - return lengthComputable; - } - - public void setLengthComputable(boolean computable) { - this.lengthComputable = computable; - } - - public long getLoaded() { - return loaded; - } - - public void setLoaded(long bytes) { - this.loaded = bytes; - } - - public long getTotal() { - return total; - } - - public void setTotal(long bytes) { - this.total = bytes; - } - - public JSONObject toJSONObject() throws JSONException { - return new JSONObject( - "{loaded:" + loaded + - ",total:" + total + - ",lengthComputable:" + (lengthComputable ? "true" : "false") + "}"); - } -} diff --git a/plugins/cordova-plugin-file-transfer/src/android/FileTransfer.java b/plugins/cordova-plugin-file-transfer/src/android/FileTransfer.java deleted file mode 100644 index 5a3c5d6..0000000 --- a/plugins/cordova-plugin-file-transfer/src/android/FileTransfer.java +++ /dev/null @@ -1,932 +0,0 @@ -/* - 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.filetransfer; - -import java.io.BufferedReader; -import java.io.ByteArrayOutputStream; -import java.io.Closeable; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FilterInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.net.HttpURLConnection; -import java.net.URLConnection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.zip.GZIPInputStream; -import java.util.zip.Inflater; - -import org.apache.cordova.CallbackContext; -import org.apache.cordova.CordovaPlugin; -import org.apache.cordova.CordovaResourceApi; -import org.apache.cordova.CordovaResourceApi.OpenForReadResult; -import org.apache.cordova.LOG; -import org.apache.cordova.PluginManager; -import org.apache.cordova.PluginResult; -import org.apache.cordova.Whitelist; -import org.apache.cordova.file.FileUtils; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import android.net.Uri; -import android.os.Build; -import android.webkit.CookieManager; - -public class FileTransfer extends CordovaPlugin { - - private static final String LOG_TAG = "FileTransfer"; - private static final String LINE_START = "--"; - private static final String LINE_END = "\r\n"; - private static final String BOUNDARY = "+++++"; - - public static int FILE_NOT_FOUND_ERR = 1; - public static int INVALID_URL_ERR = 2; - public static int CONNECTION_ERR = 3; - public static int ABORTED_ERR = 4; - public static int NOT_MODIFIED_ERR = 5; - - private static HashMap activeRequests = new HashMap(); - private static final int MAX_BUFFER_SIZE = 16 * 1024; - - private static final class RequestContext { - String source; - String target; - File targetFile; - CallbackContext callbackContext; - HttpURLConnection connection; - boolean aborted; - RequestContext(String source, String target, CallbackContext callbackContext) { - this.source = source; - this.target = target; - this.callbackContext = callbackContext; - } - void sendPluginResult(PluginResult pluginResult) { - synchronized (this) { - if (!aborted) { - callbackContext.sendPluginResult(pluginResult); - } - } - } - } - - /** - * Adds an interface method to an InputStream to return the number of bytes - * read from the raw stream. This is used to track total progress against - * the HTTP Content-Length header value from the server. - */ - private static abstract class TrackingInputStream extends FilterInputStream { - public TrackingInputStream(final InputStream in) { - super(in); - } - public abstract long getTotalRawBytesRead(); - } - - private static class ExposedGZIPInputStream extends GZIPInputStream { - public ExposedGZIPInputStream(final InputStream in) throws IOException { - super(in); - } - public Inflater getInflater() { - return inf; - } - } - - /** - * Provides raw bytes-read tracking for a GZIP input stream. Reports the - * total number of compressed bytes read from the input, rather than the - * number of uncompressed bytes. - */ - private static class TrackingGZIPInputStream extends TrackingInputStream { - private ExposedGZIPInputStream gzin; - public TrackingGZIPInputStream(final ExposedGZIPInputStream gzin) throws IOException { - super(gzin); - this.gzin = gzin; - } - public long getTotalRawBytesRead() { - return gzin.getInflater().getBytesRead(); - } - } - - /** - * Provides simple total-bytes-read tracking for an existing InputStream - */ - private static class SimpleTrackingInputStream extends TrackingInputStream { - private long bytesRead = 0; - public SimpleTrackingInputStream(InputStream stream) { - super(stream); - } - - private int updateBytesRead(int newBytesRead) { - if (newBytesRead != -1) { - bytesRead += newBytesRead; - } - return newBytesRead; - } - - @Override - public int read() throws IOException { - return updateBytesRead(super.read()); - } - - // Note: FilterInputStream delegates read(byte[] bytes) to the below method, - // so we don't override it or else double count (CB-5631). - @Override - public int read(byte[] bytes, int offset, int count) throws IOException { - return updateBytesRead(super.read(bytes, offset, count)); - } - - public long getTotalRawBytesRead() { - return bytesRead; - } - } - - @Override - public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException { - if (action.equals("upload") || action.equals("download")) { - String source = args.getString(0); - String target = args.getString(1); - - if (action.equals("upload")) { - upload(source, target, args, callbackContext); - } else { - download(source, target, args, callbackContext); - } - return true; - } else if (action.equals("abort")) { - String objectId = args.getString(0); - abort(objectId); - callbackContext.success(); - return true; - } - return false; - } - - private static void addHeadersToRequest(URLConnection connection, JSONObject headers) { - try { - for (Iterator iter = headers.keys(); iter.hasNext(); ) { - /* RFC 2616 says that non-ASCII characters and control - * characters are not allowed in header names or values. - * Additionally, spaces are not allowed in header names. - * RFC 2046 Quoted-printable encoding may be used to encode - * arbitrary characters, but we donon- not do that encoding here. - */ - String headerKey = iter.next().toString(); - String cleanHeaderKey = headerKey.replaceAll("\\n","") - .replaceAll("\\s+","") - .replaceAll(":", "") - .replaceAll("[^\\x20-\\x7E]+", ""); - - JSONArray headerValues = headers.optJSONArray(headerKey); - if (headerValues == null) { - headerValues = new JSONArray(); - - /* RFC 2616 also says that any amount of consecutive linear - * whitespace within a header value can be replaced with a - * single space character, without affecting the meaning of - * that value. - */ - - String headerValue = headers.getString(headerKey); - String finalValue = headerValue.replaceAll("\\s+", " ").replaceAll("\\n"," ").replaceAll("[^\\x20-\\x7E]+", " "); - headerValues.put(finalValue); - } - - //Use the clean header key, not the one that we passed in - connection.setRequestProperty(cleanHeaderKey, headerValues.getString(0)); - for (int i = 1; i < headerValues.length(); ++i) { - connection.addRequestProperty(headerKey, headerValues.getString(i)); - } - } - } catch (JSONException e1) { - // No headers to be manipulated! - } - } - - private String getCookies(final String target) { - boolean gotCookie = false; - String cookie = null; - Class webViewClass = webView.getClass(); - try { - Method gcmMethod = webViewClass.getMethod("getCookieManager"); - Class iccmClass = gcmMethod.getReturnType(); - Method gcMethod = iccmClass.getMethod("getCookie", String.class); - - cookie = (String)gcMethod.invoke( - iccmClass.cast( - gcmMethod.invoke(webView) - ), target); - - gotCookie = true; - } catch (NoSuchMethodException e) { - } catch (IllegalAccessException e) { - } catch (InvocationTargetException e) { - } catch (ClassCastException e) { - } - - if (!gotCookie && CookieManager.getInstance() != null) { - cookie = CookieManager.getInstance().getCookie(target); - } - - return cookie; - } - - /** - * Uploads the specified file to the server URL provided using an HTTP multipart request. - * @param source Full path of the file on the file system - * @param target URL of the server to receive the file - * @param args JSON Array of args - * @param callbackContext callback id for optional progress reports - * - * args[2] fileKey Name of file request parameter - * args[3] fileName File name to be used on server - * args[4] mimeType Describes file content type - * args[5] params key:value pairs of user-defined parameters - * @return FileUploadResult containing result of upload request - */ - private void upload(final String source, final String target, JSONArray args, CallbackContext callbackContext) throws JSONException { - LOG.d(LOG_TAG, "upload " + source + " to " + target); - - // Setup the options - final String fileKey = getArgument(args, 2, "file"); - final String fileName = getArgument(args, 3, "image.jpg"); - final String mimeType = getArgument(args, 4, "image/jpeg"); - final JSONObject params = args.optJSONObject(5) == null ? new JSONObject() : args.optJSONObject(5); - // Always use chunked mode unless set to false as per API - final boolean chunkedMode = args.optBoolean(7) || args.isNull(7); - // Look for headers on the params map for backwards compatibility with older Cordova versions. - final JSONObject headers = args.optJSONObject(8) == null ? params.optJSONObject("headers") : args.optJSONObject(8); - final String objectId = args.getString(9); - final String httpMethod = getArgument(args, 10, "POST"); - - final CordovaResourceApi resourceApi = webView.getResourceApi(); - - LOG.d(LOG_TAG, "fileKey: " + fileKey); - LOG.d(LOG_TAG, "fileName: " + fileName); - LOG.d(LOG_TAG, "mimeType: " + mimeType); - LOG.d(LOG_TAG, "params: " + params); - LOG.d(LOG_TAG, "chunkedMode: " + chunkedMode); - LOG.d(LOG_TAG, "headers: " + headers); - LOG.d(LOG_TAG, "objectId: " + objectId); - LOG.d(LOG_TAG, "httpMethod: " + httpMethod); - - final Uri targetUri = resourceApi.remapUri(Uri.parse(target)); - - int uriType = CordovaResourceApi.getUriType(targetUri); - final boolean useHttps = uriType == CordovaResourceApi.URI_TYPE_HTTPS; - if (uriType != CordovaResourceApi.URI_TYPE_HTTP && !useHttps) { - JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, null, 0, null); - LOG.e(LOG_TAG, "Unsupported URI: " + targetUri); - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error)); - return; - } - - final RequestContext context = new RequestContext(source, target, callbackContext); - synchronized (activeRequests) { - activeRequests.put(objectId, context); - } - - cordova.getThreadPool().execute(new Runnable() { - public void run() { - if (context.aborted) { - return; - } - - // We should call remapUri on background thread otherwise it throws - // IllegalStateException when trying to remap 'cdvfile://localhost/content/...' URIs - // via ContentFilesystem (see https://issues.apache.org/jira/browse/CB-9022) - Uri tmpSrc = Uri.parse(source); - final Uri sourceUri = resourceApi.remapUri( - tmpSrc.getScheme() != null ? tmpSrc : Uri.fromFile(new File(source))); - - HttpURLConnection conn = null; - int totalBytes = 0; - int fixedLength = -1; - try { - // Create return object - FileUploadResult result = new FileUploadResult(); - FileProgressResult progress = new FileProgressResult(); - - //------------------ CLIENT REQUEST - // Open a HTTP connection to the URL based on protocol - conn = resourceApi.createHttpConnection(targetUri); - - // Allow Inputs - conn.setDoInput(true); - - // Allow Outputs - conn.setDoOutput(true); - - // Don't use a cached copy. - conn.setUseCaches(false); - - // Use a post method. - conn.setRequestMethod(httpMethod); - - // if we specified a Content-Type header, don't do multipart form upload - boolean multipartFormUpload = (headers == null) || !headers.has("Content-Type"); - if (multipartFormUpload) { - conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); - } - - // Set the cookies on the response - String cookie = getCookies(target); - - if (cookie != null) { - conn.setRequestProperty("Cookie", cookie); - } - - // Handle the other headers - if (headers != null) { - addHeadersToRequest(conn, headers); - } - - /* - * Store the non-file portions of the multipart data as a string, so that we can add it - * to the contentSize, since it is part of the body of the HTTP request. - */ - StringBuilder beforeData = new StringBuilder(); - try { - for (Iterator iter = params.keys(); iter.hasNext();) { - Object key = iter.next(); - if(!String.valueOf(key).equals("headers")) - { - beforeData.append(LINE_START).append(BOUNDARY).append(LINE_END); - beforeData.append("Content-Disposition: form-data; name=\"").append(key.toString()).append('"'); - beforeData.append(LINE_END).append(LINE_END); - beforeData.append(params.getString(key.toString())); - beforeData.append(LINE_END); - } - } - } catch (JSONException e) { - LOG.e(LOG_TAG, e.getMessage(), e); - } - - beforeData.append(LINE_START).append(BOUNDARY).append(LINE_END); - beforeData.append("Content-Disposition: form-data; name=\"").append(fileKey).append("\";"); - beforeData.append(" filename=\"").append(fileName).append('"').append(LINE_END); - beforeData.append("Content-Type: ").append(mimeType).append(LINE_END).append(LINE_END); - byte[] beforeDataBytes = beforeData.toString().getBytes("UTF-8"); - byte[] tailParamsBytes = (LINE_END + LINE_START + BOUNDARY + LINE_START + LINE_END).getBytes("UTF-8"); - - - // Get a input stream of the file on the phone - OpenForReadResult readResult = resourceApi.openForRead(sourceUri); - - int stringLength = beforeDataBytes.length + tailParamsBytes.length; - if (readResult.length >= 0) { - fixedLength = (int)readResult.length; - if (multipartFormUpload) - fixedLength += stringLength; - progress.setLengthComputable(true); - progress.setTotal(fixedLength); - } - LOG.d(LOG_TAG, "Content Length: " + fixedLength); - // setFixedLengthStreamingMode causes and OutOfMemoryException on pre-Froyo devices. - // http://code.google.com/p/android/issues/detail?id=3164 - // It also causes OOM if HTTPS is used, even on newer devices. - boolean useChunkedMode = chunkedMode || (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO); - useChunkedMode = useChunkedMode || (fixedLength == -1); - - if (useChunkedMode) { - conn.setChunkedStreamingMode(MAX_BUFFER_SIZE); - // Although setChunkedStreamingMode sets this header, setting it explicitly here works - // around an OutOfMemoryException when using https. - conn.setRequestProperty("Transfer-Encoding", "chunked"); - } else { - conn.setFixedLengthStreamingMode(fixedLength); - - if (useHttps) { - LOG.w(LOG_TAG, "setFixedLengthStreamingMode could cause OutOfMemoryException - switch to chunkedMode=true to avoid it if this is an issue."); - } - } - - conn.connect(); - - OutputStream sendStream = null; - try { - sendStream = conn.getOutputStream(); - synchronized (context) { - if (context.aborted) { - return; - } - context.connection = conn; - } - - if (multipartFormUpload) { - //We don't want to change encoding, we just want this to write for all Unicode. - sendStream.write(beforeDataBytes); - totalBytes += beforeDataBytes.length; - } - - // create a buffer of maximum size - int bytesAvailable = readResult.inputStream.available(); - int bufferSize = Math.min(bytesAvailable, MAX_BUFFER_SIZE); - byte[] buffer = new byte[bufferSize]; - - // read file and write it into form... - int bytesRead = readResult.inputStream.read(buffer, 0, bufferSize); - - long prevBytesRead = 0; - while (bytesRead > 0) { - totalBytes += bytesRead; - result.setBytesSent(totalBytes); - sendStream.write(buffer, 0, bytesRead); - if (totalBytes > prevBytesRead + 102400) { - prevBytesRead = totalBytes; - LOG.d(LOG_TAG, "Uploaded " + totalBytes + " of " + fixedLength + " bytes"); - } - bytesAvailable = readResult.inputStream.available(); - bufferSize = Math.min(bytesAvailable, MAX_BUFFER_SIZE); - bytesRead = readResult.inputStream.read(buffer, 0, bufferSize); - - // Send a progress event. - progress.setLoaded(totalBytes); - PluginResult progressResult = new PluginResult(PluginResult.Status.OK, progress.toJSONObject()); - progressResult.setKeepCallback(true); - context.sendPluginResult(progressResult); - } - - if (multipartFormUpload) { - // send multipart form data necessary after file data... - sendStream.write(tailParamsBytes); - totalBytes += tailParamsBytes.length; - } - sendStream.flush(); - } finally { - safeClose(readResult.inputStream); - safeClose(sendStream); - } - synchronized (context) { - context.connection = null; - } - LOG.d(LOG_TAG, "Sent " + totalBytes + " of " + fixedLength); - - //------------------ read the SERVER RESPONSE - String responseString; - int responseCode = conn.getResponseCode(); - LOG.d(LOG_TAG, "response code: " + responseCode); - LOG.d(LOG_TAG, "response headers: " + conn.getHeaderFields()); - TrackingInputStream inStream = null; - try { - inStream = getInputStream(conn); - synchronized (context) { - if (context.aborted) { - return; - } - context.connection = conn; - } - - ByteArrayOutputStream out = new ByteArrayOutputStream(Math.max(1024, conn.getContentLength())); - byte[] buffer = new byte[1024]; - int bytesRead = 0; - // write bytes to file - while ((bytesRead = inStream.read(buffer)) > 0) { - out.write(buffer, 0, bytesRead); - } - responseString = out.toString("UTF-8"); - } finally { - synchronized (context) { - context.connection = null; - } - safeClose(inStream); - } - - LOG.d(LOG_TAG, "got response from server"); - LOG.d(LOG_TAG, responseString.substring(0, Math.min(256, responseString.length()))); - - // send request and retrieve response - result.setResponseCode(responseCode); - result.setResponse(responseString); - - context.sendPluginResult(new PluginResult(PluginResult.Status.OK, result.toJSONObject())); - } catch (FileNotFoundException e) { - JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, conn, e); - LOG.e(LOG_TAG, error.toString(), e); - context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error)); - } catch (IOException e) { - JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn, e); - LOG.e(LOG_TAG, error.toString(), e); - LOG.e(LOG_TAG, "Failed after uploading " + totalBytes + " of " + fixedLength + " bytes."); - context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error)); - } catch (JSONException e) { - LOG.e(LOG_TAG, e.getMessage(), e); - context.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); - } catch (Throwable t) { - // Shouldn't happen, but will - JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn, t); - LOG.e(LOG_TAG, error.toString(), t); - context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error)); - } finally { - synchronized (activeRequests) { - activeRequests.remove(objectId); - } - } - } - }); - } - - private static void safeClose(Closeable stream) { - if (stream != null) { - try { - stream.close(); - } catch (IOException e) { - } - } - } - - private static TrackingInputStream getInputStream(URLConnection conn) throws IOException { - String encoding = conn.getContentEncoding(); - if (encoding != null && encoding.equalsIgnoreCase("gzip")) { - return new TrackingGZIPInputStream(new ExposedGZIPInputStream(conn.getInputStream())); - } - return new SimpleTrackingInputStream(conn.getInputStream()); - } - - private static JSONObject createFileTransferError(int errorCode, String source, String target, URLConnection connection, Throwable throwable) { - - int httpStatus = 0; - StringBuilder bodyBuilder = new StringBuilder(); - String body = null; - if (connection != null) { - try { - if (connection instanceof HttpURLConnection) { - httpStatus = ((HttpURLConnection)connection).getResponseCode(); - InputStream err = ((HttpURLConnection) connection).getErrorStream(); - if(err != null) - { - BufferedReader reader = new BufferedReader(new InputStreamReader(err, "UTF-8")); - try { - String line = reader.readLine(); - while(line != null) { - bodyBuilder.append(line); - line = reader.readLine(); - if(line != null) { - bodyBuilder.append('\n'); - } - } - body = bodyBuilder.toString(); - } finally { - reader.close(); - } - } - } - // IOException can leave connection object in a bad state, so catch all exceptions. - } catch (Throwable e) { - LOG.w(LOG_TAG, "Error getting HTTP status code from connection.", e); - } - } - - return createFileTransferError(errorCode, source, target, body, httpStatus, throwable); - } - - /** - * Create an error object based on the passed in errorCode - * @param errorCode the error - * @return JSONObject containing the error - */ - private static JSONObject createFileTransferError(int errorCode, String source, String target, String body, Integer httpStatus, Throwable throwable) { - JSONObject error = null; - try { - error = new JSONObject(); - error.put("code", errorCode); - error.put("source", source); - error.put("target", target); - if(body != null) - { - error.put("body", body); - } - if (httpStatus != null) { - error.put("http_status", httpStatus); - } - if (throwable != null) { - String msg = throwable.getMessage(); - if (msg == null || "".equals(msg)) { - msg = throwable.toString(); - } - error.put("exception", msg); - } - } catch (JSONException e) { - LOG.e(LOG_TAG, e.getMessage(), e); - } - return error; - } - - /** - * Convenience method to read a parameter from the list of JSON args. - * @param args the args passed to the Plugin - * @param position the position to retrieve the arg from - * @param defaultString the default to be used if the arg does not exist - * @return String with the retrieved value - */ - private static String getArgument(JSONArray args, int position, String defaultString) { - String arg = defaultString; - if (args.length() > position) { - arg = args.optString(position); - if (arg == null || "null".equals(arg)) { - arg = defaultString; - } - } - return arg; - } - - /** - * Downloads a file form a given URL and saves it to the specified directory. - * - * @param source URL of the server to receive the file - * @param target Full path of the file on the file system - */ - private void download(final String source, final String target, JSONArray args, CallbackContext callbackContext) throws JSONException { - LOG.d(LOG_TAG, "download " + source + " to " + target); - - final CordovaResourceApi resourceApi = webView.getResourceApi(); - - final String objectId = args.getString(3); - final JSONObject headers = args.optJSONObject(4); - - final Uri sourceUri = resourceApi.remapUri(Uri.parse(source)); - int uriType = CordovaResourceApi.getUriType(sourceUri); - final boolean useHttps = uriType == CordovaResourceApi.URI_TYPE_HTTPS; - final boolean isLocalTransfer = !useHttps && uriType != CordovaResourceApi.URI_TYPE_HTTP; - if (uriType == CordovaResourceApi.URI_TYPE_UNKNOWN) { - JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, null, 0, null); - LOG.e(LOG_TAG, "Unsupported URI: " + sourceUri); - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error)); - return; - } - - /* This code exists for compatibility between 3.x and 4.x versions of Cordova. - * Previously the CordovaWebView class had a method, getWhitelist, which would - * return a Whitelist object. Since the fixed whitelist is removed in Cordova 4.x, - * the correct call now is to shouldAllowRequest from the plugin manager. - */ - Boolean shouldAllowRequest = null; - if (isLocalTransfer) { - shouldAllowRequest = true; - } - if (shouldAllowRequest == null) { - try { - Method gwl = webView.getClass().getMethod("getWhitelist"); - Whitelist whitelist = (Whitelist)gwl.invoke(webView); - shouldAllowRequest = whitelist.isUrlWhiteListed(source); - } catch (NoSuchMethodException e) { - } catch (IllegalAccessException e) { - } catch (InvocationTargetException e) { - } - } - if (shouldAllowRequest == null) { - try { - Method gpm = webView.getClass().getMethod("getPluginManager"); - PluginManager pm = (PluginManager)gpm.invoke(webView); - Method san = pm.getClass().getMethod("shouldAllowRequest", String.class); - shouldAllowRequest = (Boolean)san.invoke(pm, source); - } catch (NoSuchMethodException e) { - } catch (IllegalAccessException e) { - } catch (InvocationTargetException e) { - } - } - - if (!Boolean.TRUE.equals(shouldAllowRequest)) { - LOG.w(LOG_TAG, "Source URL is not in white list: '" + source + "'"); - JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, null, 401, null); - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error)); - return; - } - - - final RequestContext context = new RequestContext(source, target, callbackContext); - synchronized (activeRequests) { - activeRequests.put(objectId, context); - } - - cordova.getThreadPool().execute(new Runnable() { - public void run() { - if (context.aborted) { - return; - } - - // Accept a path or a URI for the source. - Uri tmpTarget = Uri.parse(target); - Uri targetUri = resourceApi.remapUri( - tmpTarget.getScheme() != null ? tmpTarget : Uri.fromFile(new File(target))); - HttpURLConnection connection = null; - File file = null; - PluginResult result = null; - TrackingInputStream inputStream = null; - boolean cached = false; - - OutputStream outputStream = null; - try { - OpenForReadResult readResult = null; - - file = resourceApi.mapUriToFile(targetUri); - context.targetFile = file; - - LOG.d(LOG_TAG, "Download file:" + sourceUri); - - FileProgressResult progress = new FileProgressResult(); - - if (isLocalTransfer) { - readResult = resourceApi.openForRead(sourceUri); - if (readResult.length != -1) { - progress.setLengthComputable(true); - progress.setTotal(readResult.length); - } - inputStream = new SimpleTrackingInputStream(readResult.inputStream); - } else { - // connect to server - // Open a HTTP connection to the URL based on protocol - connection = resourceApi.createHttpConnection(sourceUri); - connection.setRequestMethod("GET"); - - // TODO: Make OkHttp use this CookieManager by default. - String cookie = getCookies(sourceUri.toString()); - - if(cookie != null) - { - connection.setRequestProperty("cookie", cookie); - } - - // This must be explicitly set for gzip progress tracking to work. - connection.setRequestProperty("Accept-Encoding", "gzip"); - - // Handle the other headers - if (headers != null) { - addHeadersToRequest(connection, headers); - } - - connection.connect(); - if (connection.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) { - cached = true; - connection.disconnect(); - LOG.d(LOG_TAG, "Resource not modified: " + source); - JSONObject error = createFileTransferError(NOT_MODIFIED_ERR, source, target, connection, null); - result = new PluginResult(PluginResult.Status.ERROR, error); - } else { - if (connection.getContentEncoding() == null || connection.getContentEncoding().equalsIgnoreCase("gzip")) { - // Only trust content-length header if we understand - // the encoding -- identity or gzip - if (connection.getContentLength() != -1) { - progress.setLengthComputable(true); - progress.setTotal(connection.getContentLength()); - } - } - inputStream = getInputStream(connection); - } - } - - if (!cached) { - try { - synchronized (context) { - if (context.aborted) { - return; - } - context.connection = connection; - } - - // write bytes to file - byte[] buffer = new byte[MAX_BUFFER_SIZE]; - int bytesRead = 0; - outputStream = resourceApi.openOutputStream(targetUri); - while ((bytesRead = inputStream.read(buffer)) > 0) { - outputStream.write(buffer, 0, bytesRead); - // Send a progress event. - progress.setLoaded(inputStream.getTotalRawBytesRead()); - PluginResult progressResult = new PluginResult(PluginResult.Status.OK, progress.toJSONObject()); - progressResult.setKeepCallback(true); - context.sendPluginResult(progressResult); - } - } finally { - synchronized (context) { - context.connection = null; - } - safeClose(inputStream); - safeClose(outputStream); - } - - LOG.d(LOG_TAG, "Saved file: " + target); - - - // create FileEntry object - Class webViewClass = webView.getClass(); - PluginManager pm = null; - try { - Method gpm = webViewClass.getMethod("getPluginManager"); - pm = (PluginManager) gpm.invoke(webView); - } catch (NoSuchMethodException e) { - } catch (IllegalAccessException e) { - } catch (InvocationTargetException e) { - } - if (pm == null) { - try { - Field pmf = webViewClass.getField("pluginManager"); - pm = (PluginManager)pmf.get(webView); - } catch (NoSuchFieldException e) { - } catch (IllegalAccessException e) { - } - } - file = resourceApi.mapUriToFile(targetUri); - context.targetFile = file; - FileUtils filePlugin = (FileUtils) pm.getPlugin("File"); - if (filePlugin != null) { - JSONObject fileEntry = filePlugin.getEntryForFile(file); - if (fileEntry != null) { - result = new PluginResult(PluginResult.Status.OK, fileEntry); - } else { - JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, connection, null); - LOG.e(LOG_TAG, "File plugin cannot represent download path"); - result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error); - } - } else { - LOG.e(LOG_TAG, "File plugin not found; cannot save downloaded file"); - result = new PluginResult(PluginResult.Status.ERROR, "File plugin not found; cannot save downloaded file"); - } - } - } catch (FileNotFoundException e) { - JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, connection, e); - LOG.e(LOG_TAG, error.toString(), e); - result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error); - } catch (IOException e) { - JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, connection, e); - LOG.e(LOG_TAG, error.toString(), e); - result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error); - } catch (JSONException e) { - LOG.e(LOG_TAG, e.getMessage(), e); - result = new PluginResult(PluginResult.Status.JSON_EXCEPTION); - } catch (Throwable e) { - JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, connection, e); - LOG.e(LOG_TAG, error.toString(), e); - result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error); - } finally { - synchronized (activeRequests) { - activeRequests.remove(objectId); - } - - if (result == null) { - result = new PluginResult(PluginResult.Status.ERROR, createFileTransferError(CONNECTION_ERR, source, target, connection, null)); - } - // Remove incomplete download. - if (!cached && result.getStatus() != PluginResult.Status.OK.ordinal() && file != null) { - file.delete(); - } - context.sendPluginResult(result); - } - } - }); - } - - /** - * Abort an ongoing upload or download. - */ - private void abort(String objectId) { - final RequestContext context; - synchronized (activeRequests) { - context = activeRequests.remove(objectId); - } - if (context != null) { - // Closing the streams can block, so execute on a background thread. - cordova.getThreadPool().execute(new Runnable() { - public void run() { - synchronized (context) { - File file = context.targetFile; - if (file != null) { - file.delete(); - } - // Trigger the abort callback immediately to minimize latency between it and abort() being called. - JSONObject error = createFileTransferError(ABORTED_ERR, context.source, context.target, null, -1, null); - context.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, error)); - context.aborted = true; - if (context.connection != null) { - try { - context.connection.disconnect(); - } catch (Exception e) { - LOG.e(LOG_TAG, "CB-8431 Catch workaround for fatal exception", e); - } - } - } - } - }); - } - } -} diff --git a/plugins/cordova-plugin-file-transfer/src/android/FileUploadResult.java b/plugins/cordova-plugin-file-transfer/src/android/FileUploadResult.java deleted file mode 100644 index c24ea78..0000000 --- a/plugins/cordova-plugin-file-transfer/src/android/FileUploadResult.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - 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.filetransfer; - -import org.json.JSONException; -import org.json.JSONObject; - -/** - * Encapsulates the result and/or status of uploading a file to a remote server. - */ -public class FileUploadResult { - - private long bytesSent = 0; // bytes sent - private int responseCode = -1; // HTTP response code - private String response = null; // HTTP response - private String objectId = null; // FileTransfer object id - - public long getBytesSent() { - return bytesSent; - } - - public void setBytesSent(long bytes) { - this.bytesSent = bytes; - } - - public int getResponseCode() { - return responseCode; - } - - public void setResponseCode(int responseCode) { - this.responseCode = responseCode; - } - - public String getResponse() { - return response; - } - - public void setResponse(String response) { - this.response = response; - } - - public String getObjectId() { - return objectId; - } - - public void setObjectId(String objectId) { - this.objectId = objectId; - } - - public JSONObject toJSONObject() throws JSONException { - return new JSONObject( - "{bytesSent:" + bytesSent + - ",responseCode:" + responseCode + - ",response:" + JSONObject.quote(response) + - ",objectId:" + JSONObject.quote(objectId) + "}"); - } -} diff --git a/plugins/cordova-plugin-file-transfer/src/ios/CDVFileTransfer.h b/plugins/cordova-plugin-file-transfer/src/ios/CDVFileTransfer.h deleted file mode 100644 index b7301ef..0000000 --- a/plugins/cordova-plugin-file-transfer/src/ios/CDVFileTransfer.h +++ /dev/null @@ -1,89 +0,0 @@ -/* - 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 "CDVFile.h" - -enum CDVFileTransferError { - FILE_NOT_FOUND_ERR = 1, - INVALID_URL_ERR = 2, - CONNECTION_ERR = 3, - CONNECTION_ABORTED = 4, - NOT_MODIFIED = 5 -}; -typedef int CDVFileTransferError; - -enum CDVFileTransferDirection { - CDV_TRANSFER_UPLOAD = 1, - CDV_TRANSFER_DOWNLOAD = 2, -}; -typedef int CDVFileTransferDirection; - -// Magic value within the options dict used to set a cookie. -extern NSString* const kOptionsKeyCookie; - -@interface CDVFileTransfer : CDVPlugin {} - -- (void)upload:(CDVInvokedUrlCommand*)command; -- (void)download:(CDVInvokedUrlCommand*)command; -- (NSString*)escapePathComponentForUrlString:(NSString*)urlString; - -// Visible for testing. -- (NSURLRequest*)requestForUploadCommand:(CDVInvokedUrlCommand*)command fileData:(NSData*)fileData; -- (NSMutableDictionary*)createFileTransferError:(int)code AndSource:(NSString*)source AndTarget:(NSString*)target; - -- (NSMutableDictionary*)createFileTransferError:(int)code - AndSource:(NSString*)source - AndTarget:(NSString*)target - AndHttpStatus:(int)httpStatus - AndBody:(NSString*)body; -@property (nonatomic, strong) NSOperationQueue* queue; -@property (readonly) NSMutableDictionary* activeTransfers; -@end - -@class CDVFileTransferEntityLengthRequest; - -@interface CDVFileTransferDelegate : NSObject {} - -- (void)updateBytesExpected:(long long)newBytesExpected; -- (void)cancelTransfer:(NSURLConnection*)connection; - -@property (strong) NSMutableData* responseData; // atomic -@property (nonatomic, strong) NSDictionary* responseHeaders; -@property (nonatomic, assign) UIBackgroundTaskIdentifier backgroundTaskID; -@property (nonatomic, strong) CDVFileTransfer* command; -@property (nonatomic, assign) CDVFileTransferDirection direction; -@property (nonatomic, strong) NSURLConnection* connection; -@property (nonatomic, copy) NSString* callbackId; -@property (nonatomic, copy) NSString* objectId; -@property (nonatomic, copy) NSString* source; -@property (nonatomic, copy) NSString* target; -@property (nonatomic, copy) NSURL* targetURL; -@property (nonatomic, copy) NSString* mimeType; -@property (assign) int responseCode; // atomic -@property (nonatomic, assign) long long bytesTransfered; -@property (nonatomic, assign) long long bytesExpected; -@property (nonatomic, assign) BOOL trustAllHosts; -@property (strong) NSFileHandle* targetFileHandle; -@property (nonatomic, strong) CDVFileTransferEntityLengthRequest* entityLengthRequest; -@property (nonatomic, strong) CDVFile *filePlugin; -@property (nonatomic, assign) BOOL chunkedMode; - -@end diff --git a/plugins/cordova-plugin-file-transfer/src/ios/CDVFileTransfer.m b/plugins/cordova-plugin-file-transfer/src/ios/CDVFileTransfer.m deleted file mode 100644 index d0584ad..0000000 --- a/plugins/cordova-plugin-file-transfer/src/ios/CDVFileTransfer.m +++ /dev/null @@ -1,861 +0,0 @@ -/* - 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 "CDVFileTransfer.h" -#import "CDVLocalFilesystem.h" - -#import -#import -#import -#import - -#ifndef DLog -#ifdef DEBUG - #define DLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__) -#else - #define DLog(...) -#endif -#endif - -@interface CDVFileTransfer () -// Sets the requests headers for the request. -- (void)applyRequestHeaders:(NSDictionary*)headers toRequest:(NSMutableURLRequest*)req; -// Creates a delegate to handle an upload. -- (CDVFileTransferDelegate*)delegateForUploadCommand:(CDVInvokedUrlCommand*)command; -// Creates an NSData* for the file for the given upload arguments. -- (void)fileDataForUploadCommand:(CDVInvokedUrlCommand*)command; -@end - -// Buffer size to use for streaming uploads. -static const NSUInteger kStreamBufferSize = 32768; -// Magic value within the options dict used to set a cookie. -NSString* const kOptionsKeyCookie = @"__cookie"; -// Form boundary for multi-part requests. -NSString* const kFormBoundary = @"+++++org.apache.cordova.formBoundary"; - -// Writes the given data to the stream in a blocking way. -// If successful, returns bytesToWrite. -// If the stream was closed on the other end, returns 0. -// If there was an error, returns -1. -static CFIndex WriteDataToStream(NSData* data, CFWriteStreamRef stream) -{ - UInt8* bytes = (UInt8*)[data bytes]; - long long bytesToWrite = [data length]; - long long totalBytesWritten = 0; - - while (totalBytesWritten < bytesToWrite) { - CFIndex result = CFWriteStreamWrite(stream, - bytes + totalBytesWritten, - bytesToWrite - totalBytesWritten); - if (result < 0) { - CFStreamError error = CFWriteStreamGetError(stream); - NSLog(@"WriteStreamError domain: %ld error: %ld", error.domain, (long)error.error); - return result; - } else if (result == 0) { - return result; - } - totalBytesWritten += result; - } - - return totalBytesWritten; -} - -@implementation CDVFileTransfer -@synthesize activeTransfers; - -- (void)pluginInitialize { - activeTransfers = [[NSMutableDictionary alloc] init]; -} - -- (NSString*)escapePathComponentForUrlString:(NSString*)urlString -{ - NSRange schemeAndHostRange = [urlString rangeOfString:@"://.*?/" options:NSRegularExpressionSearch]; - - if (schemeAndHostRange.length == 0) { - return urlString; - } - - NSInteger schemeAndHostEndIndex = NSMaxRange(schemeAndHostRange); - NSString* schemeAndHost = [urlString substringToIndex:schemeAndHostEndIndex]; - NSString* pathComponent = [urlString substringFromIndex:schemeAndHostEndIndex]; - pathComponent = [pathComponent stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; - - return [schemeAndHost stringByAppendingString:pathComponent]; -} - -- (void)applyRequestHeaders:(NSDictionary*)headers toRequest:(NSMutableURLRequest*)req -{ - [req setValue:@"XMLHttpRequest" forHTTPHeaderField:@"X-Requested-With"]; - - NSString* userAgent = [self.commandDelegate userAgent]; - if (userAgent) { - [req setValue:userAgent forHTTPHeaderField:@"User-Agent"]; - } - - for (NSString* headerName in headers) { - id value = [headers objectForKey:headerName]; - if (!value || (value == [NSNull null])) { - value = @"null"; - } - - // First, remove an existing header if one exists. - [req setValue:nil forHTTPHeaderField:headerName]; - - if (![value isKindOfClass:[NSArray class]]) { - value = [NSArray arrayWithObject:value]; - } - - // Then, append all header values. - for (id __strong subValue in value) { - // Convert from an NSNumber -> NSString. - if ([subValue respondsToSelector:@selector(stringValue)]) { - subValue = [subValue stringValue]; - } - if ([subValue isKindOfClass:[NSString class]]) { - [req addValue:subValue forHTTPHeaderField:headerName]; - } - } - } -} - -- (NSURLRequest*)requestForUploadCommand:(CDVInvokedUrlCommand*)command fileData:(NSData*)fileData -{ - // arguments order from js: [filePath, server, fileKey, fileName, mimeType, params, debug, chunkedMode] - // however, params is a JavaScript object and during marshalling is put into the options dict, - // thus debug and chunkedMode are the 6th and 7th arguments - NSString* target = [command argumentAtIndex:0]; - NSString* server = [command argumentAtIndex:1]; - NSString* fileKey = [command argumentAtIndex:2 withDefault:@"file"]; - NSString* fileName = [command argumentAtIndex:3 withDefault:@"image.jpg"]; - NSString* mimeType = [command argumentAtIndex:4 withDefault:@"image/jpeg"]; - NSDictionary* options = [command argumentAtIndex:5 withDefault:nil]; - // BOOL trustAllHosts = [[command argumentAtIndex:6 withDefault:[NSNumber numberWithBool:YES]] boolValue]; // allow self-signed certs - BOOL chunkedMode = [[command argumentAtIndex:7 withDefault:[NSNumber numberWithBool:YES]] boolValue]; - NSDictionary* headers = [command argumentAtIndex:8 withDefault:nil]; - // Allow alternative http method, default to POST. JS side checks - // for allowed methods, currently PUT or POST (forces POST for - // unrecognised values) - NSString* httpMethod = [command argumentAtIndex:10 withDefault:@"POST"]; - CDVPluginResult* result = nil; - CDVFileTransferError errorCode = 0; - - // NSURL does not accepts URLs with spaces in the path. We escape the path in order - // to be more lenient. - NSURL* url = [NSURL URLWithString:server]; - - if (!url) { - errorCode = INVALID_URL_ERR; - NSLog(@"File Transfer Error: Invalid server URL %@", server); - } else if (!fileData) { - errorCode = FILE_NOT_FOUND_ERR; - } - - if (errorCode > 0) { - result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:[self createFileTransferError:errorCode AndSource:target AndTarget:server]]; - [self.commandDelegate sendPluginResult:result callbackId:command.callbackId]; - return nil; - } - - NSMutableURLRequest* req = [NSMutableURLRequest requestWithURL:url]; - - [req setHTTPMethod:httpMethod]; - - // Magic value to set a cookie - if ([options objectForKey:kOptionsKeyCookie]) { - [req setValue:[options objectForKey:kOptionsKeyCookie] forHTTPHeaderField:@"Cookie"]; - [req setHTTPShouldHandleCookies:NO]; - } - - // if we specified a Content-Type header, don't do multipart form upload - BOOL multipartFormUpload = [headers objectForKey:@"Content-Type"] == nil; - if (multipartFormUpload) { - NSString* contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", kFormBoundary]; - [req setValue:contentType forHTTPHeaderField:@"Content-Type"]; - } - [self applyRequestHeaders:headers toRequest:req]; - - NSData* formBoundaryData = [[NSString stringWithFormat:@"--%@\r\n", kFormBoundary] dataUsingEncoding:NSUTF8StringEncoding]; - NSMutableData* postBodyBeforeFile = [NSMutableData data]; - - for (NSString* key in options) { - id val = [options objectForKey:key]; - if (!val || (val == [NSNull null]) || [key isEqualToString:kOptionsKeyCookie]) { - continue; - } - // if it responds to stringValue selector (eg NSNumber) get the NSString - if ([val respondsToSelector:@selector(stringValue)]) { - val = [val stringValue]; - } - // finally, check whether it is a NSString (for dataUsingEncoding selector below) - if (![val isKindOfClass:[NSString class]]) { - continue; - } - - [postBodyBeforeFile appendData:formBoundaryData]; - [postBodyBeforeFile appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", key] dataUsingEncoding:NSUTF8StringEncoding]]; - [postBodyBeforeFile appendData:[val dataUsingEncoding:NSUTF8StringEncoding]]; - [postBodyBeforeFile appendData:[@"\r\n" dataUsingEncoding : NSUTF8StringEncoding]]; - } - - [postBodyBeforeFile appendData:formBoundaryData]; - [postBodyBeforeFile appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", fileKey, fileName] dataUsingEncoding:NSUTF8StringEncoding]]; - if (mimeType != nil) { - [postBodyBeforeFile appendData:[[NSString stringWithFormat:@"Content-Type: %@\r\n", mimeType] dataUsingEncoding:NSUTF8StringEncoding]]; - } - [postBodyBeforeFile appendData:[[NSString stringWithFormat:@"Content-Length: %ld\r\n\r\n", (long)[fileData length]] dataUsingEncoding:NSUTF8StringEncoding]]; - - DLog(@"fileData length: %ld", [fileData length]); - NSData* postBodyAfterFile = [[NSString stringWithFormat:@"\r\n--%@--\r\n", kFormBoundary] dataUsingEncoding:NSUTF8StringEncoding]; - - long long totalPayloadLength = [fileData length]; - if (multipartFormUpload) { - totalPayloadLength += [postBodyBeforeFile length] + [postBodyAfterFile length]; - } - - [req setValue:[[NSNumber numberWithLongLong:totalPayloadLength] stringValue] forHTTPHeaderField:@"Content-Length"]; - - if (chunkedMode) { - CFReadStreamRef readStream = NULL; - CFWriteStreamRef writeStream = NULL; - CFStreamCreateBoundPair(NULL, &readStream, &writeStream, kStreamBufferSize); - [req setHTTPBodyStream:CFBridgingRelease(readStream)]; - - [self.commandDelegate runInBackground:^{ - if (CFWriteStreamOpen(writeStream)) { - if (multipartFormUpload) { - NSData* chunks[] = { postBodyBeforeFile, fileData, postBodyAfterFile }; - int numChunks = sizeof(chunks) / sizeof(chunks[0]); - - for (int i = 0; i < numChunks; ++i) { - // Allow uploading of an empty file - if (chunks[i].length == 0) { - continue; - } - - CFIndex result = WriteDataToStream(chunks[i], writeStream); - if (result <= 0) { - break; - } - } - } else { - if (totalPayloadLength > 0) { - WriteDataToStream(fileData, writeStream); - } else { - NSLog(@"Uploading of an empty file is not supported for chunkedMode=true and multipart=false"); - } - } - } else { - NSLog(@"FileTransfer: Failed to open writeStream"); - } - CFWriteStreamClose(writeStream); - CFRelease(writeStream); - }]; - } else { - if (multipartFormUpload) { - [postBodyBeforeFile appendData:fileData]; - [postBodyBeforeFile appendData:postBodyAfterFile]; - [req setHTTPBody:postBodyBeforeFile]; - } else { - [req setHTTPBody:fileData]; - } - } - return req; -} - -- (CDVFileTransferDelegate*)delegateForUploadCommand:(CDVInvokedUrlCommand*)command -{ - NSString* source = [command argumentAtIndex:0]; - NSString* server = [command argumentAtIndex:1]; - BOOL trustAllHosts = [[command argumentAtIndex:6 withDefault:[NSNumber numberWithBool:NO]] boolValue]; // allow self-signed certs - NSString* objectId = [command argumentAtIndex:9]; - BOOL chunkedMode = [[command argumentAtIndex:7 withDefault:[NSNumber numberWithBool:YES]] boolValue]; - - CDVFileTransferDelegate* delegate = [[CDVFileTransferDelegate alloc] init]; - - delegate.command = self; - delegate.callbackId = command.callbackId; - delegate.direction = CDV_TRANSFER_UPLOAD; - delegate.objectId = objectId; - delegate.source = source; - delegate.target = server; - delegate.trustAllHosts = trustAllHosts; - delegate.filePlugin = [self.commandDelegate getCommandInstance:@"File"]; - delegate.chunkedMode = chunkedMode; - - return delegate; -} - -- (void)fileDataForUploadCommand:(CDVInvokedUrlCommand*)command -{ - NSString* source = (NSString*)[command argumentAtIndex:0]; - NSString* server = [command argumentAtIndex:1]; - NSError* __autoreleasing err = nil; - - if ([source hasPrefix:@"data:"] && [source rangeOfString:@"base64"].location != NSNotFound) { - NSRange commaRange = [source rangeOfString: @","]; - if (commaRange.location == NSNotFound) { - // Return error is there is no comma - __weak CDVFileTransfer* weakSelf = self; - CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:[weakSelf createFileTransferError:INVALID_URL_ERR AndSource:source AndTarget:server]]; - [weakSelf.commandDelegate sendPluginResult:result callbackId:command.callbackId]; - return; - } - - if (commaRange.location + 1 > source.length - 1) { - // Init as an empty data - NSData *fileData = [[NSData alloc] init]; - [self uploadData:fileData command:command]; - return; - } - - NSData *fileData = [[NSData alloc] initWithBase64EncodedString:[source substringFromIndex:(commaRange.location + 1)] options:NSDataBase64DecodingIgnoreUnknownCharacters]; - [self uploadData:fileData command:command]; - return; - } - - CDVFilesystemURL *sourceURL = [CDVFilesystemURL fileSystemURLWithString:source]; - NSObject *fs; - if (sourceURL) { - // Try to get a CDVFileSystem which will handle this file. - // This requires talking to the current CDVFile plugin. - fs = [[self.commandDelegate getCommandInstance:@"File"] filesystemForURL:sourceURL]; - } - if (fs) { - __weak CDVFileTransfer* weakSelf = self; - [fs readFileAtURL:sourceURL start:0 end:-1 callback:^(NSData *fileData, NSString *mimeType, CDVFileError err) { - if (err) { - // We couldn't find the asset. Send the appropriate error. - CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:[weakSelf createFileTransferError:NOT_FOUND_ERR AndSource:source AndTarget:server]]; - [weakSelf.commandDelegate sendPluginResult:result callbackId:command.callbackId]; - } else { - [weakSelf uploadData:fileData command:command]; - } - }]; - return; - } else { - // Extract the path part out of a file: URL. - NSString* filePath = [source hasPrefix:@"/"] ? [source copy] : [(NSURL *)[NSURL URLWithString:source] path]; - if (filePath == nil) { - // We couldn't find the asset. Send the appropriate error. - CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:[self createFileTransferError:NOT_FOUND_ERR AndSource:source AndTarget:server]]; - [self.commandDelegate sendPluginResult:result callbackId:command.callbackId]; - return; - } - - // Memory map the file so that it can be read efficiently even if it is large. - NSData* fileData = [NSData dataWithContentsOfFile:filePath options:NSDataReadingMappedIfSafe error:&err]; - - if (err != nil) { - NSLog(@"Error opening file %@: %@", source, err); - CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:[self createFileTransferError:NOT_FOUND_ERR AndSource:source AndTarget:server]]; - [self.commandDelegate sendPluginResult:result callbackId:command.callbackId]; - } else { - [self uploadData:fileData command:command]; - } - } -} - -- (void)upload:(CDVInvokedUrlCommand*)command -{ - // fileData and req are split into helper functions to ease the unit testing of delegateForUpload. - // First, get the file data. This method will call `uploadData:command`. - [self fileDataForUploadCommand:command]; -} - -- (void)uploadData:(NSData*)fileData command:(CDVInvokedUrlCommand*)command -{ - NSURLRequest* req = [self requestForUploadCommand:command fileData:fileData]; - - if (req == nil) { - return; - } - CDVFileTransferDelegate* delegate = [self delegateForUploadCommand:command]; - delegate.connection = [[NSURLConnection alloc] initWithRequest:req delegate:delegate startImmediately:NO]; - if (self.queue == nil) { - self.queue = [[NSOperationQueue alloc] init]; - } - [delegate.connection setDelegateQueue:self.queue]; - - // sets a background task ID for the transfer object. - delegate.backgroundTaskID = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{ - [delegate cancelTransfer:delegate.connection]; - }]; - - @synchronized (activeTransfers) { - activeTransfers[delegate.objectId] = delegate; - } - [delegate.connection start]; -} - -- (void)abort:(CDVInvokedUrlCommand*)command -{ - NSString* objectId = [command argumentAtIndex:0]; - - @synchronized (activeTransfers) { - CDVFileTransferDelegate* delegate = activeTransfers[objectId]; - if (delegate != nil) { - [delegate cancelTransfer:delegate.connection]; - CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:[self createFileTransferError:CONNECTION_ABORTED AndSource:delegate.source AndTarget:delegate.target]]; - [self.commandDelegate sendPluginResult:result callbackId:delegate.callbackId]; - } - } -} - -- (void)download:(CDVInvokedUrlCommand*)command -{ - DLog(@"File Transfer downloading file..."); - NSString* source = [command argumentAtIndex:0]; - NSString* target = [command argumentAtIndex:1]; - BOOL trustAllHosts = [[command argumentAtIndex:2 withDefault:[NSNumber numberWithBool:NO]] boolValue]; // allow self-signed certs - NSString* objectId = [command argumentAtIndex:3]; - NSDictionary* headers = [command argumentAtIndex:4 withDefault:nil]; - - CDVPluginResult* result = nil; - CDVFileTransferError errorCode = 0; - - NSURL* targetURL; - - if ([target hasPrefix:@"/"]) { - /* Backwards-compatibility: - * Check here to see if it looks like the user passed in a raw filesystem path. (Perhaps they had the path saved, and were previously using it with the old version of File). If so, normalize it by removing empty path segments, and check with File to see if any of the installed filesystems will handle it. If so, then we will end up with a filesystem url to use for the remainder of this operation. - */ - target = [target stringByReplacingOccurrencesOfString:@"//" withString:@"/"]; - targetURL = [[self.commandDelegate getCommandInstance:@"File"] fileSystemURLforLocalPath:target].url; - } else { - targetURL = [NSURL URLWithString:target]; - - if (targetURL == nil) { - NSString* targetUrlTextEscaped = [target stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]]; - if (targetUrlTextEscaped) { - targetURL = [NSURL URLWithString:targetUrlTextEscaped]; - } - } - } - - NSURL* sourceURL = [NSURL URLWithString:source]; - - if (!sourceURL) { - errorCode = INVALID_URL_ERR; - NSLog(@"File Transfer Error: Invalid server URL %@", source); - } else if (!targetURL) { - errorCode = INVALID_URL_ERR; - NSLog(@"File Tranfer Error: Invalid target URL %@", target); - } else if (![targetURL isFileURL]) { - CDVFilesystemURL *fsURL = [CDVFilesystemURL fileSystemURLWithString:target]; - if (!fsURL) { - errorCode = FILE_NOT_FOUND_ERR; - NSLog(@"File Transfer Error: Invalid file path or URL %@", target); - } - } - - if (errorCode > 0) { - result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:[self createFileTransferError:errorCode AndSource:source AndTarget:target]]; - [self.commandDelegate sendPluginResult:result callbackId:command.callbackId]; - return; - } - - NSMutableURLRequest* req = [NSMutableURLRequest requestWithURL:sourceURL]; - [self applyRequestHeaders:headers toRequest:req]; - - CDVFileTransferDelegate* delegate = [[CDVFileTransferDelegate alloc] init]; - delegate.command = self; - delegate.direction = CDV_TRANSFER_DOWNLOAD; - delegate.callbackId = command.callbackId; - delegate.objectId = objectId; - delegate.source = source; - delegate.target = [targetURL absoluteString]; - delegate.targetURL = targetURL; - delegate.trustAllHosts = trustAllHosts; - delegate.filePlugin = [self.commandDelegate getCommandInstance:@"File"]; - delegate.backgroundTaskID = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{ - [delegate cancelTransfer:delegate.connection]; - }]; - - delegate.connection = [[NSURLConnection alloc] initWithRequest:req delegate:delegate startImmediately:NO]; - - if (self.queue == nil) { - self.queue = [[NSOperationQueue alloc] init]; - } - [delegate.connection setDelegateQueue:self.queue]; - - @synchronized (activeTransfers) { - activeTransfers[delegate.objectId] = delegate; - } - // Downloads can take time - // sending this to a new thread calling the download_async method - dispatch_async( - dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, (unsigned long)NULL), - ^(void) { [delegate.connection start];} - ); -} - -- (NSMutableDictionary*)createFileTransferError:(int)code AndSource:(NSString*)source AndTarget:(NSString*)target -{ - NSMutableDictionary* result = [NSMutableDictionary dictionaryWithCapacity:3]; - - [result setObject:[NSNumber numberWithInt:code] forKey:@"code"]; - if (source != nil) { - [result setObject:source forKey:@"source"]; - } - if (target != nil) { - [result setObject:target forKey:@"target"]; - } - NSLog(@"FileTransferError %@", result); - - return result; -} - -- (NSMutableDictionary*)createFileTransferError:(int)code - AndSource:(NSString*)source - AndTarget:(NSString*)target - AndHttpStatus:(int)httpStatus - AndBody:(NSString*)body -{ - NSMutableDictionary* result = [NSMutableDictionary dictionaryWithCapacity:5]; - - [result setObject:[NSNumber numberWithInt:code] forKey:@"code"]; - if (source != nil) { - [result setObject:source forKey:@"source"]; - } - if (target != nil) { - [result setObject:target forKey:@"target"]; - } - [result setObject:[NSNumber numberWithInt:httpStatus] forKey:@"http_status"]; - if (body != nil) { - [result setObject:body forKey:@"body"]; - } - NSLog(@"FileTransferError %@", result); - - return result; -} - -- (void)onReset { - @synchronized (activeTransfers) { - while ([activeTransfers count] > 0) { - CDVFileTransferDelegate* delegate = [activeTransfers allValues][0]; - [delegate cancelTransfer:delegate.connection]; - } - } -} - -@end - -@interface CDVFileTransferEntityLengthRequest : NSObject { - NSURLConnection* _connection; - CDVFileTransferDelegate* __weak _originalDelegate; -} - -- (CDVFileTransferEntityLengthRequest*)initWithOriginalRequest:(NSURLRequest*)originalRequest andDelegate:(CDVFileTransferDelegate*)originalDelegate; - -@end - -@implementation CDVFileTransferEntityLengthRequest - -- (CDVFileTransferEntityLengthRequest*)initWithOriginalRequest:(NSURLRequest*)originalRequest andDelegate:(CDVFileTransferDelegate*)originalDelegate -{ - if (self) { - DLog(@"Requesting entity length for GZIPped content..."); - - NSMutableURLRequest* req = [originalRequest mutableCopy]; - [req setHTTPMethod:@"HEAD"]; - [req setValue:@"identity" forHTTPHeaderField:@"Accept-Encoding"]; - - _originalDelegate = originalDelegate; - _connection = [NSURLConnection connectionWithRequest:req delegate:self]; - } - return self; -} - -- (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response -{ - DLog(@"HEAD request returned; content-length is %lld", [response expectedContentLength]); - [_originalDelegate updateBytesExpected:[response expectedContentLength]]; -} - -- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data -{} - -- (void)connectionDidFinishLoading:(NSURLConnection*)connection -{} - -@end - -@implementation CDVFileTransferDelegate - -@synthesize callbackId, connection = _connection, source, target, responseData, responseHeaders, command, bytesTransfered, bytesExpected, direction, responseCode, objectId, targetFileHandle, filePlugin; - -- (void)connectionDidFinishLoading:(NSURLConnection*)connection -{ - NSString* uploadResponse = nil; - NSString* downloadResponse = nil; - NSMutableDictionary* uploadResult; - CDVPluginResult* result = nil; - - NSLog(@"File Transfer Finished with response code %d", self.responseCode); - - if (self.direction == CDV_TRANSFER_UPLOAD) { - uploadResponse = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding]; - if (uploadResponse == nil) { - uploadResponse = [[NSString alloc] initWithData: self.responseData encoding:NSISOLatin1StringEncoding]; - } - - if ((self.responseCode >= 200) && (self.responseCode < 300)) { - // create dictionary to return FileUploadResult object - uploadResult = [NSMutableDictionary dictionaryWithCapacity:3]; - if (uploadResponse != nil) { - [uploadResult setObject:uploadResponse forKey:@"response"]; - [uploadResult setObject:self.responseHeaders forKey:@"headers"]; - } - [uploadResult setObject:[NSNumber numberWithLongLong:self.bytesTransfered] forKey:@"bytesSent"]; - [uploadResult setObject:[NSNumber numberWithInt:self.responseCode] forKey:@"responseCode"]; - result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:uploadResult]; - } else { - result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:[command createFileTransferError:CONNECTION_ERR AndSource:source AndTarget:target AndHttpStatus:self.responseCode AndBody:uploadResponse]]; - } - } - if (self.direction == CDV_TRANSFER_DOWNLOAD) { - if (self.targetFileHandle) { - [self.targetFileHandle closeFile]; - self.targetFileHandle = nil; - DLog(@"File Transfer Download success"); - - result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:[self.filePlugin makeEntryForURL:self.targetURL]]; - } else { - downloadResponse = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding]; - if (downloadResponse == nil) { - downloadResponse = [[NSString alloc] initWithData: self.responseData encoding:NSISOLatin1StringEncoding]; - } - - CDVFileTransferError errorCode = self.responseCode == 404 ? FILE_NOT_FOUND_ERR - : (self.responseCode == 304 ? NOT_MODIFIED : CONNECTION_ERR); - result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:[command createFileTransferError:errorCode AndSource:source AndTarget:target AndHttpStatus:self.responseCode AndBody:downloadResponse]]; - } - } - - [self.command.commandDelegate sendPluginResult:result callbackId:callbackId]; - - // remove connection for activeTransfers - @synchronized (command.activeTransfers) { - [command.activeTransfers removeObjectForKey:objectId]; - // remove background id task in case our upload was done in the background - [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskID]; - self.backgroundTaskID = UIBackgroundTaskInvalid; - } -} - -- (void)removeTargetFile -{ - NSFileManager* fileMgr = [NSFileManager defaultManager]; - - NSString *targetPath = [self targetFilePath]; - if ([fileMgr fileExistsAtPath:targetPath]) - { - [fileMgr removeItemAtPath:targetPath error:nil]; - } -} - -- (void)cancelTransfer:(NSURLConnection*)connection -{ - [connection cancel]; - @synchronized (self.command.activeTransfers) { - CDVFileTransferDelegate* delegate = self.command.activeTransfers[self.objectId]; - [self.command.activeTransfers removeObjectForKey:self.objectId]; - [[UIApplication sharedApplication] endBackgroundTask:delegate.backgroundTaskID]; - delegate.backgroundTaskID = UIBackgroundTaskInvalid; - } - - if (self.direction == CDV_TRANSFER_DOWNLOAD) { - [self removeTargetFile]; - } -} - -- (void)cancelTransferWithError:(NSURLConnection*)connection errorMessage:(NSString*)errorMessage -{ - CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsDictionary:[self.command createFileTransferError:FILE_NOT_FOUND_ERR AndSource:self.source AndTarget:self.target AndHttpStatus:self.responseCode AndBody:errorMessage]]; - - NSLog(@"File Transfer Error: %@", errorMessage); - [self cancelTransfer:connection]; - [self.command.commandDelegate sendPluginResult:result callbackId:callbackId]; -} - -- (NSString *)targetFilePath -{ - NSString *path = nil; - CDVFilesystemURL *sourceURL = [CDVFilesystemURL fileSystemURLWithString:self.target]; - if (sourceURL && sourceURL.fileSystemName != nil) { - // This requires talking to the current CDVFile plugin - NSObject *fs = [self.filePlugin filesystemForURL:sourceURL]; - path = [fs filesystemPathForURL:sourceURL]; - } else { - // Extract the path part out of a file: URL. - path = [self.target hasPrefix:@"/"] ? [self.target copy] : [(NSURL *)[NSURL URLWithString:self.target] path]; - } - return path; -} - -- (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response -{ - NSError* __autoreleasing error = nil; - - self.mimeType = [response MIMEType]; - self.targetFileHandle = nil; - - // required for iOS 4.3, for some reason; response is - // a plain NSURLResponse, not the HTTP subclass - if ([response isKindOfClass:[NSHTTPURLResponse class]]) { - NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response; - - self.responseCode = (int)[httpResponse statusCode]; - self.bytesExpected = [response expectedContentLength]; - self.responseHeaders = [httpResponse allHeaderFields]; - if ((self.direction == CDV_TRANSFER_DOWNLOAD) && (self.responseCode == 200) && (self.bytesExpected == NSURLResponseUnknownLength)) { - // Kick off HEAD request to server to get real length - // bytesExpected will be updated when that response is returned - self.entityLengthRequest = [[CDVFileTransferEntityLengthRequest alloc] initWithOriginalRequest:connection.currentRequest andDelegate:self]; - } - } else if ([response.URL isFileURL]) { - NSDictionary* attr = [[NSFileManager defaultManager] attributesOfItemAtPath:[response.URL path] error:nil]; - self.responseCode = 200; - self.bytesExpected = [attr[NSFileSize] longLongValue]; - } else { - self.responseCode = 200; - self.bytesExpected = NSURLResponseUnknownLength; - } - if ((self.direction == CDV_TRANSFER_DOWNLOAD) && (self.responseCode >= 200) && (self.responseCode < 300)) { - // Download response is okay; begin streaming output to file - NSString *filePath = [self targetFilePath]; - if (filePath == nil) { - // We couldn't find the asset. Send the appropriate error. - [self cancelTransferWithError:connection errorMessage:[NSString stringWithFormat:@"Could not create target file"]]; - return; - } - - NSString* parentPath = [filePath stringByDeletingLastPathComponent]; - - // create parent directories if needed - if ([[NSFileManager defaultManager] createDirectoryAtPath:parentPath withIntermediateDirectories:YES attributes:nil error:&error] == NO) { - if (error) { - [self cancelTransferWithError:connection errorMessage:[NSString stringWithFormat:@"Could not create path to save downloaded file: %@", [error localizedDescription]]]; - } else { - [self cancelTransferWithError:connection errorMessage:@"Could not create path to save downloaded file"]; - } - return; - } - // create target file - if ([[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil] == NO) { - [self cancelTransferWithError:connection errorMessage:@"Could not create target file"]; - return; - } - // open target file for writing - self.targetFileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath]; - if (self.targetFileHandle == nil) { - [self cancelTransferWithError:connection errorMessage:@"Could not open target file for writing"]; - } - DLog(@"Streaming to file %@", filePath); - } -} - -- (void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error -{ - NSString* body = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding]; - CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:[command createFileTransferError:CONNECTION_ERR AndSource:source AndTarget:target AndHttpStatus:self.responseCode AndBody:body]]; - - NSLog(@"File Transfer Error: %@", [error localizedDescription]); - - [self cancelTransfer:connection]; - [self.command.commandDelegate sendPluginResult:result callbackId:callbackId]; -} - -- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data -{ - self.bytesTransfered += data.length; - if (self.targetFileHandle) { - [self.targetFileHandle writeData:data]; - } else { - [self.responseData appendData:data]; - } - [self updateProgress]; -} - -- (void)updateBytesExpected:(long long)newBytesExpected -{ - DLog(@"Updating bytesExpected to %lld", newBytesExpected); - self.bytesExpected = newBytesExpected; - [self updateProgress]; -} - -- (void)updateProgress -{ - if (self.direction == CDV_TRANSFER_DOWNLOAD) { - BOOL lengthComputable = (self.bytesExpected != NSURLResponseUnknownLength); - // If the response is GZipped, and we have an outstanding HEAD request to get - // the length, then hold off on sending progress events. - if (!lengthComputable && (self.entityLengthRequest != nil)) { - return; - } - NSMutableDictionary* downloadProgress = [NSMutableDictionary dictionaryWithCapacity:3]; - [downloadProgress setObject:[NSNumber numberWithBool:lengthComputable] forKey:@"lengthComputable"]; - [downloadProgress setObject:[NSNumber numberWithLongLong:self.bytesTransfered] forKey:@"loaded"]; - [downloadProgress setObject:[NSNumber numberWithLongLong:self.bytesExpected] forKey:@"total"]; - CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:downloadProgress]; - [result setKeepCallbackAsBool:true]; - [self.command.commandDelegate sendPluginResult:result callbackId:callbackId]; - } -} - -- (void)connection:(NSURLConnection*)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite -{ - if (self.direction == CDV_TRANSFER_UPLOAD) { - NSMutableDictionary* uploadProgress = [NSMutableDictionary dictionaryWithCapacity:3]; - - [uploadProgress setObject:[NSNumber numberWithBool:true] forKey:@"lengthComputable"]; - [uploadProgress setObject:[NSNumber numberWithLongLong:totalBytesWritten] forKey:@"loaded"]; - [uploadProgress setObject:[NSNumber numberWithLongLong:totalBytesExpectedToWrite] forKey:@"total"]; - CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:uploadProgress]; - [result setKeepCallbackAsBool:true]; - [self.command.commandDelegate sendPluginResult:result callbackId:callbackId]; - } - self.bytesTransfered = totalBytesWritten; -} - -// for self signed certificates -- (void)connection:(NSURLConnection*)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge*)challenge -{ - if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) { - if (self.trustAllHosts) { - NSURLCredential* credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]; - [challenge.sender useCredential:credential forAuthenticationChallenge:challenge]; - } - [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge]; - } else { - [challenge.sender performDefaultHandlingForAuthenticationChallenge:challenge]; - } -} - -- (id)init -{ - if ((self = [super init])) { - self.responseData = [NSMutableData data]; - self.targetFileHandle = nil; - } - return self; -} - -@end diff --git a/plugins/cordova-plugin-file-transfer/src/ubuntu/file-transfer.cpp b/plugins/cordova-plugin-file-transfer/src/ubuntu/file-transfer.cpp deleted file mode 100644 index 5b1adea..0000000 --- a/plugins/cordova-plugin-file-transfer/src/ubuntu/file-transfer.cpp +++ /dev/null @@ -1,265 +0,0 @@ -/* - * - * Copyright 2013 Canonical Ltd. - * - * 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-transfer.h" -#include -#include - -static void SetHeaders(QNetworkRequest &request, const QVariantMap &headers) { - for (const QString &key: headers.keys()) { - QVariant val = *headers.find(key); - QString value = val.toString(); - if (val.userType() == QMetaType::QVariantList || val.userType() == QMetaType::QStringList) { - QList list = val.toList(); - for (QVariant v: list) { - if (value.size()) - value += ", "; - value += v.toString(); - } - } - request.setRawHeader(key.toUtf8(), value.toUtf8()); - } -} - -void FileTransfer::download(int scId, int ecId, const QString& url, const QString &target, bool /*trustAllHost*/, int id, const QVariantMap &headers) { - QSharedPointer request(new FileTransferRequest(_manager, scId, ecId, id, this)); - - assert(_id2request.find(id) == _id2request.end()); - - _id2request.insert(id, request); - - request->connect(request.data(), &FileTransferRequest::done, [&]() { - auto it = _id2request.find(id); - while (it != _id2request.end() && it.key() == id) { - if (it.value().data() == request.data()) { - _id2request.erase(it); - break; - } - it++; - } - }); - request->download(url, target, headers); -} - -void FileTransfer::upload(int scId, int ecId, const QString &fileURI, const QString& url, const QString& fileKey, const QString& fileName, const QString& mimeType, - const QVariantMap & params, bool /*trustAllHosts*/, bool /*chunkedMode*/, const QVariantMap &headers, int id, const QString &/*httpMethod*/) { - QSharedPointer request(new FileTransferRequest(_manager, scId, ecId, id, this)); - - assert(_id2request.find(id) == _id2request.end()); - - _id2request.insert(id, request); - - request->connect(request.data(), &FileTransferRequest::done, [&]() { - auto it = _id2request.find(id); - while (it != _id2request.end() && it.key() == id) { - if (it.value().data() == request.data()) { - _id2request.erase(it); - break; - } - it++; - } - }); - request->upload(url, fileURI, fileKey, fileName, mimeType, params, headers); -} - -void FileTransfer::abort(int scId, int ecId, int id) { - Q_UNUSED(scId) - Q_UNUSED(ecId) - - auto it = _id2request.find(id); - while (it != _id2request.end() && it.key() == id) { - (*it)->abort(); - it++; - } -} - -void FileTransferRequest::download(const QString& uri, const QString &targetURI, const QVariantMap &headers) { - QUrl url(uri); - QNetworkRequest request; - - QSharedPointer filePlugin(_plugin->cordova()->getPlugin()); - - if (!filePlugin.data()) - return; - - if (!url.isValid()) { - QVariantMap map; - map.insert("code", INVALID_URL_ERR); - map.insert("source", uri); - map.insert("target", targetURI); - _plugin->cb(_ecId, map); - emit done(); - return; - } - - request.setUrl(url); - if (url.password().size() || url.userName().size()) { - QString headerData = "Basic " + (url.userName() + ":" + url.password()).toLocal8Bit().toBase64(); - request.setRawHeader("Authorization", headerData.toLocal8Bit()); - } - SetHeaders(request, headers); - _reply = QSharedPointer(_manager.get(request)); - - _reply->connect(_reply.data(), &QNetworkReply::finished, [this, targetURI, uri, filePlugin]() { - if (!_scId || _reply->error() != QNetworkReply::NoError) - return; - - QPair f1(dynamic_cast(filePlugin.data())->resolveURI(targetURI)); - - QFile res(f1.second.absoluteFilePath()); - if (!f1.first || !res.open(QIODevice::WriteOnly)) { - QVariantMap map; - map.insert("code", INVALID_URL_ERR); - map.insert("source", uri); - map.insert("target", targetURI); - _plugin->cb(_ecId, map); - emit done(); - return; - } - res.write(_reply->readAll()); - - _plugin->cb(_scId, dynamic_cast(filePlugin.data())->file2map(f1.second)); - - emit done(); - }); - _reply->connect(_reply.data(), SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(error(QNetworkReply::NetworkError))); - _reply->connect(_reply.data(), SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(progress(qint64, qint64))); -} - -void FileTransferRequest::upload(const QString& _url, const QString& fileURI, QString fileKey, QString fileName, QString mimeType, const QVariantMap ¶ms, const QVariantMap &headers) { - QUrl url(_url); - QNetworkRequest request; - - QSharedPointer filePlugin(_plugin->cordova()->getPlugin()); - - if (!filePlugin.data()) - return; - - if (!url.isValid()) { - QVariantMap map; - map.insert("code", INVALID_URL_ERR); - map.insert("source", fileURI); - map.insert("target", _url); - _plugin->cb(_ecId, map); - emit done(); - return; - } - - QPair f1(dynamic_cast(filePlugin.data())->resolveURI(fileURI)); - QFile file(f1.second.absoluteFilePath()); - if (!f1.first || !file.open(QIODevice::ReadOnly)) { - QVariantMap map; - map.insert("code", FILE_NOT_FOUND_ERR); - map.insert("source", fileURI); - map.insert("target", _url); - _plugin->cb(_ecId, map); - emit done(); - return; - } - QString content{file.readAll()}; - - request.setUrl(url); - if (url.password().size() || url.userName().size()) { - QString headerData = "Basic " + (url.userName() + ":" + url.password()).toLocal8Bit().toBase64(); - request.setRawHeader("Authorization", headerData.toLocal8Bit()); - } - SetHeaders(request, headers); - - QString boundary = QString("CORDOVA-QT-%1A").arg(qrand()); - while (content.contains(boundary)) { - boundary += QString("B%1A").arg(qrand()); - } - - request.setHeader(QNetworkRequest::ContentTypeHeader, QString("multipart/form-data; boundary=") + boundary); - - fileKey.replace("\"", ""); - fileName.replace("\"", ""); - mimeType.replace("\"", ""); - QString part = "--" + boundary + "\r\n"; - - part += "Content-Disposition: form-data; name=\"" + fileKey +"\"; filename=\"" + fileName + "\"\r\n"; - part += "Content-Type: " + mimeType + "\r\n\r\n"; - part += content + "\r\n"; - - for (QString key: params.keys()) { - part += "--" + boundary + "\r\n"; - part += "Content-Disposition: form-data; name=\"" + key + "\";\r\n\r\n"; - part += params.find(key)->toString(); - part += "\r\n"; - } - - part += QString("--") + boundary + "--" + "\r\n"; - - _reply = QSharedPointer(_manager.post(request, QByteArray(part.toUtf8()))); - - _reply->connect(_reply.data(), &QNetworkReply::finished, [this, content]() { - if (_reply->error() != QNetworkReply::NoError) - return; - int status = 200; - QVariant statusCode = _reply->attribute(QNetworkRequest::HttpStatusCodeAttribute); - - if (statusCode.isValid()) { - status = statusCode.toInt(); - } - - QVariantMap map; - map.insert("responseCode", status); - map.insert("response", QString(_reply->readAll())); - map.insert("bytesSent", content.size()); - _plugin->cb(_scId, map); - emit done(); - }); - _reply->connect(_reply.data(), SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(error(QNetworkReply::NetworkError))); - _reply->connect(_reply.data(), SIGNAL(uploadProgress(qint64, qint64)), this, SLOT(progress(qint64, qint64))); -} - -void FileTransferRequest::abort() { - QVariantMap map; - map.insert("code", ABORT_ERR); - _plugin->cb(_ecId, map); - _scId = 0; - emit done(); -} - -void FileTransferRequest::error(QNetworkReply::NetworkError code) { - Q_UNUSED(code); - - int status = 404; - QVariant statusCode = _reply->attribute(QNetworkRequest::HttpStatusCodeAttribute); - if (statusCode.isValid()) { - status = statusCode.toInt(); - } - - QVariantMap map; - map.insert("http_status", status); - map.insert("body", QString(_reply->readAll())); - map.insert("code", CONNECTION_ERR); - _plugin->cb(_ecId, map); - emit done(); -} - -void FileTransferRequest::progress(qint64 bytesReceived, qint64 bytesTotal) { - QVariantMap map; - map.insert("lengthComputable", true); - map.insert("total", bytesTotal); - map.insert("loaded", bytesReceived); - - if (bytesReceived && bytesTotal && _scId) - _plugin->callbackWithoutRemove(_scId, CordovaInternal::format(map)); -} diff --git a/plugins/cordova-plugin-file-transfer/src/ubuntu/file-transfer.h b/plugins/cordova-plugin-file-transfer/src/ubuntu/file-transfer.h deleted file mode 100644 index 75822cb..0000000 --- a/plugins/cordova-plugin-file-transfer/src/ubuntu/file-transfer.h +++ /dev/null @@ -1,103 +0,0 @@ -/* - * - * Copyright 2013 Canonical Ltd. - * - * 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 FILE_TRANSFER_H_SDASDASDAS -#define FILE_TRANSFER_H_SDASDASDAS - -#include -#include - -#include - -class FileTransfer; - -class FileTransferRequest: public QObject { - Q_OBJECT - - QNetworkAccessManager &_manager; - int _scId, _ecId; - int _id; - QSharedPointer _reply; - - enum FileTransferError { - FILE_NOT_FOUND_ERR = 1, - INVALID_URL_ERR = 2, - CONNECTION_ERR = 3, - ABORT_ERR = 4 - }; - -public: - FileTransferRequest(QNetworkAccessManager &manager, int scId, int ecId, int id, FileTransfer *plugin): - _manager(manager), - _scId(scId), - _ecId(ecId), - _id(id), - _plugin(plugin) { - } - - void download(const QString& url, const QString &targetURI, const QVariantMap &headers); - void upload(const QString& _url, const QString& fileURI, QString fileKey, QString fileName, QString mimeType, const QVariantMap ¶ms, const QVariantMap &headers); - void abort(); - -signals: - void done(); - -private slots: - void progress(qint64 bytesReceived, qint64 bytesTotal); - void error(QNetworkReply::NetworkError code); -private: - FileTransfer *_plugin; - Q_DISABLE_COPY(FileTransferRequest); -}; - -class FileTransfer : public CPlugin { - Q_OBJECT -public: - explicit FileTransfer(Cordova *cordova): CPlugin(cordova) { - } - - Cordova* cordova() { - return m_cordova; - } - - virtual const QString fullName() override { - return FileTransfer::fullID(); - } - - virtual const QString shortName() override { - return "FileTransfer"; - } - - static const QString fullID() { - return "FileTransfer"; - } - -public slots: - void abort(int scId, int ecId, int id); - void download(int scId, int ecId, const QString& url, const QString &target, bool /*trustAllHost*/, int id, const QVariantMap &/*headers*/); - void upload(int scId, int ecId, const QString &filePath, const QString& url, const QString& fileKey, const QString& fileName, const QString& mimeType, - const QVariantMap & params, bool /*trustAllHosts*/, bool /*chunkedMode*/, const QVariantMap &headers, int id, const QString &httpMethod); - -private: - QNetworkAccessManager _manager; - QMultiMap > _id2request; - int lastRequestId; -}; - -#endif diff --git a/plugins/cordova-plugin-file-transfer/src/windows/FileTransferProxy.js b/plugins/cordova-plugin-file-transfer/src/windows/FileTransferProxy.js deleted file mode 100644 index 5d1363f..0000000 --- a/plugins/cordova-plugin-file-transfer/src/windows/FileTransferProxy.js +++ /dev/null @@ -1,579 +0,0 @@ -/* - * - * 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 -W030 */ -/*global Windows, WinJS*/ -/*global module, require*/ - -var FTErr = require('./FileTransferError'), - ProgressEvent = require('cordova-plugin-file.ProgressEvent'), - FileUploadResult = require('cordova-plugin-file.FileUploadResult'), - FileProxy = require('cordova-plugin-file.FileProxy'); - -var appData = Windows.Storage.ApplicationData.current; - -var LINE_START = "--"; -var LINE_END = "\r\n"; -var BOUNDARY = '+++++'; - -var fileTransferOps = []; - -// Some private helper functions, hidden by the module -function cordovaPathToNative(path) { - - var cleanPath = String(path); - // turn / into \\ - cleanPath = cleanPath.replace(/\//g, '\\'); - // turn \\ into \ - cleanPath = cleanPath.replace(/\\\\/g, '\\'); - // strip end \\ characters - cleanPath = cleanPath.replace(/\\+$/g, ''); - return cleanPath; -} - -function nativePathToCordova(path) { - return String(path).replace(/\\/g, '/'); -} - -function alreadyCancelled(opId) { - var op = fileTransferOps[opId]; - return op && op.state === FileTransferOperation.CANCELLED; -} - -function doUpload (upload, uploadId, filePath, server, successCallback, errorCallback) { - if (alreadyCancelled(uploadId)) { - errorCallback(new FTErr(FTErr.ABORT_ERR, nativePathToCordova(filePath), server)); - return; - } - - // update internal TransferOperation object with newly created promise - var uploadOperation = upload.startAsync(); - fileTransferOps[uploadId].promise = uploadOperation; - - uploadOperation.then( - function (result) { - // Update TransferOperation object with new state, delete promise property - // since it is not actual anymore - var currentUploadOp = fileTransferOps[uploadId]; - if (currentUploadOp) { - currentUploadOp.state = FileTransferOperation.DONE; - currentUploadOp.promise = null; - } - - var response = result.getResponseInformation(); - var ftResult = new FileUploadResult(result.progress.bytesSent, response.statusCode, ''); - - // if server's response doesn't contain any data, then resolve operation now - if (result.progress.bytesReceived === 0) { - successCallback(ftResult); - return; - } - - // otherwise create a data reader, attached to response stream to get server's response - var reader = new Windows.Storage.Streams.DataReader(result.getResultStreamAt(0)); - reader.loadAsync(result.progress.bytesReceived).then(function (size) { - ftResult.response = reader.readString(size); - successCallback(ftResult); - reader.close(); - }); - }, - function (error) { - var source = nativePathToCordova(filePath); - - // Handle download error here. - // Wrap this routines into promise due to some async methods - var getTransferError = new WinJS.Promise(function (resolve) { - if (error.message === 'Canceled') { - // If download was cancelled, message property will be specified - resolve(new FTErr(FTErr.ABORT_ERR, source, server, null, null, error)); - } else { - // in the other way, try to get response property - var response = upload.getResponseInformation(); - if (!response) { - resolve(new FTErr(FTErr.CONNECTION_ERR, source, server)); - } else { - var reader = new Windows.Storage.Streams.DataReader(upload.getResultStreamAt(0)); - reader.loadAsync(upload.progress.bytesReceived).then(function (size) { - var responseText = reader.readString(size); - resolve(new FTErr(FTErr.FILE_NOT_FOUND_ERR, source, server, response.statusCode, responseText, error)); - reader.close(); - }); - } - } - }); - - // Update TransferOperation object with new state, delete promise property - // since it is not actual anymore - var currentUploadOp = fileTransferOps[uploadId]; - if (currentUploadOp) { - currentUploadOp.state = FileTransferOperation.CANCELLED; - currentUploadOp.promise = null; - } - - // Report the upload error back - getTransferError.then(function (transferError) { - errorCallback(transferError); - }); - }, - function (evt) { - var progressEvent = new ProgressEvent('progress', { - loaded: evt.progress.bytesSent, - total: evt.progress.totalBytesToSend, - target: evt.resultFile - }); - progressEvent.lengthComputable = true; - successCallback(progressEvent, { keepCallback: true }); - } - ); -} - -function FileTransferOperation(state, promise) { - this.state = state; - this.promise = promise; -} - -FileTransferOperation.PENDING = 0; -FileTransferOperation.DONE = 1; -FileTransferOperation.CANCELLED = 2; - -var HTTP_E_STATUS_NOT_MODIFIED = -2145844944; - -module.exports = { - -/* -exec(win, fail, 'FileTransfer', 'upload', -[filePath, server, fileKey, fileName, mimeType, params, trustAllHosts, chunkedMode, headers, this._id, httpMethod]); -*/ - upload: function (successCallback, errorCallback, options) { - var filePath = options[0]; - var server = options[1]; - var fileKey = options[2] || 'source'; - var fileName = options[3]; - var mimeType = options[4]; - var params = options[5]; - // var trustAllHosts = options[6]; // todo - // var chunkedMode = options[7]; // todo - var headers = options[8] || {}; - var uploadId = options[9]; - var httpMethod = options[10]; - - var isMultipart = typeof headers["Content-Type"] === 'undefined'; - - function stringToByteArray(str) { - var byteCharacters = atob(str); - var byteNumbers = new Array(byteCharacters.length); - for (var i = 0; i < byteCharacters.length; i++) { - byteNumbers[i] = byteCharacters.charCodeAt(i); - } - return new Uint8Array(byteNumbers); - } - - if (!filePath || (typeof filePath !== 'string')) { - errorCallback(new FTErr(FTErr.FILE_NOT_FOUND_ERR, null, server)); - return; - } - - if (filePath.indexOf("data:") === 0 && filePath.indexOf("base64") !== -1) { - // First a DataWriter object is created, backed by an in-memory stream where - // the data will be stored. - var writer = Windows.Storage.Streams.DataWriter(new Windows.Storage.Streams.InMemoryRandomAccessStream()); - writer.unicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.utf8; - writer.byteOrder = Windows.Storage.Streams.ByteOrder.littleEndian; - - var commaIndex = filePath.indexOf(","); - if (commaIndex === -1) { - errorCallback(new FTErr(FTErr.INVALID_URL_ERR, fileName, server, null, null, "No comma in data: URI")); - return; - } - - // Create internal download operation object - fileTransferOps[uploadId] = new FileTransferOperation(FileTransferOperation.PENDING, null); - - var fileDataString = filePath.substr(commaIndex + 1); - - // setting request headers for uploader - var uploader = new Windows.Networking.BackgroundTransfer.BackgroundUploader(); - uploader.method = httpMethod; - for (var header in headers) { - if (headers.hasOwnProperty(header)) { - uploader.setRequestHeader(header, headers[header]); - } - } - - if (isMultipart) { - // adding params supplied to request payload - var multipartParams = ''; - for (var key in params) { - if (params.hasOwnProperty(key)) { - multipartParams += LINE_START + BOUNDARY + LINE_END; - multipartParams += "Content-Disposition: form-data; name=\"" + key + "\""; - multipartParams += LINE_END + LINE_END; - multipartParams += params[key]; - multipartParams += LINE_END; - } - } - - var multipartFile = LINE_START + BOUNDARY + LINE_END; - multipartFile += "Content-Disposition: form-data; name=\"file\";"; - multipartFile += " filename=\"" + fileName + "\"" + LINE_END; - multipartFile += "Content-Type: " + mimeType + LINE_END + LINE_END; - - var bound = LINE_END + LINE_START + BOUNDARY + LINE_START + LINE_END; - - uploader.setRequestHeader("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); - writer.writeString(multipartParams); - writer.writeString(multipartFile); - writer.writeBytes(stringToByteArray(fileDataString)); - writer.writeString(bound); - } else { - writer.writeBytes(stringToByteArray(fileDataString)); - } - - var stream; - - // The call to store async sends the actual contents of the writer - // to the backing stream. - writer.storeAsync().then(function () { - // For the in-memory stream implementation we are using, the flushAsync call - // is superfluous, but other types of streams may require it. - return writer.flushAsync(); - }).then(function () { - // We detach the stream to prolong its useful lifetime. Were we to fail - // to detach the stream, the call to writer.close() would close the underlying - // stream, preventing its subsequent use by the DataReader below. Most clients - // of DataWriter will have no reason to use the underlying stream after - // writer.close() is called, and will therefore have no reason to call - // writer.detachStream(). Note that once we detach the stream, we assume - // responsibility for closing the stream subsequently; after the stream - // has been detached, a call to writer.close() will have no effect on the stream. - stream = writer.detachStream(); - // Make sure the stream is read from the beginning in the reader - // we are creating below. - stream.seek(0); - // Most DataWriter clients will not call writer.detachStream(), - // and furthermore will be working with a file-backed or network-backed stream, - // rather than an in-memory-stream. In such cases, it would be particularly - // important to call writer.close(). Doing so is always a best practice. - writer.close(); - - if (alreadyCancelled(uploadId)) { - errorCallback(new FTErr(FTErr.ABORT_ERR, nativePathToCordova(filePath), server)); - return; - } - - // create download object. This will throw an exception if URL is malformed - var uri = new Windows.Foundation.Uri(server); - - var createUploadOperation; - try { - createUploadOperation = uploader.createUploadFromStreamAsync(uri, stream); - } catch (e) { - errorCallback(new FTErr(FTErr.INVALID_URL_ERR)); - return; - } - - createUploadOperation.then( - function (upload) { - doUpload(upload, uploadId, filePath, server, successCallback, errorCallback); - }, - function (err) { - var errorObj = new FTErr(FTErr.INVALID_URL_ERR); - errorObj.exception = err; - errorCallback(errorObj); - }); - }); - - return; - } - - if (filePath.substr(0, 8) === "file:///") { - filePath = appData.localFolder.path + filePath.substr(8).split("/").join("\\"); - } else if (filePath.indexOf('ms-appdata:///') === 0) { - // Handle 'ms-appdata' scheme - filePath = filePath.replace('ms-appdata:///local', appData.localFolder.path) - .replace('ms-appdata:///temp', appData.temporaryFolder.path); - } else if (filePath.indexOf('cdvfile://') === 0) { - filePath = filePath.replace('cdvfile://localhost/persistent', appData.localFolder.path) - .replace('cdvfile://localhost/temporary', appData.temporaryFolder.path); - } - - // normalize path separators - filePath = cordovaPathToNative(filePath); - - // Create internal download operation object - fileTransferOps[uploadId] = new FileTransferOperation(FileTransferOperation.PENDING, null); - - Windows.Storage.StorageFile.getFileFromPathAsync(filePath) - .then(function (storageFile) { - - if (!fileName) { - fileName = storageFile.name; - } - if (!mimeType) { - // use the actual content type of the file, probably this should be the default way. - // other platforms probably can't look this up. - mimeType = storageFile.contentType; - } - - if (alreadyCancelled(uploadId)) { - errorCallback(new FTErr(FTErr.ABORT_ERR, nativePathToCordova(filePath), server)); - return; - } - - // setting request headers for uploader - var uploader = new Windows.Networking.BackgroundTransfer.BackgroundUploader(); - uploader.method = httpMethod; - for (var header in headers) { - if (headers.hasOwnProperty(header)) { - uploader.setRequestHeader(header, headers[header]); - } - } - - // create download object. This will throw an exception if URL is malformed - var uri = new Windows.Foundation.Uri(server); - - var createUploadOperation; - try { - if (isMultipart) { - // adding params supplied to request payload - var transferParts = []; - for (var key in params) { - // Create content part for params only if value is specified because CreateUploadAsync fails otherwise - if (params.hasOwnProperty(key) && params[key] !== null && params[key] !== undefined && params[key].toString() !== "") { - var contentPart = new Windows.Networking.BackgroundTransfer.BackgroundTransferContentPart(); - contentPart.setHeader("Content-Disposition", "form-data; name=\"" + key + "\""); - contentPart.setText(params[key]); - transferParts.push(contentPart); - } - } - - // Adding file to upload to request payload - var fileToUploadPart = new Windows.Networking.BackgroundTransfer.BackgroundTransferContentPart(fileKey, fileName); - fileToUploadPart.setHeader("Content-Type", mimeType); - fileToUploadPart.setFile(storageFile); - transferParts.push(fileToUploadPart); - - createUploadOperation = uploader.createUploadAsync(uri, transferParts); - } else { - createUploadOperation = WinJS.Promise.wrap(uploader.createUpload(uri, storageFile)); - } - } catch (e) { - errorCallback(new FTErr(FTErr.INVALID_URL_ERR)); - return; - } - - createUploadOperation.then( - function (upload) { - doUpload(upload, uploadId, filePath, server, successCallback, errorCallback); - }, - function (err) { - var errorObj = new FTErr(FTErr.INVALID_URL_ERR); - errorObj.exception = err; - errorCallback(errorObj); - } - ); - }, function (err) { - errorCallback(new FTErr(FTErr.FILE_NOT_FOUND_ERR, fileName, server, null, null, err)); - }); - }, - - // [source, target, trustAllHosts, id, headers] - download:function(successCallback, errorCallback, options) { - var source = options[0]; - var target = options[1]; - var downloadId = options[3]; - var headers = options[4] || {}; - - if (!target) { - errorCallback(new FTErr(FTErr.FILE_NOT_FOUND_ERR)); - return; - } - if (target.substr(0, 8) === "file:///") { - target = appData.localFolder.path + target.substr(8).split("/").join("\\"); - } else if (target.indexOf('ms-appdata:///') === 0) { - // Handle 'ms-appdata' scheme - target = target.replace('ms-appdata:///local', appData.localFolder.path) - .replace('ms-appdata:///temp', appData.temporaryFolder.path); - } else if (target.indexOf('cdvfile://') === 0) { - target = target.replace('cdvfile://localhost/persistent', appData.localFolder.path) - .replace('cdvfile://localhost/temporary', appData.temporaryFolder.path); - } - target = cordovaPathToNative(target); - - var path = target.substr(0, target.lastIndexOf("\\")); - var fileName = target.substr(target.lastIndexOf("\\") + 1); - if (path === null || fileName === null) { - errorCallback(new FTErr(FTErr.FILE_NOT_FOUND_ERR)); - return; - } - // Download to a temp file to avoid the file deletion on 304 - // CB-7006 Empty file is created on file transfer if server response is 304 - var tempFileName = '~' + fileName; - - var download = null; - - // Create internal download operation object - fileTransferOps[downloadId] = new FileTransferOperation(FileTransferOperation.PENDING, null); - - var downloadCallback = function(storageFolder) { - storageFolder.createFileAsync(tempFileName, Windows.Storage.CreationCollisionOption.replaceExisting).then(function (storageFile) { - - if (alreadyCancelled(downloadId)) { - errorCallback(new FTErr(FTErr.ABORT_ERR, source, target)); - return; - } - - // if download isn't cancelled, contunue with creating and preparing download operation - var downloader = new Windows.Networking.BackgroundTransfer.BackgroundDownloader(); - for (var header in headers) { - if (headers.hasOwnProperty(header)) { - downloader.setRequestHeader(header, headers[header]); - } - } - - // create download object. This will throw an exception if URL is malformed - try { - var uri = Windows.Foundation.Uri(source); - download = downloader.createDownload(uri, storageFile); - } catch (e) { - // so we handle this and call errorCallback - errorCallback(new FTErr(FTErr.INVALID_URL_ERR)); - return; - } - - var downloadOperation = download.startAsync(); - // update internal TransferOperation object with newly created promise - fileTransferOps[downloadId].promise = downloadOperation; - - downloadOperation.then(function () { - - // Update TransferOperation object with new state, delete promise property - // since it is not actual anymore - var currentDownloadOp = fileTransferOps[downloadId]; - if (currentDownloadOp) { - currentDownloadOp.state = FileTransferOperation.DONE; - currentDownloadOp.promise = null; - } - - storageFile.renameAsync(fileName, Windows.Storage.CreationCollisionOption.replaceExisting).done(function () { - var nativeURI = storageFile.path.replace(appData.localFolder.path, 'ms-appdata:///local') - .replace(appData.temporaryFolder.path, 'ms-appdata:///temp') - .replace(/\\/g, '/'); - - // Passing null as error callback here because downloaded file should exist in any case - // otherwise the error callback will be hit during file creation in another place - FileProxy.resolveLocalFileSystemURI(successCallback, null, [nativeURI]); - }, function(error) { - errorCallback(new FTErr(FTErr.FILE_NOT_FOUND_ERR, source, target, null, null, error)); - }); - }, function(error) { - - var getTransferError = new WinJS.Promise(function (resolve) { - // Handle download error here. If download was cancelled, - // message property will be specified - if (error.message === 'Canceled') { - resolve(new FTErr(FTErr.ABORT_ERR, source, target, null, null, error)); - } else if (error && error.number === HTTP_E_STATUS_NOT_MODIFIED) { - resolve(new FTErr(FTErr.NOT_MODIFIED_ERR, source, target, 304, null, error)); - } else { - // in the other way, try to get response property - var response = download.getResponseInformation(); - if (!response) { - resolve(new FTErr(FTErr.CONNECTION_ERR, source, target)); - } else { - var reader = new Windows.Storage.Streams.DataReader(download.getResultStreamAt(0)); - reader.loadAsync(download.progress.bytesReceived).then(function (bytesLoaded) { - var payload = reader.readString(bytesLoaded); - resolve(new FTErr(FTErr.FILE_NOT_FOUND_ERR, source, target, response.statusCode, payload, error)); - }); - } - } - }); - getTransferError.then(function (fileTransferError) { - - // Update TransferOperation object with new state, delete promise property - // since it is not actual anymore - var currentDownloadOp = fileTransferOps[downloadId]; - if (currentDownloadOp) { - currentDownloadOp.state = FileTransferOperation.CANCELLED; - currentDownloadOp.promise = null; - } - - // Cleanup, remove incompleted file - storageFile.deleteAsync().then(function() { - errorCallback(fileTransferError); - }); - }); - - }, function(evt) { - - var progressEvent = new ProgressEvent('progress', { - loaded: evt.progress.bytesReceived, - total: evt.progress.totalBytesToReceive, - target: evt.resultFile - }); - // when bytesReceived == 0, BackgroundDownloader has not yet differentiated whether it could get file length or not, - // when totalBytesToReceive == 0, BackgroundDownloader is unable to get file length - progressEvent.lengthComputable = (evt.progress.bytesReceived > 0) && (evt.progress.totalBytesToReceive > 0); - - successCallback(progressEvent, { keepCallback: true }); - }); - }, function(error) { - errorCallback(new FTErr(FTErr.FILE_NOT_FOUND_ERR, source, target, null, null, error)); - }); - }; - - var fileNotFoundErrorCallback = function(error) { - errorCallback(new FTErr(FTErr.FILE_NOT_FOUND_ERR, source, target, null, null, error)); - }; - - Windows.Storage.StorageFolder.getFolderFromPathAsync(path).then(downloadCallback, function (error) { - // Handle non-existent directory - if (error.number === -2147024894) { - var parent = path.substr(0, path.lastIndexOf('\\')), - folderNameToCreate = path.substr(path.lastIndexOf('\\') + 1); - - Windows.Storage.StorageFolder.getFolderFromPathAsync(parent).then(function(parentFolder) { - parentFolder.createFolderAsync(folderNameToCreate).then(downloadCallback, fileNotFoundErrorCallback); - }, fileNotFoundErrorCallback); - } else { - fileNotFoundErrorCallback(); - } - }); - }, - - abort: function (successCallback, error, options) { - var fileTransferOpId = options[0]; - - // Try to find transferOperation with id specified, and cancel its' promise - var currentOp = fileTransferOps[fileTransferOpId]; - if (currentOp) { - currentOp.state = FileTransferOperation.CANCELLED; - currentOp.promise && currentOp.promise.cancel(); - } else if (typeof fileTransferOpId !== 'undefined') { - // Create the operation in cancelled state to be aborted right away - fileTransferOps[fileTransferOpId] = new FileTransferOperation(FileTransferOperation.CANCELLED, null); - } - } - -}; - -require("cordova/exec/proxy").add("FileTransfer",module.exports); diff --git a/plugins/cordova-plugin-file-transfer/src/wp/FileTransfer.cs b/plugins/cordova-plugin-file-transfer/src/wp/FileTransfer.cs deleted file mode 100644 index 4be46e8..0000000 --- a/plugins/cordova-plugin-file-transfer/src/wp/FileTransfer.cs +++ /dev/null @@ -1,994 +0,0 @@ -/* - 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 Microsoft.Phone.Controls; -using System; -using System.Collections.Generic; -using System.IO; -using System.IO.IsolatedStorage; -using System.Linq; -using System.Net; -using System.Runtime.Serialization; -using System.Windows; -using System.Security; -using System.Diagnostics; -using System.Threading.Tasks; -using WPCordovaClassLib.Cordova.JSON; -using System.Reflection; - -namespace WPCordovaClassLib.Cordova.Commands -{ - public class FileTransfer : BaseCommand - { - public class DownloadRequestState - { - // This class stores the State of the request. - public HttpWebRequest request; - public TransferOptions options; - public bool isCancelled; - - public DownloadRequestState() - { - request = null; - options = null; - isCancelled = false; - } - } - - public class TransferOptions - { - /// File path to upload OR File path to download to - public string FilePath { get; set; } - - public string Url { get; set; } - /// Flag to recognize if we should trust every host (only in debug environments) - public bool TrustAllHosts { get; set; } - public string Id { get; set; } - public string Headers { get; set; } - public string CallbackId { get; set; } - public bool ChunkedMode { get; set; } - /// Server address - public string Server { get; set; } - /// File key - public string FileKey { get; set; } - /// File name on the server - public string FileName { get; set; } - /// File Mime type - public string MimeType { get; set; } - /// Additional options - public string Params { get; set; } - public string Method { get; set; } - - public TransferOptions() - { - FileKey = "file"; - FileName = "image.jpg"; - MimeType = "image/jpeg"; - } - } - - /// - /// Boundary symbol - /// - private string Boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x"); - - // Error codes - public const int FileNotFoundError = 1; - public const int InvalidUrlError = 2; - public const int ConnectionError = 3; - public const int AbortError = 4; // not really an error, but whatevs - - private static Dictionary InProcDownloads = new Dictionary(); - - // Private instance of the main WebBrowser instance - // NOTE: Any access to this object needs to occur on the UI thread via the Dispatcher - private WebBrowser browser; - - - - /// - /// Uploading response info - /// - [DataContract] - public class FileUploadResult - { - /// - /// Amount of sent bytes - /// - [DataMember(Name = "bytesSent")] - public long BytesSent { get; set; } - - /// - /// Server response code - /// - [DataMember(Name = "responseCode")] - public long ResponseCode { get; set; } - - /// - /// Server response - /// - [DataMember(Name = "response", EmitDefaultValue = false)] - public string Response { get; set; } - - /// - /// Creates FileUploadResult object with response values - /// - /// Amount of sent bytes - /// Server response code - /// Server response - public FileUploadResult(long bytesSent, long responseCode, string response) - { - this.BytesSent = bytesSent; - this.ResponseCode = responseCode; - this.Response = response; - } - } - /// - /// Represents transfer error codes for callback - /// - [DataContract] - public class FileTransferError - { - /// - /// Error code - /// - [DataMember(Name = "code", IsRequired = true)] - public int Code { get; set; } - - /// - /// The source URI - /// - [DataMember(Name = "source", IsRequired = true)] - public string Source { get; set; } - - /// - /// The target URI - /// - /// - [DataMember(Name = "target", IsRequired = true)] - public string Target { get; set; } - - [DataMember(Name = "body", IsRequired = true)] - public string Body { get; set; } - - /// - /// The http status code response from the remote URI - /// - [DataMember(Name = "http_status", IsRequired = true)] - public int HttpStatus { get; set; } - - /// - /// Creates FileTransferError object - /// - /// Error code - public FileTransferError(int errorCode) - { - this.Code = errorCode; - this.Source = null; - this.Target = null; - this.HttpStatus = 0; - this.Body = ""; - } - public FileTransferError(int errorCode, string source, string target, int status, string body = "") - { - this.Code = errorCode; - this.Source = source; - this.Target = target; - this.HttpStatus = status; - this.Body = body; - } - } - - /// - /// Represents a singular progress event to be passed back to javascript - /// - [DataContract] - public class FileTransferProgress - { - /// - /// Is the length of the response known? - /// - [DataMember(Name = "lengthComputable", IsRequired = true)] - public bool LengthComputable { get; set; } - /// - /// amount of bytes loaded - /// - [DataMember(Name = "loaded", IsRequired = true)] - public long BytesLoaded { get; set; } - /// - /// Total bytes - /// - [DataMember(Name = "total", IsRequired = false)] - public long BytesTotal { get; set; } - - public FileTransferProgress(long bTotal = 0, long bLoaded = 0) - { - LengthComputable = bTotal > 0; - BytesLoaded = bLoaded; - BytesTotal = bTotal; - } - } - - /// - /// Represents a request header passed from Javascript to upload/download operations - /// - [DataContract] - protected struct Header - { - [DataMember(Name = "name")] - public string Name; - - [DataMember(Name = "value")] - public string Value; - } - - private static MethodInfo JsonDeserializeUsingJsonNet; - - public FileTransfer() - { - if (JsonDeserializeUsingJsonNet == null) - { - var method = typeof(JsonHelper).GetMethod("Deserialize", new Type[] { typeof(string), typeof(bool) }); - if (method != null) - { - JsonDeserializeUsingJsonNet = method.MakeGenericMethod(new Type[] { typeof(Header[]) }); - } - } - } - - /// Helper method to copy all relevant cookies from the WebBrowser control into a header on - /// the HttpWebRequest - /// - /// The source browser to copy the cookies from - /// The destination HttpWebRequest to add the cookie header to - /// Nothing - private async Task CopyCookiesFromWebBrowser(HttpWebRequest webRequest) - { - var tcs = new TaskCompletionSource(); - - // Accessing WebBrowser needs to happen on the UI thread - Deployment.Current.Dispatcher.BeginInvoke(() => - { - // Get the WebBrowser control - if (this.browser == null) - { - PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame; - if (frame != null) - { - PhoneApplicationPage page = frame.Content as PhoneApplicationPage; - if (page != null) - { - CordovaView cView = page.FindName("CordovaView") as CordovaView; - if (cView != null) - { - this.browser = cView.Browser; - } - } - } - } - - try - { - // Only copy the cookies if the scheme and host match (to avoid any issues with secure/insecure cookies) - // NOTE: since the returned CookieCollection appears to munge the original cookie's domain value in favor of the actual Source domain, - // we can't know for sure whether the cookies would be applicable to any other hosts, so best to play it safe and skip for now. - if (this.browser != null && this.browser.Source.IsAbsoluteUri == true && - this.browser.Source.Scheme == webRequest.RequestUri.Scheme && this.browser.Source.Host == webRequest.RequestUri.Host) - { - string cookieHeader = ""; - string requestPath = webRequest.RequestUri.PathAndQuery; - CookieCollection cookies = this.browser.GetCookies(); - - // Iterate over the cookies and add to the header - foreach (Cookie cookie in cookies) - { - // Check that the path is allowed, first - // NOTE: Path always seems to be empty for now, even if the cookie has a path set by the server. - if (cookie.Path.Length == 0 || requestPath.IndexOf(cookie.Path, StringComparison.InvariantCultureIgnoreCase) == 0) - { - cookieHeader += cookie.Name + "=" + cookie.Value + "; "; - } - } - - // Finally, set the header if we found any cookies - if (cookieHeader.Length > 0) - { - webRequest.Headers["Cookie"] = cookieHeader; - } - } - } - catch (Exception) - { - // Swallow the exception - } - - // Complete the task - tcs.SetResult(Type.Missing); - }); - - await tcs.Task; - } - - /// - /// Upload options - /// - //private TransferOptions uploadOptions; - - /// - /// Bytes sent - /// - private long bytesSent; - - /// - /// sends a file to a server - /// - /// Upload options - /// exec(win, fail, 'FileTransfer', 'upload', [filePath, server, fileKey, fileName, mimeType, params, trustAllHosts, chunkedMode, headers, this._id, httpMethod]); - public void upload(string options) - { - options = options.Replace("{}", ""); // empty objects screw up the Deserializer - string callbackId = ""; - - TransferOptions uploadOptions = null; - HttpWebRequest webRequest = null; - - try - { - try - { - string[] args = JSON.JsonHelper.Deserialize(options); - uploadOptions = new TransferOptions(); - uploadOptions.FilePath = args[0]; - uploadOptions.Server = args[1]; - uploadOptions.FileKey = args[2]; - uploadOptions.FileName = args[3]; - uploadOptions.MimeType = args[4]; - uploadOptions.Params = args[5]; - - bool trustAll = false; - bool.TryParse(args[6],out trustAll); - uploadOptions.TrustAllHosts = trustAll; - - bool doChunked = false; - bool.TryParse(args[7], out doChunked); - uploadOptions.ChunkedMode = doChunked; - - //8 : Headers - //9 : id - //10: method - - uploadOptions.Headers = args[8]; - uploadOptions.Id = args[9]; - uploadOptions.Method = args[10]; - - uploadOptions.CallbackId = callbackId = args[11]; - } - catch (Exception) - { - DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); - return; - } - - Uri serverUri; - try - { - serverUri = new Uri(uploadOptions.Server); - } - catch (Exception) - { - DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(InvalidUrlError, uploadOptions.Server, null, 0))); - return; - } - webRequest = (HttpWebRequest)WebRequest.Create(serverUri); - webRequest.ContentType = "multipart/form-data; boundary=" + Boundary; - webRequest.Method = uploadOptions.Method; - - DownloadRequestState reqState = new DownloadRequestState(); - InProcDownloads[uploadOptions.Id] = reqState; - reqState.options = uploadOptions; - reqState.request = webRequest; - - try - { - // Associate cookies with the request - // This is an async call, so we need to await it in order to preserve proper control flow - Task cookieTask = CopyCookiesFromWebBrowser(webRequest); - cookieTask.Wait(); - } - catch (AggregateException ae) - { - DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, - new FileTransferError(FileTransfer.ConnectionError, uploadOptions.FilePath, uploadOptions.Server, 0, ae.InnerException.Message))); - return; - } - - if (!string.IsNullOrEmpty(uploadOptions.Headers)) - { - Dictionary headers = parseHeaders(uploadOptions.Headers); - if (headers != null) - { - foreach (string key in headers.Keys) - { - webRequest.Headers[key] = headers[key]; - } - } - } - - webRequest.BeginGetRequestStream(uploadCallback, reqState); - } - catch (Exception /*ex*/) - { - DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(ConnectionError)),callbackId); - } - } - - // example : "{\"Authorization\":\"Basic Y29yZG92YV91c2VyOmNvcmRvdmFfcGFzc3dvcmQ=\"}" - protected Dictionary parseHeaders(string jsonHeaders) - { - try - { - if (FileTransfer.JsonDeserializeUsingJsonNet != null) - { - return ((Header[])FileTransfer.JsonDeserializeUsingJsonNet.Invoke(null, new object[] { jsonHeaders, true })) - .ToDictionary(header => header.Name, header => header.Value); - } - else - { - return JsonHelper.Deserialize(jsonHeaders) - .ToDictionary(header => header.Name, header => header.Value); - } - } - catch (Exception) - { - Debug.WriteLine("Failed to parseHeaders from string :: " + jsonHeaders); - } - return new Dictionary(); - } - - public void download(string options) - { - TransferOptions downloadOptions = null; - HttpWebRequest webRequest = null; - string callbackId; - - try - { - // source, target, trustAllHosts, this._id, headers - string[] optionStrings = JSON.JsonHelper.Deserialize(options); - - downloadOptions = new TransferOptions(); - downloadOptions.Url = optionStrings[0]; - downloadOptions.FilePath = optionStrings[1]; - - bool trustAll = false; - bool.TryParse(optionStrings[2],out trustAll); - downloadOptions.TrustAllHosts = trustAll; - - downloadOptions.Id = optionStrings[3]; - downloadOptions.Headers = optionStrings[4]; - downloadOptions.CallbackId = callbackId = optionStrings[5]; - } - catch (Exception) - { - DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); - return; - } - - try - { - // is the URL a local app file? - if (downloadOptions.Url.StartsWith("x-wmapp0") || downloadOptions.Url.StartsWith("file:")) - { - using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) - { - string cleanUrl = downloadOptions.Url.Replace("x-wmapp0:", "").Replace("file:", "").Replace("//",""); - - // pre-emptively create any directories in the FilePath that do not exist - string directoryName = getDirectoryName(downloadOptions.FilePath); - if (!string.IsNullOrEmpty(directoryName) && !isoFile.DirectoryExists(directoryName)) - { - isoFile.CreateDirectory(directoryName); - } - - // just copy from one area of iso-store to another ... - if (isoFile.FileExists(downloadOptions.Url)) - { - isoFile.CopyFile(downloadOptions.Url, downloadOptions.FilePath); - } - else - { - // need to unpack resource from the dll - Uri uri = new Uri(cleanUrl, UriKind.Relative); - var resource = Application.GetResourceStream(uri); - - if (resource != null) - { - // create the file destination - if (!isoFile.FileExists(downloadOptions.FilePath)) - { - var destFile = isoFile.CreateFile(downloadOptions.FilePath); - destFile.Close(); - } - - using (FileStream fileStream = new IsolatedStorageFileStream(downloadOptions.FilePath, FileMode.Open, FileAccess.Write, isoFile)) - { - long totalBytes = resource.Stream.Length; - int bytesRead = 0; - using (BinaryReader reader = new BinaryReader(resource.Stream)) - { - using (BinaryWriter writer = new BinaryWriter(fileStream)) - { - int BUFFER_SIZE = 1024; - byte[] buffer; - - while (true) - { - buffer = reader.ReadBytes(BUFFER_SIZE); - // fire a progress event ? - bytesRead += buffer.Length; - if (buffer.Length > 0) - { - writer.Write(buffer); - DispatchFileTransferProgress(bytesRead, totalBytes, callbackId); - } - else - { - writer.Close(); - reader.Close(); - fileStream.Close(); - break; - } - } - } - } - } - } - } - } - - File.FileEntry entry = File.FileEntry.GetEntry(downloadOptions.FilePath); - if (entry != null) - { - DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entry), callbackId); - } - else - { - DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, File.NOT_FOUND_ERR), callbackId); - } - - return; - } - else - { - // otherwise it is web-bound, we will actually download it - //Debug.WriteLine("Creating WebRequest for url : " + downloadOptions.Url); - webRequest = (HttpWebRequest)WebRequest.Create(downloadOptions.Url); - } - } - catch (Exception /*ex*/) - { - DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, - new FileTransferError(InvalidUrlError, downloadOptions.Url, null, 0))); - return; - } - - if (downloadOptions != null && webRequest != null) - { - DownloadRequestState state = new DownloadRequestState(); - state.options = downloadOptions; - state.request = webRequest; - InProcDownloads[downloadOptions.Id] = state; - - try - { - // Associate cookies with the request - // This is an async call, so we need to await it in order to preserve proper control flow - Task cookieTask = CopyCookiesFromWebBrowser(webRequest); - cookieTask.Wait(); - } - catch (AggregateException ae) - { - DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, - new FileTransferError(FileTransfer.ConnectionError, downloadOptions.Url, downloadOptions.FilePath, 0, ae.InnerException.Message))); - return; - } - - if (!string.IsNullOrEmpty(downloadOptions.Headers)) - { - Dictionary headers = parseHeaders(downloadOptions.Headers); - foreach (string key in headers.Keys) - { - webRequest.Headers[key] = headers[key]; - } - } - - try - { - webRequest.BeginGetResponse(new AsyncCallback(downloadCallback), state); - } - catch (WebException) - { - // eat it - } - // dispatch an event for progress ( 0 ) - lock (state) - { - if (!state.isCancelled) - { - var plugRes = new PluginResult(PluginResult.Status.OK, new FileTransferProgress()); - plugRes.KeepCallback = true; - plugRes.CallbackId = callbackId; - DispatchCommandResult(plugRes, callbackId); - } - } - } - } - - public void abort(string options) - { - Debug.WriteLine("Abort :: " + options); - string[] optionStrings = JSON.JsonHelper.Deserialize(options); - string id = optionStrings[0]; - string callbackId = optionStrings[1]; - - if (id != null && InProcDownloads.ContainsKey(id)) - { - DownloadRequestState state = InProcDownloads[id]; - if (!state.isCancelled) - { // prevent multiple callbacks for the same abort - state.isCancelled = true; - if (!state.request.HaveResponse) - { - state.request.Abort(); - InProcDownloads.Remove(id); - //callbackId = state.options.CallbackId; - //state = null; - DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, - new FileTransferError(FileTransfer.AbortError)), - state.options.CallbackId); - } - } - } - else - { - DispatchCommandResult(new PluginResult(PluginResult.Status.IO_EXCEPTION), callbackId); // TODO: is it an IO exception? - } - } - - private void DispatchFileTransferProgress(long bytesLoaded, long bytesTotal, string callbackId, bool keepCallback = true) - { - Debug.WriteLine("DispatchFileTransferProgress : " + callbackId); - // send a progress change event - FileTransferProgress progEvent = new FileTransferProgress(bytesTotal); - progEvent.BytesLoaded = bytesLoaded; - PluginResult plugRes = new PluginResult(PluginResult.Status.OK, progEvent); - plugRes.KeepCallback = keepCallback; - plugRes.CallbackId = callbackId; - DispatchCommandResult(plugRes, callbackId); - } - - /// - /// - /// - /// - private void downloadCallback(IAsyncResult asynchronousResult) - { - DownloadRequestState reqState = (DownloadRequestState)asynchronousResult.AsyncState; - HttpWebRequest request = reqState.request; - - string callbackId = reqState.options.CallbackId; - try - { - HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult); - - // send a progress change event - DispatchFileTransferProgress(0, response.ContentLength, callbackId); - - using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) - { - // create any directories in the path that do not exist - string directoryName = getDirectoryName(reqState.options.FilePath); - if (!string.IsNullOrEmpty(directoryName) && !isoFile.DirectoryExists(directoryName)) - { - isoFile.CreateDirectory(directoryName); - } - - // create the file if not exists - if (!isoFile.FileExists(reqState.options.FilePath)) - { - var file = isoFile.CreateFile(reqState.options.FilePath); - file.Close(); - } - - using (FileStream fileStream = new IsolatedStorageFileStream(reqState.options.FilePath, FileMode.Open, FileAccess.Write, isoFile)) - { - long totalBytes = response.ContentLength; - int bytesRead = 0; - using (BinaryReader reader = new BinaryReader(response.GetResponseStream())) - { - using (BinaryWriter writer = new BinaryWriter(fileStream)) - { - int BUFFER_SIZE = 1024; - byte[] buffer; - - while (true) - { - buffer = reader.ReadBytes(BUFFER_SIZE); - // fire a progress event ? - bytesRead += buffer.Length; - if (buffer.Length > 0 && !reqState.isCancelled) - { - writer.Write(buffer); - DispatchFileTransferProgress(bytesRead, totalBytes, callbackId); - } - else - { - writer.Close(); - reader.Close(); - fileStream.Close(); - break; - } - System.Threading.Thread.Sleep(1); - } - } - } - } - if (reqState.isCancelled) - { - isoFile.DeleteFile(reqState.options.FilePath); - } - } - - if (reqState.isCancelled) - { - DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(AbortError)), - callbackId); - } - else - { - File.FileEntry entry = new File.FileEntry(reqState.options.FilePath); - DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entry), callbackId); - } - } - catch (IsolatedStorageException) - { - // Trying to write the file somewhere within the IsoStorage. - DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(FileNotFoundError)), - callbackId); - } - catch (SecurityException) - { - // Trying to write the file somewhere not allowed. - DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(FileNotFoundError)), - callbackId); - } - catch (WebException webex) - { - // TODO: probably need better work here to properly respond with all http status codes back to JS - // Right now am jumping through hoops just to detect 404. - HttpWebResponse response = (HttpWebResponse)webex.Response; - if ((webex.Status == WebExceptionStatus.ProtocolError && response.StatusCode == HttpStatusCode.NotFound) - || webex.Status == WebExceptionStatus.UnknownError) - { - // Weird MSFT detection of 404... seriously... just give us the f(*&#$@ status code as a number ffs!!! - // "Numbers for HTTP status codes? Nah.... let's create our own set of enums/structs to abstract that stuff away." - // FACEPALM - // Or just cast it to an int, whiner ... -jm - int statusCode = (int)response.StatusCode; - string body = ""; - - using (Stream streamResponse = response.GetResponseStream()) - { - using (StreamReader streamReader = new StreamReader(streamResponse)) - { - body = streamReader.ReadToEnd(); - } - } - FileTransferError ftError = new FileTransferError(ConnectionError, null, null, statusCode, body); - DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ftError), - callbackId); - } - else - { - lock (reqState) - { - if (!reqState.isCancelled) - { - DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, - new FileTransferError(ConnectionError)), - callbackId); - } - else - { - Debug.WriteLine("It happened"); - } - } - } - } - catch (Exception) - { - DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, - new FileTransferError(FileNotFoundError)), - callbackId); - } - - //System.Threading.Thread.Sleep(1000); - if (InProcDownloads.ContainsKey(reqState.options.Id)) - { - InProcDownloads.Remove(reqState.options.Id); - } - } - - /// - /// Read file from Isolated Storage and sends it to server - /// - /// - private void uploadCallback(IAsyncResult asynchronousResult) - { - DownloadRequestState reqState = (DownloadRequestState)asynchronousResult.AsyncState; - HttpWebRequest webRequest = reqState.request; - string callbackId = reqState.options.CallbackId; - - try - { - using (Stream requestStream = (webRequest.EndGetRequestStream(asynchronousResult))) - { - string lineStart = "--"; - string lineEnd = Environment.NewLine; - byte[] boundaryBytes = System.Text.Encoding.UTF8.GetBytes(lineStart + Boundary + lineEnd); - string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"" + lineEnd + lineEnd + "{1}" + lineEnd; - - if (!string.IsNullOrEmpty(reqState.options.Params)) - { - Dictionary paramMap = parseHeaders(reqState.options.Params); - foreach (string key in paramMap.Keys) - { - requestStream.Write(boundaryBytes, 0, boundaryBytes.Length); - string formItem = string.Format(formdataTemplate, key, paramMap[key]); - byte[] formItemBytes = System.Text.Encoding.UTF8.GetBytes(formItem); - requestStream.Write(formItemBytes, 0, formItemBytes.Length); - } - } - using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) - { - if (!isoFile.FileExists(reqState.options.FilePath)) - { - DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(FileNotFoundError, reqState.options.Server, reqState.options.FilePath, 0))); - return; - } - - byte[] endRequest = System.Text.Encoding.UTF8.GetBytes(lineEnd + lineStart + Boundary + lineStart + lineEnd); - long totalBytesToSend = 0; - - using (FileStream fileStream = new IsolatedStorageFileStream(reqState.options.FilePath, FileMode.Open, isoFile)) - { - string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"" + lineEnd + "Content-Type: {2}" + lineEnd + lineEnd; - string header = string.Format(headerTemplate, reqState.options.FileKey, reqState.options.FileName, reqState.options.MimeType); - byte[] headerBytes = System.Text.Encoding.UTF8.GetBytes(header); - - byte[] buffer = new byte[4096]; - int bytesRead = 0; - //sent bytes needs to be reseted before new upload - bytesSent = 0; - totalBytesToSend = fileStream.Length; - - requestStream.Write(boundaryBytes, 0, boundaryBytes.Length); - - requestStream.Write(headerBytes, 0, headerBytes.Length); - - while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) - { - if (!reqState.isCancelled) - { - requestStream.Write(buffer, 0, bytesRead); - bytesSent += bytesRead; - DispatchFileTransferProgress(bytesSent, totalBytesToSend, callbackId); - System.Threading.Thread.Sleep(1); - } - else - { - throw new Exception("UploadCancelledException"); - } - } - } - - requestStream.Write(endRequest, 0, endRequest.Length); - } - } - // webRequest - - webRequest.BeginGetResponse(ReadCallback, reqState); - } - catch (Exception /*ex*/) - { - if (!reqState.isCancelled) - { - DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(ConnectionError)), callbackId); - } - } - } - - /// - /// Reads response into FileUploadResult - /// - /// - private void ReadCallback(IAsyncResult asynchronousResult) - { - DownloadRequestState reqState = (DownloadRequestState)asynchronousResult.AsyncState; - try - { - HttpWebRequest webRequest = reqState.request; - string callbackId = reqState.options.CallbackId; - - if (InProcDownloads.ContainsKey(reqState.options.Id)) - { - InProcDownloads.Remove(reqState.options.Id); - } - - using (HttpWebResponse response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult)) - { - using (Stream streamResponse = response.GetResponseStream()) - { - using (StreamReader streamReader = new StreamReader(streamResponse)) - { - string responseString = streamReader.ReadToEnd(); - Deployment.Current.Dispatcher.BeginInvoke(() => - { - DispatchCommandResult(new PluginResult(PluginResult.Status.OK, new FileUploadResult(bytesSent, (long)response.StatusCode, responseString))); - }); - } - } - } - } - catch (WebException webex) - { - // TODO: probably need better work here to properly respond with all http status codes back to JS - // Right now am jumping through hoops just to detect 404. - if ((webex.Status == WebExceptionStatus.ProtocolError && ((HttpWebResponse)webex.Response).StatusCode == HttpStatusCode.NotFound) - || webex.Status == WebExceptionStatus.UnknownError) - { - int statusCode = (int)((HttpWebResponse)webex.Response).StatusCode; - FileTransferError ftError = new FileTransferError(ConnectionError, null, null, statusCode); - DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ftError), reqState.options.CallbackId); - } - else - { - DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, - new FileTransferError(ConnectionError)), - reqState.options.CallbackId); - } - } - catch (Exception /*ex*/) - { - FileTransferError transferError = new FileTransferError(ConnectionError, reqState.options.Server, reqState.options.FilePath, 403); - DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, transferError), reqState.options.CallbackId); - } - } - - // Gets the full path without the filename - private string getDirectoryName(String filePath) - { - string directoryName; - try - { - directoryName = filePath.Substring(0, filePath.LastIndexOf('/')); - } - catch - { - directoryName = ""; - } - return directoryName; - } - } -} diff --git a/plugins/cordova-plugin-file-transfer/tests/package.json b/plugins/cordova-plugin-file-transfer/tests/package.json deleted file mode 100644 index a02fa86..0000000 --- a/plugins/cordova-plugin-file-transfer/tests/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "cordova-plugin-file-transfer-tests", - "version": "1.6.3-dev", - "description": "", - "cordova": { - "id": "cordova-plugin-file-transfer-tests", - "platforms": [] - }, - "keywords": [ - "ecosystem:cordova" - ], - "author": "", - "license": "Apache 2.0" -} diff --git a/plugins/cordova-plugin-file-transfer/tests/plugin.xml b/plugins/cordova-plugin-file-transfer/tests/plugin.xml deleted file mode 100644 index fabb5e2..0000000 --- a/plugins/cordova-plugin-file-transfer/tests/plugin.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - - - Cordova File Transfer Plugin Tests - Apache 2.0 - - - - - - - - diff --git a/plugins/cordova-plugin-file-transfer/tests/tests.js b/plugins/cordova-plugin-file-transfer/tests/tests.js deleted file mode 100644 index c8d9ef3..0000000 --- a/plugins/cordova-plugin-file-transfer/tests/tests.js +++ /dev/null @@ -1,1739 +0,0 @@ -/* -* -* 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 exports, cordova, FileTransfer, FileTransferError, FileUploadOptions, LocalFileSystem, WinJS */ - -/* jshint jasmine: true */ - -exports.defineAutoTests = function () { - - "use strict"; - - // constants - var ONE_SECOND = 1000; // in milliseconds - var GRACE_TIME_DELTA = 600; // in milliseconds - var DEFAULT_FILESYSTEM_SIZE = 1024 * 50; // filesystem size in bytes - var UNKNOWN_HOST = "http://foobar.apache.org"; - var DOWNLOAD_TIMEOUT = 15 * ONE_SECOND; - var LONG_TIMEOUT = 60 * ONE_SECOND; - var UPLOAD_TIMEOUT = 15 * ONE_SECOND; - var ABORT_DELAY = 100; // for abort() tests - var LATIN1_SYMBOLS = '¥§©ÆÖÑøøø¼'; - var DATA_URI_PREFIX = "data:image/png;base64,"; - var DATA_URI_CONTENT = "iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="; - var DATA_URI_CONTENT_LENGTH = 85; // bytes. (This is the raw file size: used https://en.wikipedia.org/wiki/File:Red-dot-5px.png from https://en.wikipedia.org/wiki/Data_URI_scheme) - var RETRY_COUNT = 100; // retry some flaky tests (yes, THIS many times, due to Heroku server instability) - var RETRY_INTERVAL = 100; - - // upload test server address - // NOTE: - // more info at https://github.com/apache/cordova-labs/tree/cordova-filetransfer - // Will get it from the config - // you can specify it as a 'FILETRANSFER_SERVER_ADDRESS' variable upon test plugin installation - // or change the default value in plugin.xml - var SERVER = ""; - var SERVER_WITH_CREDENTIALS = ""; - - // flags - var isWindows = cordova.platformId === "windows8" || cordova.platformId === "windows"; - var isWindowsPhone81 = isWindows && WinJS.Utilities.isPhone; - var isWP8 = cordova.platformId === "windowsphone"; - var isBrowser = cordova.platformId === "browser"; - var isIE = isBrowser && navigator.userAgent.indexOf("Trident") >= 0; - var isIos = cordova.platformId === "ios"; - var isIot = cordova.platformId === "android" && navigator.userAgent.indexOf("iot") >= 0; - - // tests - describe("FileTransferError", function () { - - it("should exist", function () { - expect(FileTransferError).toBeDefined(); - }); - - it("should be constructable", function () { - var transferError = new FileTransferError(); - expect(transferError).toBeDefined(); - }); - - it("filetransfer.spec.3 should expose proper constants", function () { - - expect(FileTransferError.FILE_NOT_FOUND_ERR).toBeDefined(); - expect(FileTransferError.INVALID_URL_ERR).toBeDefined(); - expect(FileTransferError.CONNECTION_ERR).toBeDefined(); - expect(FileTransferError.ABORT_ERR).toBeDefined(); - expect(FileTransferError.NOT_MODIFIED_ERR).toBeDefined(); - - expect(FileTransferError.FILE_NOT_FOUND_ERR).toBe(1); - expect(FileTransferError.INVALID_URL_ERR).toBe(2); - expect(FileTransferError.CONNECTION_ERR).toBe(3); - expect(FileTransferError.ABORT_ERR).toBe(4); - expect(FileTransferError.NOT_MODIFIED_ERR).toBe(5); - }); - }); - - describe("FileUploadOptions", function () { - - it("should exist", function () { - expect(FileUploadOptions).toBeDefined(); - }); - - it("should be constructable", function () { - var transferOptions = new FileUploadOptions(); - expect(transferOptions).toBeDefined(); - }); - }); - - describe("FileTransfer", function () { - this.persistentRoot = null; - this.tempRoot = null; - - // named callbacks - var unexpectedCallbacks = { - httpFail: function () {}, - httpWin: function () {}, - fileSystemFail: function () {}, - fileSystemWin: function () {}, - fileOperationFail: function () {}, - fileOperationWin: function () {}, - }; - - var expectedCallbacks = { - unsupportedOperation: function (response) { - console.log("spec called unsupported functionality; response:", response); - }, - }; - - // helpers - var deleteFile = function (fileSystem, name, done) { - fileSystem.getFile(name, null, - function (fileEntry) { - fileEntry.remove( - function () { - done(); - }, - function () { - throw new Error("failed to delete: '" + name + "'"); - } - ); - }, - function () { - done(); - } - ); - }; - - var writeFile = function (fileSystem, name, content, success, done) { - var fileOperationFail = function() { - unexpectedCallbacks.fileOperationFail(); - done(); - }; - - fileSystem.getFile(name, { create: true }, - function (fileEntry) { - fileEntry.createWriter(function (writer) { - - writer.onwrite = function () { - success(fileEntry); - }; - - writer.onabort = function (evt) { - throw new Error("aborted creating test file '" + name + "': " + evt); - }; - - writer.error = function (evt) { - throw new Error("aborted creating test file '" + name + "': " + evt); - }; - - if (cordova.platformId === "browser") { - var blob = new Blob([content + "\n"], { type: "text/plain" }); - writer.write(blob); - } else { - writer.write(content + "\n"); - } - - }, fileOperationFail); - }, - function () { - throw new Error("could not create test file '" + name + "'"); - } - ); - }; - - // according to documentation, wp8 does not support onProgress: - // https://github.com/apache/cordova-plugin-file-transfer/blob/master/doc/index.md#supported-platforms - var wp8OnProgressHandler = function () {}; - - var defaultOnProgressHandler = function (event) { - if (event.lengthComputable) { - expect(event.loaded).toBeGreaterThan(1); - expect(event.total).toBeGreaterThan(0); - expect(event.total).not.toBeLessThan(event.loaded); - expect(event.lengthComputable).toBe(true, "lengthComputable"); - } else { - // In IE, when lengthComputable === false, event.total somehow is equal to 2^64 - if (isIE) { - expect(event.total).toBe(Math.pow(2, 64)); - } else { - // iOS returns -1, and other platforms return 0 - expect(event.total).toBeLessThan(1); - } - } - }; - - var getMalformedUrl = function () { - if (cordova.platformId === "android" || cordova.platformId === "amazon-fireos") { - // bad protocol causes a MalformedUrlException on Android - return "httpssss://example.com"; - } else { - // iOS doesn't care about protocol, space in hostname causes error - return "httpssss://exa mple.com"; - } - }; - - var setServerAddress = function (address) { - SERVER = address; - SERVER_WITH_CREDENTIALS = SERVER.replace('http://', 'http://cordova_user:cordova_password@'); - }; - - // NOTE: - // there are several beforeEach calls, one per async call; since calling done() - // signifies a completed async call, each async call needs its own done(), and - // therefore its own beforeEach - beforeEach(function (done) { - var specContext = this; - - window.requestFileSystem(LocalFileSystem.PERSISTENT, DEFAULT_FILESYSTEM_SIZE, - function (fileSystem) { - specContext.persistentRoot = fileSystem.root; - done(); - }, - function () { - throw new Error("Failed to initialize persistent file system."); - } - ); - }); - - beforeEach(function (done) { - var specContext = this; - - window.requestFileSystem(LocalFileSystem.TEMPORARY, DEFAULT_FILESYSTEM_SIZE, - function (fileSystem) { - specContext.tempRoot = fileSystem.root; - done(); - }, - function () { - throw new Error("Failed to initialize temporary file system."); - } - ); - }); - - // spy on all named callbacks - beforeEach(function() { - - // ignore the actual implementations of the unexpected callbacks - for (var callback in unexpectedCallbacks) { - if (unexpectedCallbacks.hasOwnProperty(callback)) { - spyOn(unexpectedCallbacks, callback); - } - } - - // but run the implementations of the expected callbacks - for (callback in expectedCallbacks) { // jshint ignore: line - if (expectedCallbacks.hasOwnProperty(callback)) { - spyOn(expectedCallbacks, callback).and.callThrough(); - } - } - }); - - // at the end, check that none of the unexpected callbacks got called, - // and act on the expected callbacks - afterEach(function() { - for (var callback in unexpectedCallbacks) { - if (unexpectedCallbacks.hasOwnProperty(callback)) { - expect(unexpectedCallbacks[callback]).not.toHaveBeenCalled(); - } - } - - if (expectedCallbacks.unsupportedOperation.calls.any()) { - pending(); - } - }); - - it ("util spec: get file transfer server url", function () { - try { - // attempt to synchronously load medic config - var xhr = new XMLHttpRequest(); - xhr.open("GET", "../fileTransferOpts.json", false); - xhr.send(null); - var parsedCfg = JSON.parse(xhr.responseText); - if (parsedCfg.serverAddress) { - setServerAddress(parsedCfg.serverAddress); - } - } catch (ex) { - console.error('Unable to load file transfer server url: ' + ex); - console.error('Note: if you are testing this on cordova-ios with cordova-plugin-wkwebview-engine, that may be why you are getting this error. See https://issues.apache.org/jira/browse/CB-10144.'); - fail(ex); - } - }); - - it("should initialise correctly", function() { - expect(this.persistentRoot).toBeDefined(); - expect(this.tempRoot).toBeDefined(); - }); - - it("should exist", function () { - expect(FileTransfer).toBeDefined(); - }); - - it("filetransfer.spec.1 should be constructable", function () { - var transfer = new FileTransfer(); - expect(transfer).toBeDefined(); - }); - - it("filetransfer.spec.2 should expose proper functions", function () { - - var transfer = new FileTransfer(); - - expect(transfer.upload).toBeDefined(); - expect(transfer.download).toBeDefined(); - - expect(transfer.upload).toEqual(jasmine.any(Function)); - expect(transfer.download).toEqual(jasmine.any(Function)); - }); - - describe("methods", function() { - this.transfer = null; - this.root = null; - this.fileName = null; - this.localFilePath = null; - - beforeEach(function() { - - this.transfer = new FileTransfer(); - - // assign onprogress handler - this.transfer.onprogress = isWP8 ? wp8OnProgressHandler : defaultOnProgressHandler; - - // spy on the onprogress handler, but still call through to it - spyOn(this.transfer, "onprogress").and.callThrough(); - - this.root = this.persistentRoot; - this.fileName = "testFile.txt"; - this.localFilePath = this.root.toURL() + this.fileName; - }); - - // NOTE: - // if download tests are failing, check the - // URL white list for the following URLs: - // - 'httpssss://example.com' - // - 'apache.org', with subdomains="true" - // - 'cordova-filetransfer.jitsu.com' - describe("download", function () { - - // helpers - var verifyDownload = function (fileEntry, specContext) { - expect(fileEntry.name).toBe(specContext.fileName); - }; - - // delete the downloaded file - afterEach(function (done) { - deleteFile(this.root, this.fileName, done); - }); - - it("ensures that test file does not exist", function (done) { - deleteFile(this.root, this.fileName, done); - }); - - it("filetransfer.spec.4 should download a file", function (done) { - var fileURL = SERVER + "/robots.txt"; - var specContext = this; - - var fileWin = function (blob) { - - if (specContext.transfer.onprogress.calls.any()) { - var lastProgressEvent = specContext.transfer.onprogress.calls.mostRecent().args[0]; - expect(lastProgressEvent.loaded).not.toBeGreaterThan(blob.size); - } else { - console.log("no progress events were emitted"); - } - - done(); - }; - - var fileSystemFail = function() { - unexpectedCallbacks.fileSystemFail(); - done(); - }; - - var downloadFail = function() { - unexpectedCallbacks.httpFail(); - done(); - }; - - var downloadWin = function (entry) { - - verifyDownload(entry, specContext); - - // verify the FileEntry representing this file - entry.file(fileWin, fileSystemFail); - }; - - specContext.transfer.download(fileURL, specContext.localFilePath, downloadWin, downloadFail); - }, DOWNLOAD_TIMEOUT * 10); // to give Heroku server some time to wake up - - it("filetransfer.spec.4.1 should download a file using target name with space", function (done) { - - var fileURL = SERVER + "/robots.txt"; - this.fileName = "test file.txt"; - this.localFilePath = this.root.toURL() + this.fileName; - - var specContext = this; - - var fileWin = function (blob) { - - if (specContext.transfer.onprogress.calls.any()) { - var lastProgressEvent = specContext.transfer.onprogress.calls.mostRecent().args[0]; - expect(lastProgressEvent.loaded).not.toBeGreaterThan(blob.size); - } else { - console.log("no progress events were emitted"); - } - - done(); - }; - - var fileSystemFail = function() { - unexpectedCallbacks.fileSystemFail(); - done(); - }; - - var downloadFail = function() { - unexpectedCallbacks.httpFail(); - done(); - }; - - var downloadWin = function (entry) { - - verifyDownload(entry, specContext); - - // verify the FileEntry representing this file - entry.file(fileWin, fileSystemFail); - }; - - specContext.transfer.download(fileURL, specContext.localFilePath, downloadWin, downloadFail); - }, DOWNLOAD_TIMEOUT); - - it("filetransfer.spec.5 should download a file using http basic auth", function (done) { - var fileURL = SERVER_WITH_CREDENTIALS + "/download_basic_auth"; - var specContext = this; - - var downloadWin = function (entry) { - verifyDownload(entry, specContext); - done(); - }; - - var downloadFail = function() { - unexpectedCallbacks.httpFail(); - done(); - }; - - specContext.transfer.download(fileURL, specContext.localFilePath, downloadWin, downloadFail); - }, DOWNLOAD_TIMEOUT); - - it("filetransfer.spec.6 should get 401 status on http basic auth failure", function (done) { - // NOTE: - // using server without credentials - var fileURL = SERVER + "/download_basic_auth"; - - var downloadFail = function (error) { - expect(error.http_status).toBe(401); - expect(error.http_status).not.toBe(404, "Ensure " + fileURL + " is in the white list"); - done(); - }; - - var downloadWin = function() { - unexpectedCallbacks.httpWin(); - done(); - }; - - this.transfer.download(fileURL, this.localFilePath, downloadWin, downloadFail, null, - { - headers: { - "If-Modified-Since": "Thu, 19 Mar 2015 00:00:00 GMT" - } - }); - }, DOWNLOAD_TIMEOUT); - - it("filetransfer.spec.7 should download a file using file:// (when hosted from file://)", function (done) { - // for Windows platform it's ms-appdata:/// by default, not file:// - if (isWindows) { - pending(); - return; - } - - var fileURL = window.location.protocol + "//" + window.location.pathname.replace(/ /g, "%20"); - var specContext = this; - - if (!/^file:/.exec(fileURL) && cordova.platformId !== "blackberry10") { - if (cordova.platformId === "windowsphone") { - expect(fileURL).toMatch(/^x-wmapp0:/); - } - done(); - return; - } - - var downloadWin = function (entry) { - verifyDownload(entry, specContext); - done(); - }; - - var downloadFail = function() { - unexpectedCallbacks.httpFail(); - done(); - }; - - specContext.transfer.download(fileURL, specContext.localFilePath, downloadWin, downloadFail); - }, DOWNLOAD_TIMEOUT); - - it("filetransfer.spec.8 should download a file using https://", function (done) { - var fileURL = "https://www.apache.org/licenses/"; - var specContext = this; - - var downloadFail = function() { - unexpectedCallbacks.httpFail(); - done(); - }; - - var fileOperationFail = function() { - unexpectedCallbacks.fileOperationFail(); - done(); - }; - - var fileSystemFail = function() { - unexpectedCallbacks.fileSystemFail(); - done(); - }; - - var fileWin = function (file) { - - var reader = new FileReader(); - - reader.onerror = fileOperationFail; - reader.onload = function () { - expect(reader.result).toMatch(/The Apache Software Foundation/); - done(); - }; - - reader.readAsText(file); - }; - - var downloadWin = function (entry) { - verifyDownload(entry, specContext); - entry.file(fileWin, fileSystemFail); - }; - - specContext.transfer.download(fileURL, specContext.localFilePath, downloadWin, downloadFail); - }, isWindows ? LONG_TIMEOUT : DOWNLOAD_TIMEOUT); - - it("filetransfer.spec.11 should call the error callback on abort()", function (done) { - var fileURL = "http://cordova.apache.org/downloads/BlueZedEx.mp3"; - fileURL = fileURL + "?q=" + (new Date()).getTime(); - var specContext = this; - - var downloadWin = function () { - unexpectedCallbacks.httpWin(); - done(); - }; - - specContext.transfer.download(fileURL, specContext.localFilePath, downloadWin, done); - setTimeout(function() { - specContext.transfer.abort(); - }, ABORT_DELAY); - }, DOWNLOAD_TIMEOUT); - - it("filetransfer.spec.9 should not leave partial file due to abort", function (done) { - var fileURL = "http://cordova.apache.org/downloads/logos_2.zip"; - var specContext = this; - - var fileSystemWin = function() { - unexpectedCallbacks.fileSystemWin(); - done(); - }; - - var downloadWin = function() { - unexpectedCallbacks.httpWin(); - done(); - }; - - var downloadFail = function (error) { - - var result = (error.code === FileTransferError.ABORT_ERR || error.code === FileTransferError.CONNECTION_ERR)? true: false; - if (!result) { - fail("Expected " + error.code + " to be " + FileTransferError.ABORT_ERR + " or " + FileTransferError.CONNECTION_ERR); - } - expect(specContext.transfer.onprogress).toHaveBeenCalled(); - - // check that there is no file - specContext.root.getFile(specContext.fileName, null, fileSystemWin, done); - }; - - // abort at the first onprogress event - specContext.transfer.onprogress = function (event) { - if (event.loaded > 0) { - specContext.transfer.abort(); - } - }; - - spyOn(specContext.transfer, "onprogress").and.callThrough(); - - specContext.transfer.download(fileURL, specContext.localFilePath, downloadWin, downloadFail); - }, isWindows ? LONG_TIMEOUT : DOWNLOAD_TIMEOUT); - - it("filetransfer.spec.10 should be stopped by abort()", function (done) { - var fileURL = "http://cordova.apache.org/downloads/BlueZedEx.mp3"; - fileURL = fileURL + "?q=" + (new Date()).getTime(); - var specContext = this; - - expect(specContext.transfer.abort).not.toThrow(); // should be a no-op. - - var downloadWin = function() { - unexpectedCallbacks.httpWin(); - done(); - }; - - var downloadFail = function (error) { - - expect(error.code).toBe(FileTransferError.ABORT_ERR); - - // delay calling done() to wait for the bogus abort() - setTimeout(done, GRACE_TIME_DELTA * 2); - }; - - specContext.transfer.download(fileURL, specContext.localFilePath, downloadWin, downloadFail); - setTimeout(function() { - specContext.transfer.abort(); - }, ABORT_DELAY); - - // call abort() again, after a time greater than the grace period - setTimeout(function () { - expect(specContext.transfer.abort).not.toThrow(); - }, GRACE_TIME_DELTA); - }, DOWNLOAD_TIMEOUT); - - it("filetransfer.spec.12 should get http status on failure", function (done) { - var fileURL = SERVER + "/404"; - - var downloadFail = function (error) { - - expect(error.http_status).not.toBe(401, "Ensure " + fileURL + " is in the white list"); - expect(error.http_status).toBe(404); - - // wp8 does not make difference between 404 and unknown host - if (isWP8) { - expect(error.code).toBe(FileTransferError.CONNECTION_ERR); - } else { - expect(error.code).toBe(FileTransferError.FILE_NOT_FOUND_ERR); - } - - done(); - }; - - var downloadWin = function() { - unexpectedCallbacks.httpWin(); - done(); - }; - - this.transfer.download(fileURL, this.localFilePath, downloadWin, downloadFail); - }, DOWNLOAD_TIMEOUT); - - it("filetransfer.spec.13 should get http body on failure", function (done) { - var fileURL = SERVER + "/404"; - - var downloadFail = function (error) { - - expect(error.http_status).not.toBe(401, "Ensure " + fileURL + " is in the white list"); - expect(error.http_status).toBe(404); - - expect(error.body).toBeDefined(); - expect(error.body).toMatch("You requested a 404"); - - done(); - }; - - var downloadWin = function() { - unexpectedCallbacks.httpWin(); - done(); - }; - - this.transfer.download(fileURL, this.localFilePath, downloadWin, downloadFail); - }, DOWNLOAD_TIMEOUT); - - it("filetransfer.spec.14 should handle malformed urls", function (done) { - var fileURL = getMalformedUrl(); - - var downloadFail = function (error) { - - // Note: Android needs the bad protocol to be added to the access list - // won't match because ^https?:// is prepended to the regex - // The bad protocol must begin with http to avoid automatic prefix - expect(error.http_status).not.toBe(401, "Ensure " + fileURL + " is in the white list"); - expect(error.code).toBe(FileTransferError.INVALID_URL_ERR); - - done(); - }; - - var downloadWin = function() { - unexpectedCallbacks.httpWin(); - done(); - }; - - this.transfer.download(fileURL, this.localFilePath, downloadWin, downloadFail); - }); - - it("filetransfer.spec.15 should handle unknown host", function (done) { - var fileURL = UNKNOWN_HOST; - - var downloadFail = function (error) { - expect(error.code).toBe(FileTransferError.CONNECTION_ERR); - done(); - }; - - var downloadWin = function() { - unexpectedCallbacks.httpWin(); - done(); - }; - - // turn off the onprogress handler - this.transfer.onprogress = function () {}; - - this.transfer.download(fileURL, this.localFilePath, downloadWin, downloadFail); - }, isWindows ? LONG_TIMEOUT : DOWNLOAD_TIMEOUT); - - it("filetransfer.spec.16 should handle bad file path", function (done) { - var fileURL = SERVER; - - var downloadWin = function() { - unexpectedCallbacks.httpWin(); - done(); - }; - - this.transfer.download(fileURL, "c:\\54321", downloadWin, done); - }); - - it("filetransfer.spec.17 progress should work with gzip encoding", function (done) { - - // lengthComputable false on bb10 when downloading gzip - if (cordova.platformId === "blackberry10") { - pending(); - return; - } - - var fileURL = "http://www.apache.org/"; - var specContext = this; - - var downloadWin = function (entry) { - verifyDownload(entry, specContext); - done(); - }; - - var downloadFail = function () { - unexpectedCallbacks.httpFail(); - done(); - }; - - specContext.transfer.download(fileURL, specContext.localFilePath, downloadWin,downloadFail); - }, DOWNLOAD_TIMEOUT); - - it("filetransfer.spec.30 downloaded file entries should have a toNativeURL method", function (done) { - if (cordova.platformId === "browser") { - pending(); - return; - } - - var fileURL = SERVER + "/robots.txt"; - - var downloadWin = function (entry) { - - expect(entry.toNativeURL).toBeDefined(); - expect(entry.toNativeURL).toEqual(jasmine.any(Function)); - - var nativeURL = entry.toNativeURL(); - - expect(nativeURL).toBeTruthy(); - expect(nativeURL).toEqual(jasmine.any(String)); - - if (isWindows) { - expect(nativeURL.substring(0, 14)).toBe("ms-appdata:///"); - } else if (isWP8) { - expect(nativeURL.substring(0, 1)).toBe("/"); - } else { - expect(nativeURL.substring(0, 7)).toBe("file://"); - } - - done(); - }; - - var downloadFail = function() { - unexpectedCallbacks.httpFail(); - done(); - }; - - this.transfer.download(fileURL, this.localFilePath, downloadWin, downloadFail); - }, DOWNLOAD_TIMEOUT); - - it("filetransfer.spec.28 (compatibility) should be able to download a file using local paths", function (done) { - var fileURL = SERVER + "/robots.txt"; - var specContext = this; - - var unsupported = function (response) { - expectedCallbacks.unsupportedOperation(response); - done(); - }; - - var downloadWin = function (entry) { - verifyDownload(entry, specContext); - done(); - }; - - var internalFilePath; - if (specContext.root.toInternalURL) { - internalFilePath = specContext.root.toInternalURL() + specContext.fileName; - } else { - internalFilePath = specContext.localFilePath; - } - - var downloadFail = function() { - unexpectedCallbacks.httpFail(); - done(); - }; - - // 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 transfer.download() to make sure that previously-stored - // paths are still valid. - cordova.exec(function (localPath) { - specContext.transfer.download(fileURL, localPath, downloadWin, downloadFail); - }, unsupported, "File", "_getLocalFilesystemPath", [internalFilePath]); - }); - - it("filetransfer.spec.33 should properly handle 304", function (done) { - if (isWP8) { - pending(); - return; - } - - var downloadFail = function (error) { - expect(error.http_status).toBe(304); - expect(error.code).toBe(FileTransferError.NOT_MODIFIED_ERR); - done(); - }; - - var downloadWin = function() { - unexpectedCallbacks.httpWin(); - done(); - }; - - this.transfer.download(SERVER + '/304', this.localFilePath, downloadWin, downloadFail); - }, DOWNLOAD_TIMEOUT); - - it("filetransfer.spec.35 304 should not result in the deletion of a cached file", function (done) { - if (isWP8) { - pending(); - return; - } - - var specContext = this; - - var fileOperationFail = function() { - unexpectedCallbacks.fileOperationFail(); - done(); - }; - - var fileSystemFail = function() { - unexpectedCallbacks.fileSystemFail(); - done(); - }; - - var httpWin = function() { - unexpectedCallbacks.httpWin(); - done(); - }; - - var downloadFail = function (error) { - expect(error.http_status).toBe(304); - expect(error.code).toBe(FileTransferError.NOT_MODIFIED_ERR); - - specContext.persistentRoot.getFile(specContext.fileName, { create: false }, - function (entry) { - var fileWin = function (file) { - var reader = new FileReader(); - - reader.onerror = fileOperationFail; - reader.onloadend = function () { - - expect(reader.result).toBeTruthy(); - if (reader.result !== null) { - expect(reader.result.length).toBeGreaterThan(0); - } - - done(); - }; - - reader.readAsBinaryString(file); - }; - - entry.file(fileWin, fileSystemFail); - }, - function (err) { - expect("Could not open test file '" + specContext.fileName + "': " + JSON.stringify(err)).not.toBeDefined(); - done(); - } - ); - }; - - writeFile(specContext.root, specContext.fileName, 'Temp data', function () { - specContext.transfer.download(SERVER + '/304', specContext.localFilePath, httpWin, downloadFail); - }, fileOperationFail); - }, DOWNLOAD_TIMEOUT); - - it("filetransfer.spec.36 should handle non-UTF8 encoded download response", function (done) { - // Only iOS is supported: https://issues.apache.org/jira/browse/CB-9840 - if (!isIos) { - pending(); - } - - var fileURL = SERVER + '/download_non_utf'; - var specContext = this; - - var fileOperationFail = function() { - unexpectedCallbacks.fileOperationFail(); - done(); - }; - - var fileSystemFail = function() { - unexpectedCallbacks.fileSystemFail(); - done(); - }; - - var httpFail = function() { - unexpectedCallbacks.httpFail(); - done(); - }; - - var fileWin = function (blob) { - - if (specContext.transfer.onprogress.calls.any()) { - var lastProgressEvent = specContext.transfer.onprogress.calls.mostRecent().args[0]; - expect(lastProgressEvent.loaded).not.toBeGreaterThan(blob.size); - } else { - console.log("no progress events were emitted"); - } - - expect(blob.size).toBeGreaterThan(0); - - var reader = new FileReader(); - - reader.onerror = fileOperationFail; - reader.onloadend = function () { - expect(reader.result.indexOf(LATIN1_SYMBOLS)).not.toBe(-1); - done(); - }; - - reader.readAsBinaryString(blob); - }; - - var downloadWin = function (entry) { - - verifyDownload(entry, specContext); - - // verify the FileEntry representing this file - entry.file(fileWin, fileSystemFail); - }; - - specContext.transfer.download(fileURL, specContext.localFilePath, downloadWin, httpFail); - }, UPLOAD_TIMEOUT); - }); - - describe("upload", function() { - this.uploadParams = null; - this.uploadOptions = null; - this.fileName = null; - this.fileContents = null; - this.localFilePath = null; - - // helpers - var verifyUpload = function (uploadResult, specContext) { - - expect(uploadResult.bytesSent).toBeGreaterThan(0); - expect(uploadResult.responseCode).toBe(200); - - var obj = null; - try { - obj = JSON.parse(uploadResult.response); - expect(obj.fields).toBeDefined(); - expect(obj.fields.value1).toBe("test"); - expect(obj.fields.value2).toBe("param"); - } catch (e) { - expect(obj).not.toBeNull("returned data from server should be valid json"); - } - - expect(specContext.transfer.onprogress).toHaveBeenCalled(); - }; - - beforeEach(function(done) { - var specContext = this; - - specContext.fileName = "fileToUpload.txt"; - specContext.fileContents = "upload test file"; - - specContext.uploadParams = {}; - specContext.uploadParams.value1 = "test"; - specContext.uploadParams.value2 = "param"; - - specContext.uploadOptions = new FileUploadOptions(); - specContext.uploadOptions.fileKey = "file"; - specContext.uploadOptions.fileName = specContext.fileName; - specContext.uploadOptions.mimeType = "text/plain"; - specContext.uploadOptions.params = specContext.uploadParams; - - var fileWin = function (entry) { - specContext.localFilePath = entry.toURL(); - done(); - }; - - // create a file to upload - writeFile(specContext.root, specContext.fileName, specContext.fileContents, fileWin, done); - }); - - // delete the uploaded file - afterEach(function (done) { - deleteFile(this.root, this.fileName, done); - }); - - it("filetransfer.spec.18 should be able to upload a file", function (done) { - var fileURL = SERVER + "/upload"; - var specContext = this; - - var uploadWin = function (uploadResult) { - - verifyUpload(uploadResult, specContext); - - if (cordova.platformId === "ios") { - expect(uploadResult.headers).toBeDefined("Expected headers to be defined."); - expect(uploadResult.headers["Content-Type"]).toBeDefined("Expected content-type header to be defined."); - } - - done(); - }; - - var uploadFail = function() { - unexpectedCallbacks.httpFail(); - done(); - }; - - // NOTE: removing uploadOptions cause Android to timeout - specContext.transfer.upload(specContext.localFilePath, fileURL, uploadWin, uploadFail, specContext.uploadOptions); - }, UPLOAD_TIMEOUT); - - it("filetransfer.spec.19 should be able to upload a file with http basic auth", function (done) { - var fileURL = SERVER_WITH_CREDENTIALS + "/upload_basic_auth"; - var specContext = this; - - var uploadWin = function (uploadResult) { - verifyUpload(uploadResult, specContext); - done(); - }; - - var uploadFail = function() { - unexpectedCallbacks.httpFail(); - done(); - }; - - // NOTE: removing uploadOptions cause Android to timeout - specContext.transfer.upload(specContext.localFilePath, fileURL, uploadWin, uploadFail, specContext.uploadOptions); - }, UPLOAD_TIMEOUT); - - it("filetransfer.spec.21 should be stopped by abort()", function (done) { - var fileURL = SERVER + "/upload"; - var specContext = this; - - var uploadFail = function (e) { - expect(e.code).toBe(FileTransferError.ABORT_ERR); - - // delay calling done() to wait for the bogus abort() - setTimeout(done, GRACE_TIME_DELTA * 2); - }; - - var uploadWin = function() { - unexpectedCallbacks.httpWin(); - done(); - }; - - var fileWin = function () { - - expect(specContext.transfer.abort).not.toThrow(); - - // NOTE: removing uploadOptions cause Android to timeout - specContext.transfer.upload(specContext.localFilePath, fileURL, uploadWin, uploadFail, specContext.uploadOptions); - setTimeout(function() { - specContext.transfer.abort(); - }, ABORT_DELAY); - - setTimeout(function () { - expect(specContext.transfer.abort).not.toThrow(); - }, GRACE_TIME_DELTA); - }; - - // windows store and ios are too fast, win is called before we have a chance to abort - // so let's get them busy - while not providing an extra load to the slow Android emulators - var arrayLength = ((isWindows && !isWindowsPhone81) || isIos) ? 3000000 : isIot ? 150000 : 200000; - writeFile(specContext.root, specContext.fileName, new Array(arrayLength).join("aborttest!"), fileWin, done); - }, UPLOAD_TIMEOUT); - - it("filetransfer.spec.22 should get http status and body on failure", function (done) { - var fileURL = SERVER + "/403"; - var retryCount = 0; - var self = this; - - var uploadWin = function() { - unexpectedCallbacks.httpWin(); - done(); - }; - - var uploadFail = function (error) { - if (error.http_status === 503 && ++retryCount <= RETRY_COUNT) { - // Heroku often gives this error, retry in 1 second - console.log('retrying... ' + retryCount); - setTimeout(function () { - self.transfer.upload(self.localFilePath, fileURL, uploadWin, uploadFail, self.uploadOptions); - }, RETRY_INTERVAL); - } else { - expect(error.http_status).toBe(403); - expect(error.http_status).not.toBe(401, "Ensure " + fileURL + " is in the white list"); - done(); - } - }; - - self.transfer.upload(this.localFilePath, fileURL, uploadWin, uploadFail, this.uploadOptions); - }, UPLOAD_TIMEOUT * 11); - - it("filetransfer.spec.24 should handle malformed urls", function (done) { - var fileURL = getMalformedUrl(); - - var uploadFail = function (error) { - expect(error.code).toBe(FileTransferError.INVALID_URL_ERR); - expect(error.http_status).not.toBe(401, "Ensure " + fileURL + " is in the white list"); - done(); - }; - - var uploadWin = function() { - unexpectedCallbacks.httpWin(); - done(); - }; - - this.transfer.upload(this.localFilePath, fileURL, uploadWin, uploadFail, {}); - }); - - it("filetransfer.spec.25 should handle unknown host", function (done) { - var fileURL = UNKNOWN_HOST; - - var uploadFail = function (error) { - expect(error.code).toBe(FileTransferError.CONNECTION_ERR); - expect(error.http_status).not.toBe(401, "Ensure " + fileURL + " is in the white list"); - done(); - }; - - var uploadWin = function() { - unexpectedCallbacks.httpWin(); - done(); - }; - - this.transfer.upload(this.localFilePath, fileURL, uploadWin, uploadFail, {}); - }, UPLOAD_TIMEOUT); - - it("filetransfer.spec.25 should handle missing file", function (done) { - var fileURL = SERVER + "/upload"; - - var uploadFail = function (error) { - expect(error.code).toBe(FileTransferError.FILE_NOT_FOUND_ERR); - expect(error.http_status).not.toBe(401, "Ensure " + fileURL + " is in the white list"); - done(); - }; - - var uploadWin = function() { - unexpectedCallbacks.httpWin(); - done(); - }; - - this.transfer.upload("does_not_exist.txt", fileURL, uploadWin, uploadFail); - }, UPLOAD_TIMEOUT); - - it("filetransfer.spec.26 should handle bad file path", function (done) { - var fileURL = SERVER + "/upload"; - - var uploadFail = function (error) { - expect(error.http_status).not.toBe(401, "Ensure " + fileURL + " is in the white list"); - done(); - }; - - var uploadWin = function() { - unexpectedCallbacks.httpWin(); - done(); - }; - - this.transfer.upload("c:\\54321", fileURL, uploadWin, uploadFail); - }); - - it("filetransfer.spec.27 should be able to set custom headers", function (done) { - var fileURL = SERVER + '/upload_echo_headers'; - var retryCount = 0; - var self = this; - - var uploadWin = function (uploadResult) { - - expect(uploadResult.bytesSent).toBeGreaterThan(0); - expect(uploadResult.responseCode).toBe(200); - expect(uploadResult.response).toBeDefined(); - - var responseHtml = decodeURIComponent(uploadResult.response); - - expect(responseHtml).toMatch(/CustomHeader1[\s\S]*CustomValue1/i); - expect(responseHtml).toMatch(/CustomHeader2[\s\S]*CustomValue2[\s\S]*CustomValue3/i, "Should allow array values"); - - done(); - }; - - var uploadFail = function() { - if (++retryCount >= RETRY_COUNT) { - unexpectedCallbacks.httpFail(); - done(); - } else { - console.log('retrying... ' + retryCount); - setTimeout(function () { - // NOTE: removing uploadOptions will cause Android to timeout - self.transfer.upload(self.localFilePath, fileURL, uploadWin, uploadFail, self.uploadOptions); - }, RETRY_INTERVAL); - } - }; - - this.uploadOptions.headers = { - "CustomHeader1": "CustomValue1", - "CustomHeader2": ["CustomValue2", "CustomValue3"], - }; - - // http://whatheaders.com does not support Transfer-Encoding: chunked - this.uploadOptions.chunkedMode = false; - - // NOTE: removing uploadOptions cause Android to timeout - this.transfer.upload(this.localFilePath, fileURL, uploadWin, uploadFail, this.uploadOptions); - }, UPLOAD_TIMEOUT * 11); - - it("filetransfer.spec.29 (compatibility) should be able to upload a file using local paths", function (done) { - var fileURL = SERVER + "/upload"; - var specContext = this; - - var unsupported = function (response) { - expectedCallbacks.unsupportedOperation(response); - done(); - }; - - var uploadWin = function (uploadResult) { - verifyUpload(uploadResult, specContext); - done(); - }; - - var uploadFail = function() { - unexpectedCallbacks.httpFail(); - done(); - }; - - var internalFilePath; - if (specContext.root.toInternalURL) { - internalFilePath = specContext.root.toInternalURL() + specContext.fileName; - } else { - internalFilePath = specContext.localFilePath; - } - - // 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 transfer.download() to make sure that previously-stored - // paths are still valid. - cordova.exec(function (localPath) { - specContext.transfer.upload(localPath, fileURL, uploadWin, uploadFail, specContext.uploadOptions); - }, unsupported, "File", "_getLocalFilesystemPath", [internalFilePath]); - }, UPLOAD_TIMEOUT); - - it("filetransfer.spec.31 should be able to upload a file using PUT method", function (done) { - var fileURL = SERVER + "/upload"; - var specContext = this; - - var uploadWin = function (uploadResult) { - - verifyUpload(uploadResult, specContext); - - if (cordova.platformId === "ios") { - expect(uploadResult.headers).toBeDefined("Expected headers to be defined."); - expect(uploadResult.headers["Content-Type"]).toBeDefined("Expected content-type header to be defined."); - } - - done(); - }; - - var uploadFail = function() { - unexpectedCallbacks.httpFail(); - done(); - }; - - specContext.uploadOptions.httpMethod = "PUT"; - - // NOTE: removing uploadOptions cause Android to timeout - specContext.transfer.upload(specContext.localFilePath, fileURL, uploadWin, uploadFail, specContext.uploadOptions); - }, UPLOAD_TIMEOUT); - - it("filetransfer.spec.32 should be able to upload a file (non-multipart)", function (done) { - var fileURL = SERVER + "/upload"; - var specContext = this; - - var uploadWin = function (uploadResult) { - - expect(uploadResult.bytesSent).toBeGreaterThan(0); - expect(uploadResult.responseCode).toBe(200); - expect(uploadResult.response).toBeDefined(); - if (uploadResult.response) { - expect(uploadResult.response).toEqual(specContext.fileContents + "\n"); - } - expect(specContext.transfer.onprogress).toHaveBeenCalled(); - - if (cordova.platformId === "ios") { - expect(uploadResult.headers).toBeDefined("Expected headers to be defined."); - expect(uploadResult.headers["Content-Type"]).toBeDefined("Expected content-type header to be defined."); - } - - done(); - }; - - var uploadFail = function() { - unexpectedCallbacks.httpFail(); - done(); - }; - - // Content-Type header disables multipart - specContext.uploadOptions.headers = { - "Content-Type": "text/plain" - }; - - // NOTE: removing uploadOptions cause Android to timeout - specContext.transfer.upload(specContext.localFilePath, fileURL, uploadWin, uploadFail, specContext.uploadOptions); - }, UPLOAD_TIMEOUT); - - it("filetransfer.spec.34 should not delete a file on upload error", function (done) { - - var fileURL = SERVER + "/upload"; - var specContext = this; - - var uploadFail = function (e) { - expect(e.code).toBe(FileTransferError.ABORT_ERR); - - // check that the file is there - specContext.root.getFile(specContext.fileName, null, function(entry) { - expect(entry).toBeDefined(); - // delay calling done() to wait for the bogus abort() - setTimeout(done, GRACE_TIME_DELTA * 2); - }, function(err) { - expect(err).not.toBeDefined(err && err.code); - done(); - }); - }; - - var uploadWin = function() { - unexpectedCallbacks.httpWin(); - done(); - }; - - var fileWin = function () { - - expect(specContext.transfer.abort).not.toThrow(); - - // abort at the first onprogress event - specContext.transfer.onprogress = function (event) { - if (event.loaded > 0) { - specContext.transfer.abort(); - } - }; - - // NOTE: removing uploadOptions cause Android to timeout - specContext.transfer.upload(specContext.localFilePath, fileURL, uploadWin, uploadFail, specContext.uploadOptions); - }; - - writeFile(specContext.root, specContext.fileName, new Array(100000).join("aborttest!"), fileWin, done); - }, UPLOAD_TIMEOUT); - - it("filetransfer.spec.37 should handle non-UTF8 encoded upload response", function (done) { - // Only iOS is supported: https://issues.apache.org/jira/browse/CB-9840 - if (!isIos) { - pending(); - } - - var fileURL = SERVER + '/upload_non_utf'; - var specContext = this; - - var uploadWin = function (uploadResult) { - - verifyUpload(uploadResult, specContext); - - var obj = null; - try { - obj = JSON.parse(uploadResult.response); - expect(obj.latin1Symbols).toBe(LATIN1_SYMBOLS); - } catch (e) { - expect(obj).not.toBeNull("returned data from server should be valid json"); - } - - if (cordova.platformId === 'ios') { - expect(uploadResult.headers).toBeDefined('Expected headers to be defined.'); - expect(uploadResult.headers['Content-Type']).toBeDefined('Expected content-type header to be defined.'); - } - - done(); - }; - - var uploadFail = function() { - unexpectedCallbacks.httpFail(); - done(); - }; - - // NOTE: removing uploadOptions cause Android to timeout - specContext.transfer.upload(specContext.localFilePath, fileURL, uploadWin, uploadFail, specContext.uploadOptions); - }, UPLOAD_TIMEOUT); - - it("filetransfer.spec.38 should be able to upload a file using data: source uri", function (done) { - var fileURL = SERVER + "/upload"; - var specContext = this; - - var uploadWin = function (uploadResult) { - - verifyUpload(uploadResult,specContext); - - var obj = null; - try { - obj = JSON.parse(uploadResult.response); - expect(obj.files.file.size).toBe(DATA_URI_CONTENT_LENGTH); - } catch (e) { - expect(obj).not.toBeNull("returned data from server should be valid json"); - } - - if (cordova.platformId === "ios") { - expect(uploadResult.headers).toBeDefined("Expected headers to be defined."); - expect(uploadResult.headers["Content-Type"]).toBeDefined("Expected content-type header to be defined."); - } - - done(); - }; - - var dataUri = DATA_URI_PREFIX + DATA_URI_CONTENT; - // NOTE: removing uploadOptions cause Android to timeout - specContext.transfer.upload(dataUri, fileURL, uploadWin, function (err) { - console.error('err: ' + JSON.stringify(err)); - expect(err).not.toBeDefined(); - done(); - }, specContext.uploadOptions); - }, UPLOAD_TIMEOUT); - - it("filetransfer.spec.39 should be able to upload a file using data: source uri (non-multipart)", function (done) { - var fileURL = SERVER + "/upload"; - - var uploadWin = function (uploadResult) { - - expect(uploadResult.responseCode).toBe(200); - expect(uploadResult.bytesSent).toBeGreaterThan(0); - - if (cordova.platformId === "ios") { - expect(uploadResult.headers).toBeDefined("Expected headers to be defined."); - expect(uploadResult.headers["Content-Type"]).toBeDefined("Expected content-type header to be defined."); - } - - done(); - }; - - var uploadFail = function() { - unexpectedCallbacks.httpFail(); - done(); - }; - - // Content-Type header disables multipart - this.uploadOptions.headers = { - "Content-Type": "image/png" - }; - - var dataUri = DATA_URI_PREFIX + DATA_URI_CONTENT; - // NOTE: removing uploadOptions cause Android to timeout - this.transfer.upload(dataUri, fileURL, uploadWin, uploadFail, this.uploadOptions); - }, UPLOAD_TIMEOUT); - - it("filetransfer.spec.40 should not fail to upload a file using data: source uri when the data is empty", function (done) { - var fileURL = SERVER + "/upload"; - - var dataUri = DATA_URI_PREFIX; - - var uploadFail = function() { - unexpectedCallbacks.httpFail(); - done(); - }; - - // NOTE: removing uploadOptions cause Android to timeout - this.transfer.upload(dataUri, fileURL, done, uploadFail, this.uploadOptions); - }, UPLOAD_TIMEOUT); - - it("filetransfer.spec.41 should not fail to upload a file using data: source uri when the data is empty (non-multipart)", function (done) { - if (isIos) { - // iOS does not support uploads of an empty file with __chunkedMode=true__ and `multipartMode=false`: - // request body will be empty in this case instead of 0\n\n. - pending(); - } - var fileURL = SERVER + "/upload"; - - // Content-Type header disables multipart - this.uploadOptions.headers = { - "Content-Type": "image/png" - }; - - // turn off the onprogress handler - this.transfer.onprogress = function () { }; - - var dataUri = DATA_URI_PREFIX; - - var uploadFail = function() { - unexpectedCallbacks.httpFail(); - done(); - }; - - // NOTE: removing uploadOptions cause Android to timeout - this.transfer.upload(dataUri, fileURL, done, uploadFail, this.uploadOptions); - }, UPLOAD_TIMEOUT); - - describe("chunkedMode handling", function() { - var testChunkedModeWin = function (uploadResult, specContext) { - var multipartModeEnabled = !(specContext.uploadOptions.headers && specContext.uploadOptions.headers["Content-Type"]); - var obj = null; - try { - obj = JSON.parse(uploadResult.response); - - if (specContext.uploadOptions.chunkedMode) { - if (!isIos) { - expect(obj["content-length"]).not.toBeDefined("Expected Content-Length not to be defined"); - } - expect(obj["transfer-encoding"].toLowerCase()).toEqual("chunked"); - } else { - expect(obj["content-length"]).toBeDefined("Expected Content-Length to be defined"); - expect(obj["transfer-encoding"].toLowerCase()).not.toEqual("chunked"); - } - - if (multipartModeEnabled) { - expect(obj["content-type"].indexOf("multipart/form-data")).not.toBe(-1); - } else { - expect(obj["content-type"].indexOf("multipart/form-data")).toBe(-1); - } - } catch (e) { - expect(obj).not.toBeNull("returned data from server should be valid json"); - } - }; - - var testChunkedModeBase = function(chunkedMode, multipart, done) { - var retryCount = 0; - var fileURL = SERVER + "/upload_echo_headers"; - var specContext = this; - - specContext.uploadOptions.chunkedMode = chunkedMode; - if (!multipart) { - // Content-Type header disables multipart - specContext.uploadOptions.headers = { - "Content-Type": "text/plain" - }; - } - - var uploadFail = function() { - if (++retryCount >= RETRY_COUNT) { - unexpectedCallbacks.httpFail(); - done(); - } else { - console.log('retrying... ' + retryCount); - setTimeout(function () { - // NOTE: removing uploadOptions will cause Android to timeout - specContext.transfer.upload(specContext.localFilePath, fileURL, function (uploadResult) { - testChunkedModeWin(uploadResult, specContext); - done(); - }, uploadFail, specContext.uploadOptions); - }, RETRY_INTERVAL); - } - }; - - // turn off the onprogress handler - this.transfer.onprogress = function () {}; - - // NOTE: removing uploadOptions cause Android to timeout - specContext.transfer.upload(specContext.localFilePath, fileURL, function (uploadResult) { - testChunkedModeWin(uploadResult, specContext); - done(); - }, uploadFail, specContext.uploadOptions); - }; - - it("filetransfer.spec.42 chunkedMode=false, multipart=false", function (done) { - - testChunkedModeBase.call(this, false, false, done); - }, UPLOAD_TIMEOUT * 11); - - it("filetransfer.spec.43 chunkedMode=true, multipart=false", function (done) { - - if (isWindows) { - pending(); - } - testChunkedModeBase.call(this, true, false, done); - }, UPLOAD_TIMEOUT * 11); - - it("filetransfer.spec.44 chunkedMode=false, multipart=true", function (done) { - - testChunkedModeBase.call(this, false, true, done); - }, UPLOAD_TIMEOUT * 11); - - it("filetransfer.spec.45 chunkedMode=true, multipart=true", function (done) { - - if (isWindows) { - pending(); - } - testChunkedModeBase.call(this, true, true, done); - }, UPLOAD_TIMEOUT * 11); - }); - }); - }); - }); -}; - -/******************************************************************************/ -/******************************************************************************/ -/******************************************************************************/ - -exports.defineManualTests = function (contentEl, createActionButton) { - - "use strict"; - - var imageURL = "http://apache.org/images/feather-small.gif"; - var videoURL = "http://techslides.com/demos/sample-videos/small.mp4"; - - function clearResults() { - var results = document.getElementById("info"); - results.innerHTML = ""; - } - - function downloadImg(source, urlFn, element, directory) { - var filename = source.substring(source.lastIndexOf("/") + 1); - filename = (directory || "") + filename; - - function download(fileSystem) { - var ft = new FileTransfer(); - console.log("Starting download"); - - var progress = document.getElementById("loadingStatus"); - progress.value = 0; - - ft.onprogress = function(progressEvent) { - if (progressEvent.lengthComputable) { - var currPercents = parseInt(100 * (progressEvent.loaded / progressEvent.total), 10); - if (currPercents > progress.value) { - progress.value = currPercents; - } - } else { - progress.value = null; - } - }; - - ft.download(source, fileSystem.root.toURL() + filename, function (entry) { - console.log("Download complete"); - element.src = urlFn(entry); - console.log("Src URL is " + element.src); - console.log("Inserting element"); - document.getElementById("info").appendChild(element); - }, function (e) { console.log("ERROR: ft.download " + e.code); }); - } - console.log("Requesting filesystem"); - clearResults(); - window.requestFileSystem(LocalFileSystem.TEMPORARY, 0, function (fileSystem) { - console.log("Checking for existing file"); - if (typeof directory !== "undefined") { - console.log("Checking for existing directory."); - fileSystem.root.getDirectory(directory, {}, function (dirEntry) { - dirEntry.removeRecursively(function () { - download(fileSystem); - }, function () { console.log("ERROR: dirEntry.removeRecursively"); }); - }, function () { - download(fileSystem); - }); - } else { - fileSystem.root.getFile(filename, { create: false }, function (entry) { - console.log("Removing existing file"); - entry.remove(function () { - download(fileSystem); - }, function () { console.log("ERROR: entry.remove"); }); - }, function () { - download(fileSystem); - }); - } - }, function () { console.log("ERROR: requestFileSystem"); }); - } - - /******************************************************************************/ - - var progress_tag = ""; - var file_transfer_tests = "

Image File Transfer Tests

" + - "

The following tests should display an image of the Apache feather in the status box

" + - "
" + - "
" + - "
" + - "

Video File Transfer Tests

" + - "

The following tests should display a video in the status box. The video should play when play is pressed

" + - "
" + - "
"; - - contentEl.innerHTML = "
" + "
" + progress_tag + - file_transfer_tests; - - createActionButton("Download and display img (cdvfile)", function () { - downloadImg(imageURL, function (entry) { return entry.toInternalURL(); }, new Image()); - }, "cdv_image"); - - createActionButton("Download and display img (native)", function () { - downloadImg(imageURL, function (entry) { return entry.toURL(); }, new Image()); - }, "native_image"); - - createActionButton("Download to a non-existent dir (should work)", function () { - downloadImg(imageURL, function (entry) { return entry.toURL(); }, new Image(), "/nonExistentDirTest/"); - }, "non-existent_dir"); - - createActionButton("Download and play video (cdvfile)", function () { - var videoElement = document.createElement("video"); - videoElement.controls = "controls"; - downloadImg(videoURL, function (entry) { return entry.toInternalURL(); }, videoElement); - }, "cdv_video"); - - createActionButton("Download and play video (native)", function () { - var videoElement = document.createElement("video"); - videoElement.controls = "controls"; - downloadImg(videoURL, function (entry) { return entry.toURL(); }, videoElement); - }, "native_video"); -}; diff --git a/plugins/cordova-plugin-file-transfer/types/index.d.ts b/plugins/cordova-plugin-file-transfer/types/index.d.ts deleted file mode 100644 index ad8d994..0000000 --- a/plugins/cordova-plugin-file-transfer/types/index.d.ts +++ /dev/null @@ -1,136 +0,0 @@ -// Type definitions for Apache Cordova FileTransfer plugin -// Project: https://github.com/apache/cordova-plugin-file-transfer -// Definitions by: Microsoft Open Technologies Inc. -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// -// Copyright (c) Microsoft Open Technologies Inc -// Licensed under the MIT license - -/// - -/** - * The FileTransfer object provides a way to upload files using an HTTP multi-part POST request, - * and to download files as well. - */ -interface FileTransfer { - /** Called with a ProgressEvent whenever a new chunk of data is transferred. */ - onprogress: (event: ProgressEvent) => void; - /** - * Sends a file to a server. - * @param fileURL Filesystem URL representing the file on the device. For backwards compatibility, - * this can also be the full path of the file on the device. - * @param server URL of the server to receive the file, as encoded by encodeURI(). - * @param successCallback A callback that is passed a FileUploadResult object. - * @param errorCallback A callback that executes if an error occurs retrieving the FileUploadResult. - * Invoked with a FileTransferError object. - * @param options Optional parameters. - * @param trustAllHosts Optional parameter, defaults to false. If set to true, it accepts all security certificates. - * This is useful since Android rejects self-signed security certificates. - * Not recommended for production use. Supported on Android and iOS. - */ - upload( - fileURL: string, - server: string, - successCallback: (result: FileUploadResult) => void, - errorCallback: (error: FileTransferError) => void, - options?: FileUploadOptions, - trustAllHosts?: boolean): void; - /** - * downloads a file from server. - * @param source URL of the server to download the file, as encoded by encodeURI(). - * @param target Filesystem url representing the file on the device. For backwards compatibility, - * this can also be the full path of the file on the device. - * @param successCallback A callback that is passed a FileEntry object. (Function) - * @param errorCallback A callback that executes if an error occurs when retrieving the fileEntry. - * Invoked with a FileTransferError object. - * @param options Optional parameters. - * @param trustAllHosts Optional parameter, defaults to false. If set to true, it accepts all security certificates. - * This is useful since Android rejects self-signed security certificates. - * Not recommended for production use. Supported on Android and iOS. - */ - download( - source: string, - target: string, - successCallback: (fileEntry: FileEntry) => void, - errorCallback: (error: FileTransferError) => void, - trustAllHosts?: boolean, - options?: FileDownloadOptions): void; - /** - * Aborts an in-progress transfer. The onerror callback is passed a FileTransferError object - * which has an error code of FileTransferError.ABORT_ERR. - */ - abort(): void; -} - -declare var FileTransfer: { - new (): FileTransfer; -}; - -/** A FileUploadResult object is passed to the success callback of the FileTransfer object's upload() method. */ -interface FileUploadResult { - /** The number of bytes sent to the server as part of the upload. */ - bytesSent: number; - /** The HTTP response code returned by the server. */ - responseCode: number; - /** The HTTP response returned by the server. */ - response: string; - /** The HTTP response headers by the server. Currently supported on iOS only.*/ - headers: any; -} - -/** Optional parameters for upload method. */ -interface FileUploadOptions { - /** The name of the form element. Defaults to file. */ - fileKey?: string; - /** The file name to use when saving the file on the server. Defaults to image.jpg. */ - fileName?: string; - /** The HTTP method to use - either `PUT` or `POST`. Defaults to `POST`. */ - httpMethod?: string; - /** The mime type of the data to upload. Defaults to image/jpeg. */ - mimeType?: string; - /** A set of optional key/value pairs to pass in the HTTP request. */ - params?: Object; - /** Whether to upload the data in chunked streaming mode. Defaults to true. */ - chunkedMode?: boolean; - /** A map of header name/header values. Use an array to specify more than one value. */ - headers?: Object; -} - -/** Optional parameters for download method. */ -interface FileDownloadOptions { - /** A map of header name/header values. */ - headers?: {}; -} - -/** A FileTransferError object is passed to an error callback when an error occurs. */ -interface FileTransferError { - /** - * One of the predefined error codes listed below. - * FileTransferError.FILE_NOT_FOUND_ERR - * FileTransferError.INVALID_URL_ERR - * FileTransferError.CONNECTION_ERR - * FileTransferError.ABORT_ERR - * FileTransferError.NOT_MODIFIED_ERR - */ - code: number; - /** URL to the source. */ - source: string; - /** URL to the target. */ - target: string; - /** HTTP status code. This attribute is only available when a response code is received from the HTTP connection. */ - http_status: number; - /* Response body. This attribute is only available when a response is received from the HTTP connection. */ - body: string; - /* Exception that is thrown by native code */ - exception: any; -} - -declare var FileTransferError: { - /** Constructor for FileTransferError object */ - new (code?: number, source?: string, target?: string, status?: number, body?: any, exception?: any): FileTransferError; - FILE_NOT_FOUND_ERR: number; - INVALID_URL_ERR: number; - CONNECTION_ERR: number; - ABORT_ERR: number; - NOT_MODIFIED_ERR: number; -} \ No newline at end of file diff --git a/plugins/cordova-plugin-file/CONTRIBUTING.md b/plugins/cordova-plugin-file/CONTRIBUTING.md deleted file mode 100644 index 4c8e6a5..0000000 --- a/plugins/cordova-plugin-file/CONTRIBUTING.md +++ /dev/null @@ -1,37 +0,0 @@ - - -# 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 deleted file mode 100644 index 7a4a3ea..0000000 --- a/plugins/cordova-plugin-file/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - 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 deleted file mode 100644 index 8ec56a5..0000000 --- a/plugins/cordova-plugin-file/NOTICE +++ /dev/null @@ -1,5 +0,0 @@ -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 deleted file mode 100644 index 1e21ed4..0000000 --- a/plugins/cordova-plugin-file/README.md +++ /dev/null @@ -1,835 +0,0 @@ ---- -title: File -description: Read/write files on the device. ---- - - -|AppVeyor|Travis CI| -|:-:|:-:| -|[![Build status](https://ci.appveyor.com/api/projects/status/github/apache/cordova-plugin-file?branch=master)](https://ci.appveyor.com/project/ApacheSoftwareFoundation/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 - -- Android -- iOS -- OS X -- 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` | externalCacheDirectory | 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`. - -### 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. - -## 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.resolveLocalFileSystemURL, 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 deleted file mode 100644 index 40ff79e..0000000 --- a/plugins/cordova-plugin-file/RELEASENOTES.md +++ /dev/null @@ -1,3 +0,0 @@ -### 6.0.1 (Dec 27, 2017) -* [CB-13704](https://issues.apache.org/jira/browse/CB-13704) Fix to allow 6.0.0 version install - diff --git a/plugins/cordova-plugin-file/doc/de/README.md b/plugins/cordova-plugin-file/doc/de/README.md deleted file mode 100644 index 242a2f7..0000000 --- a/plugins/cordova-plugin-file/doc/de/README.md +++ /dev/null @@ -1,335 +0,0 @@ - - -# 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 deleted file mode 100644 index 2a51695..0000000 --- a/plugins/cordova-plugin-file/doc/de/index.md +++ /dev/null @@ -1,338 +0,0 @@ - - -# 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 deleted file mode 100644 index 8887d7a..0000000 --- a/plugins/cordova-plugin-file/doc/de/plugins.md +++ /dev/null @@ -1,101 +0,0 @@ - - -# 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 deleted file mode 100644 index 2a653bf..0000000 --- a/plugins/cordova-plugin-file/doc/es/README.md +++ /dev/null @@ -1,335 +0,0 @@ - - -# 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 deleted file mode 100644 index a9c0264..0000000 --- a/plugins/cordova-plugin-file/doc/es/index.md +++ /dev/null @@ -1,336 +0,0 @@ - - -# 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 deleted file mode 100644 index dace368..0000000 --- a/plugins/cordova-plugin-file/doc/es/plugins.md +++ /dev/null @@ -1,101 +0,0 @@ - - -# 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 deleted file mode 100644 index 6296a84..0000000 --- a/plugins/cordova-plugin-file/doc/fr/README.md +++ /dev/null @@ -1,328 +0,0 @@ - - -# 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 deleted file mode 100644 index 7235522..0000000 --- a/plugins/cordova-plugin-file/doc/fr/index.md +++ /dev/null @@ -1,331 +0,0 @@ - - -# 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 deleted file mode 100644 index b04e17f..0000000 --- a/plugins/cordova-plugin-file/doc/fr/plugins.md +++ /dev/null @@ -1,101 +0,0 @@ - - -# 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 deleted file mode 100644 index f8e302f..0000000 --- a/plugins/cordova-plugin-file/doc/it/README.md +++ /dev/null @@ -1,335 +0,0 @@ - - -# 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 deleted file mode 100644 index f3cd731..0000000 --- a/plugins/cordova-plugin-file/doc/it/index.md +++ /dev/null @@ -1,338 +0,0 @@ - - -# 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 deleted file mode 100644 index d3f1465..0000000 --- a/plugins/cordova-plugin-file/doc/it/plugins.md +++ /dev/null @@ -1,101 +0,0 @@ - - -# 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 deleted file mode 100644 index 96e8ff0..0000000 --- a/plugins/cordova-plugin-file/doc/ja/README.md +++ /dev/null @@ -1,335 +0,0 @@ - - -# 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 deleted file mode 100644 index 57fb7d2..0000000 --- a/plugins/cordova-plugin-file/doc/ja/index.md +++ /dev/null @@ -1,338 +0,0 @@ - - -# 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 deleted file mode 100644 index c54aa78..0000000 --- a/plugins/cordova-plugin-file/doc/ja/plugins.md +++ /dev/null @@ -1,101 +0,0 @@ - - -# プラグイン開発者ã®ãŸã‚ã®ãƒ¡ãƒ¢ - -ã“れらã®ãƒŽãƒ¼ãƒˆã¯ä¸»ã« 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 deleted file mode 100644 index a3f3e94..0000000 --- a/plugins/cordova-plugin-file/doc/ko/README.md +++ /dev/null @@ -1,335 +0,0 @@ - - -# 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 deleted file mode 100644 index 08340d8..0000000 --- a/plugins/cordova-plugin-file/doc/ko/index.md +++ /dev/null @@ -1,338 +0,0 @@ - - -# 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 deleted file mode 100644 index 31b274d..0000000 --- a/plugins/cordova-plugin-file/doc/ko/plugins.md +++ /dev/null @@ -1,101 +0,0 @@ - - -# í”ŒëŸ¬ê·¸ì¸ ê°œë°œìžë¥¼ 위한 노트 - -ì´ ë…¸íŠ¸ëŠ” 주로 íŒŒì¼ í”ŒëŸ¬ê·¸ì¸ì„ 사용 하 ì—¬ íŒŒì¼ ì‹œìŠ¤í…œ í”ŒëŸ¬ê·¸ì¸ ì¸í„°íŽ˜ì´ìŠ¤ë¥¼ 작성 하 ê³  ì‹¶ì€ ì•ˆ ë“œ ë¡œì´ë“œì™€ 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 deleted file mode 100644 index 166c3ce..0000000 --- a/plugins/cordova-plugin-file/doc/pl/README.md +++ /dev/null @@ -1,335 +0,0 @@ - - -# 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 deleted file mode 100644 index 1ccb330..0000000 --- a/plugins/cordova-plugin-file/doc/pl/index.md +++ /dev/null @@ -1,338 +0,0 @@ - - -# 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 deleted file mode 100644 index 6e8fe86..0000000 --- a/plugins/cordova-plugin-file/doc/pl/plugins.md +++ /dev/null @@ -1,101 +0,0 @@ - - -# 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 deleted file mode 100644 index a3329d6..0000000 --- a/plugins/cordova-plugin-file/doc/plugins.md +++ /dev/null @@ -1,120 +0,0 @@ - - -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 deleted file mode 100644 index 3c9fca9..0000000 --- a/plugins/cordova-plugin-file/doc/ru/index.md +++ /dev/null @@ -1,275 +0,0 @@ - - -# 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 deleted file mode 100644 index 2445d09..0000000 --- a/plugins/cordova-plugin-file/doc/ru/plugins.md +++ /dev/null @@ -1,124 +0,0 @@ - - -# ÐŸÑ€Ð¸Ð¼ÐµÑ‡Ð°Ð½Ð¸Ñ Ð´Ð»Ñ Ñ€Ð°Ð·Ñ€Ð°Ð±Ð¾Ñ‚Ñ‡Ð¸ÐºÐ¾Ð² плагинов - -Эти Ð¿Ñ€Ð¸Ð¼ÐµÑ‡Ð°Ð½Ð¸Ñ Ð¿Ñ€ÐµÐ´Ð½Ð°Ð·Ð½Ð°Ñ‡ÐµÐ½Ñ‹ прежде вÑего Ð´Ð»Ñ 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 deleted file mode 100644 index c600587..0000000 --- a/plugins/cordova-plugin-file/doc/zh/README.md +++ /dev/null @@ -1,335 +0,0 @@ - - -# 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 deleted file mode 100644 index 6eec44d..0000000 --- a/plugins/cordova-plugin-file/doc/zh/index.md +++ /dev/null @@ -1,343 +0,0 @@ - - -# 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 deleted file mode 100644 index c9a2d61..0000000 --- a/plugins/cordova-plugin-file/doc/zh/plugins.md +++ /dev/null @@ -1,101 +0,0 @@ - - -# 外掛程å¼é–‹ç™¼äººå“¡æ³¨æ„事項 - -這些筆記主è¦ç”¨æ–¼ 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 deleted file mode 100644 index 51c689f..0000000 --- a/plugins/cordova-plugin-file/package.json +++ /dev/null @@ -1,87 +0,0 @@ -{ - "_from": "cordova-plugin-file@^6.0.1", - "_id": "cordova-plugin-file@6.0.1", - "_inBundle": false, - "_integrity": "sha1-SWBrjBWlaI1HKPkuSnMloGHeB/U=", - "_location": "/cordova-plugin-file", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "cordova-plugin-file@^6.0.1", - "name": "cordova-plugin-file", - "escapedName": "cordova-plugin-file", - "rawSpec": "^6.0.1", - "saveSpec": null, - "fetchSpec": "^6.0.1" - }, - "_requiredBy": [ - "#USER", - "/" - ], - "_resolved": "https://registry.npmjs.org/cordova-plugin-file/-/cordova-plugin-file-6.0.1.tgz", - "_shasum": "49606b8c15a5688d4728f92e4a7325a061de07f5", - "_spec": "cordova-plugin-file@^6.0.1", - "_where": "/home/thrrgilag/workspace/cordova/Goober", - "author": { - "name": "Apache Software Foundation" - }, - "bugs": { - "url": "https://issues.apache.org/jira/browse/CB" - }, - "bundleDependencies": false, - "cordova": { - "id": "cordova-plugin-file", - "platforms": [ - "android", - "browser", - "ios", - "osx", - "windows" - ] - }, - "deprecated": false, - "description": "Cordova File Plugin", - "devDependencies": { - "eslint": "^3.19.0", - "eslint-config-semistandard": "^11.0.0", - "eslint-config-standard": "^10.2.1", - "eslint-plugin-import": "^2.3.0", - "eslint-plugin-node": "^5.0.0", - "eslint-plugin-promise": "^3.5.0", - "eslint-plugin-standard": "^3.0.1" - }, - "engines": { - "cordovaDependencies": { - "5.0.0": { - "cordova-android": ">=6.3.0" - }, - "7.0.0": { - "cordova": ">100" - } - } - }, - "homepage": "https://github.com/apache/cordova-plugin-file#readme", - "keywords": [ - "cordova", - "file", - "ecosystem:cordova", - "cordova-android", - "cordova-browser", - "cordova-ios", - "cordova-osx", - "cordova-windows" - ], - "license": "Apache-2.0", - "name": "cordova-plugin-file", - "repository": { - "type": "git", - "url": "git+https://github.com/apache/cordova-plugin-file.git" - }, - "scripts": { - "eslint": "node node_modules/eslint/bin/eslint www && node node_modules/eslint/bin/eslint src && node node_modules/eslint/bin/eslint tests", - "test": "npm run eslint" - }, - "types": "./types/index.d.ts", - "version": "6.0.1" -} diff --git a/plugins/cordova-plugin-file/plugin.xml b/plugins/cordova-plugin-file/plugin.xml deleted file mode 100644 index ecd15e9..0000000 --- a/plugins/cordova-plugin-file/plugin.xml +++ /dev/null @@ -1,260 +0,0 @@ - - - - - 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 deleted file mode 100644 index b035c40..0000000 --- a/plugins/cordova-plugin-file/src/android/AssetFilesystem.java +++ /dev/null @@ -1,294 +0,0 @@ -/* - 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 deleted file mode 100644 index 6b983c0..0000000 --- a/plugins/cordova-plugin-file/src/android/ContentFilesystem.java +++ /dev/null @@ -1,223 +0,0 @@ -/* - 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 deleted file mode 100644 index 07af5ea..0000000 --- a/plugins/cordova-plugin-file/src/android/DirectoryManager.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - 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 deleted file mode 100644 index e9e1653..0000000 --- a/plugins/cordova-plugin-file/src/android/EncodingException.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - 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 deleted file mode 100644 index 5c4d83d..0000000 --- a/plugins/cordova-plugin-file/src/android/FileExistsException.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - 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 deleted file mode 100644 index 1d6e61f..0000000 --- a/plugins/cordova-plugin-file/src/android/FileUtils.java +++ /dev/null @@ -1,1225 +0,0 @@ -/* - 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("applicationDirectory")); - 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 deleted file mode 100644 index c69d3bd..0000000 --- a/plugins/cordova-plugin-file/src/android/Filesystem.java +++ /dev/null @@ -1,331 +0,0 @@ -/* - 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 deleted file mode 100644 index 8f6bec5..0000000 --- a/plugins/cordova-plugin-file/src/android/InvalidModificationException.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - 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 deleted file mode 100644 index 051f994..0000000 --- a/plugins/cordova-plugin-file/src/android/LocalFilesystem.java +++ /dev/null @@ -1,513 +0,0 @@ -/* - 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 deleted file mode 100644 index b96b6ee..0000000 --- a/plugins/cordova-plugin-file/src/android/LocalFilesystemURL.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - 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 deleted file mode 100644 index 627eafb..0000000 --- a/plugins/cordova-plugin-file/src/android/NoModificationAllowedException.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - 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 deleted file mode 100644 index 23d6d73..0000000 --- a/plugins/cordova-plugin-file/src/android/PendingRequests.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - 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 deleted file mode 100644 index 1315f9a..0000000 --- a/plugins/cordova-plugin-file/src/android/TypeMismatchException.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - 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 deleted file mode 100644 index a0a7844..0000000 --- a/plugins/cordova-plugin-file/src/android/build-extras.gradle +++ /dev/null @@ -1,47 +0,0 @@ -/* - 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/browser/FileProxy.js b/plugins/cordova-plugin-file/src/browser/FileProxy.js deleted file mode 100644 index 66ad46b..0000000 --- a/plugins/cordova-plugin-file/src/browser/FileProxy.js +++ /dev/null @@ -1,984 +0,0 @@ -/* - * - * 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 + '/', // eslint-disable-line no-undef - // 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'); - var FileSystem = require('./FileSystem'); - var FileEntry = require('./FileEntry'); - var FileError = require('./FileError'); - var DirectoryEntry = require('./DirectoryEntry'); - var 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 + '/', // eslint-disable-line no-undef - // 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]; // eslint-disable-line no-unused-vars - - 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, '_'); // eslint-disable-line no-undef - - 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]; - var data = args[1]; - var position = args[2]; - var isBinary = args[3]; // eslint-disable-line no-unused-vars - - if (!data) { - if (errorCallback) { - errorCallback(FileError.INVALID_MODIFICATION_ERR); - } - return; - } - - if (typeof data === 'string' || data instanceof String) { - data = new Blob([data]); // eslint-disable-line no-undef - } - - exports.getFile(function (fileEntry) { - var blob_ = fileEntry.file_.blob_; - - if (!blob_) { - blob_ = new Blob([data], {type: data.type}); // eslint-disable-line no-undef - } 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], // eslint-disable-line no-undef - {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]; - var enc = args[1]; - var startPos = args[2]; - var endPos = args[3]; - - readAs('text', fileName, enc, startPos, endPos, successCallback, errorCallback); - }; - - exports.readAsDataURL = function (successCallback, errorCallback, args) { - var fileName = args[0]; - var startPos = args[1]; - var endPos = args[2]; - - readAs('dataURL', fileName, null, startPos, endPos, successCallback, errorCallback); - }; - - exports.readAsBinaryString = function (successCallback, errorCallback, args) { - var fileName = args[0]; - var startPos = args[1]; - var endPos = args[2]; - - readAs('binaryString', fileName, null, startPos, endPos, successCallback, errorCallback); - }; - - exports.readAsArrayBuffer = function (successCallback, errorCallback, args) { - var fileName = args[0]; - var startPos = args[1]; - var 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]; // eslint-disable-line - var name = args[2]; // eslint-disable-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)) { // eslint-disable-line no-useless-escape - 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(); // eslint-disable-line no-undef - xhr.open('GET', path, true); - xhr.onreadystatechange = function () { - if (xhr.status === 200 && xhr.readyState === 4) { - exports.requestFileSystem(function (fs) { - fs.name = location.hostname; // eslint-disable-line no-undef - - // 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; // eslint-disable-line no-undef - successCallback(entry); - } - }; - fileWriter.onerror = function () { - if (errorCallback) { - errorCallback(FileError.NOT_READABLE_ERR); - } - }; - fileWriter.write(new Blob([xhr.response])); // eslint-disable-line no-undef - }, errorCallback); // eslint-disable-line no-undef - } - }; - - 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(); // eslint-disable-line no-undef - - 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(); // eslint-disable-line no-undef - var 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/ios/CDVAssetLibraryFilesystem.h b/plugins/cordova-plugin-file/src/ios/CDVAssetLibraryFilesystem.h deleted file mode 100644 index e09e225..0000000 --- a/plugins/cordova-plugin-file/src/ios/CDVAssetLibraryFilesystem.h +++ /dev/null @@ -1,30 +0,0 @@ -/* - 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 deleted file mode 100644 index 8486b7b..0000000 --- a/plugins/cordova-plugin-file/src/ios/CDVAssetLibraryFilesystem.m +++ /dev/null @@ -1,253 +0,0 @@ -/* - 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 deleted file mode 100644 index 987c66b..0000000 --- a/plugins/cordova-plugin-file/src/ios/CDVFile.h +++ /dev/null @@ -1,157 +0,0 @@ -/* - 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 deleted file mode 100644 index 59e7d64..0000000 --- a/plugins/cordova-plugin-file/src/ios/CDVFile.m +++ /dev/null @@ -1,1119 +0,0 @@ -/* - 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 deleted file mode 100644 index a0186c8..0000000 --- a/plugins/cordova-plugin-file/src/ios/CDVLocalFilesystem.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - 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 deleted file mode 100644 index c340ce0..0000000 --- a/plugins/cordova-plugin-file/src/ios/CDVLocalFilesystem.m +++ /dev/null @@ -1,750 +0,0 @@ -/* - 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:[self mimeTypeForFileAtPath: path] forKey:@"type"]; - [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); -} - -// fix errors that base on Alexsander Akers from http://stackoverflow.com/a/5998683/2613194 -- (NSString*) mimeTypeForFileAtPath: (NSString *) path { - if (![[NSFileManager defaultManager] fileExistsAtPath:path]) { - return nil; - } - - CFStringRef UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)[path pathExtension], NULL); - CFStringRef mimeType = UTTypeCopyPreferredTagWithClass (UTI, kUTTagClassMIMEType); - CFRelease(UTI); - - if (!mimeType) { - return @"application/octet-stream"; - } - return (__bridge NSString *)mimeType; -} - -@end diff --git a/plugins/cordova-plugin-file/src/osx/CDVFile.h b/plugins/cordova-plugin-file/src/osx/CDVFile.h deleted file mode 100644 index 13a9360..0000000 --- a/plugins/cordova-plugin-file/src/osx/CDVFile.h +++ /dev/null @@ -1,189 +0,0 @@ -/* - 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 deleted file mode 100644 index 75a6001..0000000 --- a/plugins/cordova-plugin-file/src/osx/CDVFile.m +++ /dev/null @@ -1,1056 +0,0 @@ -/* - 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 deleted file mode 100644 index a0186c8..0000000 --- a/plugins/cordova-plugin-file/src/osx/CDVLocalFilesystem.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - 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 deleted file mode 100644 index 016e399..0000000 --- a/plugins/cordova-plugin-file/src/osx/CDVLocalFilesystem.m +++ /dev/null @@ -1,733 +0,0 @@ -/* - 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/windows/FileProxy.js b/plugins/cordova-plugin-file/src/windows/FileProxy.js deleted file mode 100644 index d829d77..0000000 --- a/plugins/cordova-plugin-file/src/windows/FileProxy.js +++ /dev/null @@ -1,1190 +0,0 @@ -/* - * - * 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'); -var FileError = require('./FileError'); -var Flags = require('./Flags'); -var FileSystem = require('./FileSystem'); -var LocalFileSystem = require('./LocalFileSystem'); -var 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); // eslint-disable-line no-undef -} - -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 || {}; - 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) { // eslint-disable-line handle-callback-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 || 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 || 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) { // eslint-disable-line handle-callback-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) { // eslint-disable-line handle-callback-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]; - var enc = args[1]; - var startPos = args[2]; - var 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; - var 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]; - var startPos = args[1]; - var 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); - var 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 }); // eslint-disable-line no-undef - var xhr = new XMLHttpRequest(); // eslint-disable-line no-undef - 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; - var 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); - var resBuffer = new ArrayBuffer(endPos - startPos); - var 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) { // eslint-disable-line handle-callback-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]; - var data = args[1]; - var position = args[2]; - var 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) { // eslint-disable-line no-undef - 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/tests/package.json b/plugins/cordova-plugin-file/tests/package.json deleted file mode 100644 index c5a1dd7..0000000 --- a/plugins/cordova-plugin-file/tests/package.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "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 deleted file mode 100644 index 9074699..0000000 --- a/plugins/cordova-plugin-file/tests/plugin.xml +++ /dev/null @@ -1,44 +0,0 @@ - - - - - - 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 deleted file mode 100644 index 9eba0d0..0000000 --- a/plugins/cordova-plugin-file/tests/src/android/TestContentProvider.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - 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 deleted file mode 100644 index a9ae20a..0000000 --- a/plugins/cordova-plugin-file/tests/tests.js +++ /dev/null @@ -1,4163 +0,0 @@ -/* - * - * 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. - * - */ - -/* eslint-env jasmine */ -/* global WebKitBlobBuilder */ - -exports.defineAutoTests = function () { - /* eslint-disable no-undef */ - 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'); - /* eslint-enable no-undef */ - 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' - }; - var root; - var temp_root; - var 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(''); - var b = currentPath.split('/').join('').split('\\').join(''); - var pass = a === b; - return { - pass: pass, - message: 'Expected paths to match : ' + path + ' should be ' + currentPath - }; - } - }; - }, - toFailWithMessage: function () { - return { - compare: function (error, message) { // eslint-disable-line handle-callback-err - 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) { // eslint-disable-line no-undef - root = fileSystem.root; - // set in file.tests.js - persistent_root = root; - window.requestFileSystem(LocalFileSystem.TEMPORARY, 0, function (fileSystem) { // eslint-disable-line no-undef - 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 () { - /* eslint-disable no-undef */ - 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); - /* eslint-enable no-undef */ - }); - 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')); // eslint-disable-line no-undef - }); - 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')); // eslint-disable-line no-undef - }); - 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); // eslint-disable-line no-undef - 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); // eslint-disable-line no-undef - }); - 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) or ??? (code: 13) 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); // eslint-disable-line no-undef - } - 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) { - if (isBrowser) { - pending('browsers doesn\'t return nativeURL'); - } - var fileName = 'de.create.file'; - var 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'; - var 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'); // eslint-disable-line no-undef - var fail = function (error) { - expect(error).toBeDefined(); - if (isChrome) { - expect(error).toBeFileError(FileError.SYNTAX_ERR); // eslint-disable-line no-undef - } else { - expect(error).toBeFileError(FileError.NOT_FOUND_ERR); // eslint-disable-line no-undef - } - 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'; - var fail = function (error) { - expect(error).toBeDefined(); - if (isChrome) { - // O.o chrome returns error code 0 - } else { - expect(error).toBeFileError(FileError.ENCODING_ERR); // eslint-disable-line no-undef - } - 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(); // eslint-disable-line no-undef - 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); // eslint-disable-line no-undef - 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'; - var fail = function (error) { - expect(error).toBeDefined(); - if (isChrome) { - expect(error).toBeFileError(FileError.SYNTAX_ERR); // eslint-disable-line no-undef - } else { - expect(error).toBeFileError(FileError.NOT_FOUND_ERR); // eslint-disable-line no-undef - } - 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'; - var filePath = joinURL(root.fullPath, fileName); - var 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'; - var filePath = joinURL(root.fullPath, fileName); - var 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'; - var 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'; - var existingFile; - - function fail (error) { - expect(error).toBeDefined(); - if (isChrome) { - /* INVALID_MODIFICATION_ERR (code: 9) or ??? (code: 13) 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); // eslint-disable-line no-undef - } - // 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'; - var filePath = joinURL(root.fullPath, fileName); - var 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); - }; - var 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'; - var fail = function (error) { - expect(error).toBeDefined(); - expect(error).toBeFileError(FileError.ENCODING_ERR); // eslint-disable-line no-undef - 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'; - var fail = function (error) { - expect(error).toBeDefined(); - if (isChrome) { - expect(error).toBeFileError(FileError.SYNTAX_ERR); // eslint-disable-line no-undef - } else { - expect(error).toBeFileError(FileError.NOT_FOUND_ERR); // eslint-disable-line no-undef - } - 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'; - var 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'; - var dirPath = joinURL(root.fullPath, dirName); - var 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'; - var dirPath = joinURL(root.fullPath, dirName); - var 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'; - var dirPath = joinURL(root.fullPath, dirName); - var 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'; - var existingDir; - var fail = function (error) { - expect(error).toBeDefined(); - if (isChrome) { - /* INVALID_MODIFICATION_ERR (code: 9) or ??? (code: 13) 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); // eslint-disable-line no-undef - } - // 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'; - var dirPath = joinURL(root.fullPath, dirName); - var 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'; - var fail = function (error) { - expect(error).toBeDefined(); - expect(error).toBeFileError(FileError.ENCODING_ERR); // eslint-disable-line no-undef - 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'; - var existingFile; - var fail = function (error) { - expect(error).toBeDefined(); - if (isChrome) { - // chrome returns an unknown error with code 17 - } else { - expect(error).toBeFileError(FileError.TYPE_MISMATCH_ERR); // eslint-disable-line no-undef - } - // 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'; - var existingDir; - var fail = function (error) { - expect(error).toBeDefined(); - if (isChrome) { - // chrome returns an unknown error with code 17 - } else { - expect(error).toBeFileError(FileError.TYPE_MISMATCH_ERR); // eslint-disable-line no-undef - } - // 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'; - var subDirName = 'dir'; - var dirExists = function (error) { - expect(error).toBeDefined(); - if (isChrome) { - expect(error).toBeFileError(FileError.SYNTAX_ERR); // eslint-disable-line no-undef - } else { - expect(error).toBeFileError(FileError.NOT_FOUND_ERR); // eslint-disable-line no-undef - } - 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) or ??? (code: 13) 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); // eslint-disable-line no-undef - } - 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; - var 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'; - var 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); // eslint-disable-line no-undef - } - - // 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; - var 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(); - if (isChrome) { - expect(error).toBeFileError(FileError.SYNTAX_ERR); // eslint-disable-line no-undef - } else { - expect(error).toBeFileError(FileError.NOT_FOUND_ERR); // eslint-disable-line no-undef - } - 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(); - if (isChrome) { - expect(error).toBeFileError(FileError.SYNTAX_ERR); // eslint-disable-line no-undef - } else { - expect(error).toBeFileError(FileError.NOT_FOUND_ERR); // eslint-disable-line no-undef - } - 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(); // eslint-disable-line no-undef - expect(typeof File).toBe('function'); - }); - it('file.spec.40 should be define File attributes', function () { - var file = new File(); // eslint-disable-line no-undef - 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'; - var 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'; - var testFile; - var 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); // eslint-disable-line no-undef - } - - // 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'; - var newFile; - var 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); // eslint-disable-line no-undef - } - - // 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(); - if (isChrome) { - expect(error).toBeFileError(FileError.SYNTAX_ERR); // eslint-disable-line no-undef - } else { - expect(error).toBeFileError(FileError.NOT_FOUND_ERR); // eslint-disable-line no-undef - } - 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'; - var fullPath = joinURL(root.fullPath, fileName); - var 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'; - var 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'; - var 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; - var 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'; - var rootPath = root.fullPath; - var 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'; - var dirName_2 = 'num 2'; - var 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(); - if (isChrome) { - expect(error).toBeFileError(FileError.SYNTAX_ERR); // eslint-disable-line no-undef - } else { - expect(error).toBeFileError(FileError.NOT_FOUND_ERR); // eslint-disable-line no-undef - } - // 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) { - if (isBrowser) { - pending('Browsers can\'t do that'); - } - 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); // eslint-disable-line no-undef - // 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(); - if (isChrome) { - expect(error).toBeFileError(FileError.SYNTAX_ERR); // eslint-disable-line no-undef - } else { - expect(error).toBeFileError(FileError.NOT_FOUND_ERR); // eslint-disable-line no-undef - } - // 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'; - var fileName = 're ove.txt'; - var 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(); - if (isChrome) { - // chrome is returning unknown error with code 13 - } else { - expect(error).toBeFileError(FileError.INVALID_MODIFICATION_ERR); // eslint-disable-line no-undef - } - 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) or ??? (code: 13) 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); // eslint-disable-line no-undef - } - done(); - }); - }); - it('file.spec.57 copyTo: file', function (done) { - var file1 = 'entry copy.file1'; - var file2 = 'entry copy.file2'; - var 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(); - if (isChrome) { - // chrome returns unknown error with code 13 - } else { - expect(error).toBeFileError(FileError.INVALID_MODIFICATION_ERR); // eslint-disable-line no-undef - } - // 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'; - var srcDir = 'entry.copy.srcDir'; - var dstDir = 'entry.copy.dstDir'; - var dstPath = joinURL(root.fullPath, dstDir); - var 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'; - var srcDir = 'entry.copy srcDirSame'; - var dstDir = 'entry.copy srcDirSame-backup'; - var dstPath = joinURL(root.fullPath, dstDir); - var 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'; - var srcDir = 'entry.copy.dos.srcDir'; - var srcPath = joinURL(root.fullPath, srcDir); - var 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(); - if (isChrome) { - // chrome returns unknown error with code 13 - } else { - expect(error).toBeFileError(FileError.INVALID_MODIFICATION_ERR); // eslint-disable-line no-undef - } - 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'; - var dstDir = 'entry.copy.dis.dstDir'; - var 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(); - if (isChrome) { - // chrome returns unknown error with code 13 - } else { - expect(error).toBeFileError(FileError.INVALID_MODIFICATION_ERR); // eslint-disable-line no-undef - } - 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'; - var 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(); - if (isChrome) { - expect(error).toBeFileError(FileError.SYNTAX_ERR); // eslint-disable-line no-undef - } else { - expect(error).toBeFileError(FileError.NOT_FOUND_ERR); // eslint-disable-line no-undef - } - 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'; - var 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); // eslint-disable-line no-undef - // 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'; - var file2 = 'entry.move.fsp.file2'; - var 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(); - if (isChrome) { - expect(error).toBeFileError(FileError.SYNTAX_ERR); // eslint-disable-line no-undef - } else { - expect(error).toBeFileError(FileError.NOT_FOUND_ERR); // eslint-disable-line no-undef - } - // 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'; - var dir = 'entry.move.fnp.dir'; - var 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(); - if (isChrome) { - expect(error).toBeFileError(FileError.SYNTAX_ERR); // eslint-disable-line no-undef - } else { - expect(error).toBeFileError(FileError.NOT_FOUND_ERR); // eslint-disable-line no-undef - } - // 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'; - var srcDir = 'entry.move.dsp.srcDir'; - var dstDir = 'entry.move.dsp.dstDir'; - var dstPath = joinURL(root.fullPath, dstDir); - var 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(); - if (isChrome) { - expect(error).toBeFileError(FileError.SYNTAX_ERR); // eslint-disable-line no-undef - } else { - expect(error).toBeFileError(FileError.NOT_FOUND_ERR); // eslint-disable-line no-undef - } - // 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'; - var srcDir = 'entry.move.dsp.srcDir'; - var dstDir = 'entry.move.dsp.srcDir-backup'; - var dstPath = joinURL(root.fullPath, dstDir); - var 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(); - if (isChrome) { - expect(error).toBeFileError(FileError.SYNTAX_ERR); // eslint-disable-line no-undef - } else { - expect(error).toBeFileError(FileError.NOT_FOUND_ERR); // eslint-disable-line no-undef - } - // 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'; - var srcDir = 'entry.move.dnp.srcDir'; - var dstDir = 'entry.move.dnp.dstDir'; - var dstPath = joinURL(root.fullPath, dstDir); - var 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(); - if (isChrome) { - expect(error).toBeFileError(FileError.SYNTAX_ERR); // eslint-disable-line no-undef - } else { - expect(error).toBeFileError(FileError.NOT_FOUND_ERR); // eslint-disable-line no-undef - } - // 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); - if (!isChrome) { - 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'; - var srcDir = 'entry.move.dos.srcDir'; - var srcPath = joinURL(root.fullPath, srcDir); - var 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(); - if (isChrome) { - // chrome returns unknown error with code 13 - } else { - expect(error).toBeFileError(FileError.INVALID_MODIFICATION_ERR); // eslint-disable-line no-undef - } - // 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'; - var dstDir = 'entry.move.dis.dstDir'; - var 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(); - if (isChrome) { - // chrome returns unknown error with code 13 - } else { - expect(error).toBeFileError(FileError.INVALID_MODIFICATION_ERR); // eslint-disable-line no-undef - } - // 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'; - var 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'; - var 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(); - if (isChrome) { - // chrome returns unknown error with code 13 - } else { - expect(error).toBeFileError(FileError.INVALID_MODIFICATION_ERR); // eslint-disable-line no-undef - } - // 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'; - var dstDir = 'entry.move.fod.dstDir'; - var subDir = 'subDir'; - var dirPath = joinURL(joinURL(root.fullPath, dstDir), subDir); - var 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(); - if (isChrome) { - // chrome returns unknown error with code 13 - } else { - expect(error).toBeFileError(FileError.INVALID_MODIFICATION_ERR); // eslint-disable-line no-undef - } - // 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'; - var srcDir = 'entry.move.dof.srcDir'; - var dirPath = joinURL(root.fullPath, srcDir); - var 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(); - if (isChrome) { - // chrome returns unknown error with code 13 - } else { - expect(error).toBeFileError(FileError.INVALID_MODIFICATION_ERR); // eslint-disable-line no-undef - } - // 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'; - var srcDir = 'entry.copy.dof.srcDir'; - var dirPath = joinURL(root.fullPath, srcDir); - var 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(); - if (isChrome) { - // chrome returns unknown error with code 13 - } else { - expect(error).toBeFileError(FileError.INVALID_MODIFICATION_ERR); // eslint-disable-line no-undef - } - // 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'; - var dstDir = 'entry.move.dod.dstDir'; - var subDir = 'subDir'; - var srcPath = joinURL(root.fullPath, srcDir); - var 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(); - if (isChrome) { - // chrome returns unknown error with code 13 - } else { - expect(error).toBeFileError(FileError.INVALID_MODIFICATION_ERR); // eslint-disable-line no-undef - } - // 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'; - var file2 = 'entry.move.frf.file2'; - var 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(); - if (isChrome) { - expect(error).toBeFileError(FileError.SYNTAX_ERR); // eslint-disable-line no-undef - } else { - expect(error).toBeFileError(FileError.NOT_FOUND_ERR); // eslint-disable-line no-undef - } - // 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'; - var srcDir = 'entry.move.drd.srcDir'; - var dstDir = 'entry.move.drd.dstDir'; - var dstPath = joinURL(root.fullPath, dstDir); - var 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(); - if (isChrome) { - expect(error).toBeFileError(FileError.SYNTAX_ERR); // eslint-disable-line no-undef - } else { - expect(error).toBeFileError(FileError.NOT_FOUND_ERR); // eslint-disable-line no-undef - } - // 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) { - if (isChrome) { - pending('chrome freak out about non-existend dir not being a DirectoryEntry'); - } - var file1 = 'entry.move.dnf.file1'; - var dstDir = 'entry.move.dnf.dstDir'; - var 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(); // eslint-disable-line no-undef - 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); // eslint-disable-line no-undef - } else { - expect(error).toBeFileError(FileError.NOT_FOUND_ERR); // eslint-disable-line no-undef - } - // 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'; - var 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); // eslint-disable-line no-undef - // 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(); // eslint-disable-line no-undef - 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'; // eslint-disable-line no-undef - var verifier = function (evt) { - expect(evt).toBeDefined(); - if (isChrome) { - expect(evt.target.error).toBeFileError(FileError.SYNTAX_ERR); // eslint-disable-line no-undef - } else { - expect(evt.target.error).toBeFileError(FileError.NOT_FOUND_ERR); // eslint-disable-line no-undef - } - done(); - }; - root.getFile(fileName, { - create: true - }, function (entry) { - entry.file(function (file) { - deleteEntry(fileName, function () { - // Create FileReader - var reader = new FileReader(); // eslint-disable-line no-undef - 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]); // eslint-disable-line no-undef - } 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(); // eslint-disable-line no-undef - reader.onloadend = verifier; - reader.readAsText(blob); - }); - function writeDummyFile (writeBinary, callback, done, fileContents) { - var fileName = 'dummy.txt'; - var fileEntry = null; - // use default string if file data is not provided - var fileData = fileContents !== undefined ? fileContents : - '\u20AC\xEB - There is an exception to every rule. Except this one.'; - var 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(); // eslint-disable-line no-undef - 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; // eslint-disable-line no-undef - - 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); - if (!isChrome) { - // chrome downloads it in one chunk -.- - 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; // eslint-disable-line no-undef - - 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 - var content = 'There is an exception to every rule.'; // for checkin file length - var exception = ' Except this one.'; - var 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(); // eslint-disable-line no-undef - 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 - var content = 'There is an exception to every rule.'; // for checkin file length - var exception = ' Except this one.'; - var 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(); // eslint-disable-line no-undef - 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 - var content = 'This is our sentence.'; // for checking file length - var exception = 'newer sentence.'; - var 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(); // eslint-disable-line no-undef - 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 (isBrowser) { - /* Browser (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 - var content = 'This is our sentence.'; // for checking file length - var exception = 'new.'; - var 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(); // eslint-disable-line no-undef - 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 - var content = '\n\nData\n\n'; // for testing file length - var 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 - var content = '{ "name": "Guy Incognito", "email": "here@there.com" }'; // for testing file length - var 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 - var content = 'There is an exception to every rule. Except this one.'; // for testing file length - var 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'; - var 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 - var data = new ArrayBuffer(32); - var dataView = new Int8Array(data); // for verifying file length - var 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 - var data = new ArrayBuffer(32); - var dataView = new Int8Array(data); - var blob; // for verifying file length - var length = 32; - for (var i = 0; i < dataView.length; i++) { - dataView[i] = i; - } - try { - // Mobile Safari: Use Blob constructor - blob = new Blob([data], { // eslint-disable-line no-undef - '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'; - var outputFileName = 'verify.txt'; - var dummyFileText = 'This text should be written to two files'; - var verifier = function (outputFileWriter) { - expect(outputFileWriter.length).toBe(dummyFileText.length); - expect(outputFileWriter.position).toBe(dummyFileText.length); - deleteFile(outputFileName, done); - }; - var writeFile = function (fileName, fileData, win) { - var theWriter; - var 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)); - }; - var 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'; - var outputFileName = 'verify2.txt'; - var dummyFileText = 'This text should be written to two files'; - var verifier = function (outputFileWriter) { - expect(outputFileWriter.length).toBe(10); - expect(outputFileWriter.position).toBe(10); - deleteFile(outputFileName, done); - }; - var writeFile = function (fileName, fileData, win) { - var theWriter; - var 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)); - }; - var 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'; - var outputFileName = 'verify.bin'; // file content - var data = new ArrayBuffer(32); - var dataView = new Int8Array(data); - var blob; // for verifying file length - var length = 32; - var verifier = function (outputFileWriter) { - expect(outputFileWriter.length).toBe(length); - expect(outputFileWriter.position).toBe(length); - // cleanup - deleteFile(outputFileName); - done(); - }; - var writeFile = function (fileName, fileData, win) { - var theWriter; - var 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)); - }; - var 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], { // eslint-disable-line no-undef - '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) { // eslint-disable-line no-undef - 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'; - var 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(); - if (isChrome) { - expect(error).toBeFileError(FileError.SYNTAX_ERR); // eslint-disable-line no-undef - } else { - expect(error).toBeFileError(FileError.NOT_FOUND_ERR); // eslint-disable-line no-undef - } - 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://'; // eslint-disable-line no-undef - if (isChrome) { - pathExpect = 'filesystem:http://'; - } - 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'; - var fileName = 'nativeEntries.file'; - var directory; - var 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(function () {}, 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) { // eslint-disable-line no-undef - 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) { - /* eslint-disable no-undef */ - 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) { - /* eslint-enable no-undef */ - 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'; - var file2 = 'entry.copy.file2a'; - var sourceEntry; - var fullPath = joinURL(root.fullPath, file2); - var 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); - }; - var 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'; - var file2 = 'entry.copy.file2b'; - var sourceEntry; - var fullPath = joinURL(temp_root.fullPath, file2); - var 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); - }; - var 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'; - var file2 = 'entry.copy.file2a'; - var sourceEntry; - var fullPath = joinURL(root.fullPath, file2); - var 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); - }; - var 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'; - var file2 = 'entry.copy.file2b'; - var sourceEntry; - var fullPath = joinURL(temp_root.fullPath, file2); - var 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); - }; - var 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']; - /* eslint-disable no-undef */ - 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) { - /* eslint-enable no-undef */ - 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(); // eslint-disable-line no-undef - 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'; - var nestedDirName = 'nestedDir131'; - var 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'; - var 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'; - var 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') { // eslint-disable-line no-undef - 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'; - var fullPath = joinURL(temp_root.fullPath, file2); - var 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); - }; - var transfer = function () { - resolveLocalFileSystemURL(src, function (entry) { // eslint-disable-line no-undef - 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) { // eslint-disable-line no-undef - 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/'); // eslint-disable-line no-undef - }, MEDIUM_TIMEOUT); - it('file.spec.142 assets should be enumerable', function (done) { - resolveLocalFileSystemURL('file:///android_asset/www/fixtures/asset-test', function (entry) { // eslint-disable-line no-undef - 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) { // eslint-disable-line no-undef - 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) { // eslint-disable-line no-undef - expect(entry.isFile).toBe(true); - entry.file(function (file) { - expect(file).toBeDefined(); - var reader = new FileReader(); // eslint-disable-line no-undef - 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'; - var fullPath = joinURL(temp_root.fullPath, file2); - var 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); - }; - var transfer = function () { - resolveLocalFileSystemURL('file:///android_asset/www/index.html', function (entry) { // eslint-disable-line no-undef - 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) { // eslint-disable-line no-undef - 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); - /* eslint-disable no-undef */ - 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) { - /* eslint-enable no-undef */ - 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); - /* eslint-disable no-undef */ - if (fsRoots.hasOwnProperty(cordova.platformId)) { - (fsRoots[cordova.platformId].split(',')).forEach(function (fs) { - if (cordova.platformId === 'ios' && fs === 'private') { - /* eslint-enable no-undef */ - 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/types/index.d.ts b/plugins/cordova-plugin-file/types/index.d.ts deleted file mode 100644 index c748e3d..0000000 --- a/plugins/cordova-plugin-file/types/index.d.ts +++ /dev/null @@ -1,378 +0,0 @@ -// 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