Bläddra i källkod

Hope this works

Emmanuel 4 år sedan
förälder
incheckning
cb6986fa70
100 ändrade filer med 27706 tillägg och 0 borttagningar
  1. 19
    0
      node_modules/cordova-plugin-advanced-http/.editorconfig
  2. 33
    0
      node_modules/cordova-plugin-advanced-http/.github/ISSUE_TEMPLATE/--bug-report.md
  3. 21
    0
      node_modules/cordova-plugin-advanced-http/.github/ISSUE_TEMPLATE/--feature-request.md
  4. 18
    0
      node_modules/cordova-plugin-advanced-http/.github/ISSUE_TEMPLATE/--support-question.md
  5. 65
    0
      node_modules/cordova-plugin-advanced-http/.github/workflows/ci.yml
  6. 61
    0
      node_modules/cordova-plugin-advanced-http/.travis.yml
  7. 3
    0
      node_modules/cordova-plugin-advanced-http/.vscode/settings.json
  8. 343
    0
      node_modules/cordova-plugin-advanced-http/CHANGELOG.md
  9. 82
    0
      node_modules/cordova-plugin-advanced-http/CONTRIBUTING.md
  10. 23
    0
      node_modules/cordova-plugin-advanced-http/LICENSE
  11. 443
    0
      node_modules/cordova-plugin-advanced-http/README.md
  12. 115
    0
      node_modules/cordova-plugin-advanced-http/package.json
  13. 95
    0
      node_modules/cordova-plugin-advanced-http/plugin.xml
  14. 113
    0
      node_modules/cordova-plugin-advanced-http/src/android/com/silkimen/cordovahttp/CordovaClientAuth.java
  15. 205
    0
      node_modules/cordova-plugin-advanced-http/src/android/com/silkimen/cordovahttp/CordovaHttpBase.java
  16. 42
    0
      node_modules/cordova-plugin-advanced-http/src/android/com/silkimen/cordovahttp/CordovaHttpDownload.java
  17. 25
    0
      node_modules/cordova-plugin-advanced-http/src/android/com/silkimen/cordovahttp/CordovaHttpOperation.java
  18. 169
    0
      node_modules/cordova-plugin-advanced-http/src/android/com/silkimen/cordovahttp/CordovaHttpPlugin.java
  19. 100
    0
      node_modules/cordova-plugin-advanced-http/src/android/com/silkimen/cordovahttp/CordovaHttpResponse.java
  20. 92
    0
      node_modules/cordova-plugin-advanced-http/src/android/com/silkimen/cordovahttp/CordovaHttpUpload.java
  21. 124
    0
      node_modules/cordova-plugin-advanced-http/src/android/com/silkimen/cordovahttp/CordovaServerTrust.java
  22. 55
    0
      node_modules/cordova-plugin-advanced-http/src/android/com/silkimen/http/HttpBodyDecoder.java
  23. 3095
    0
      node_modules/cordova-plugin-advanced-http/src/android/com/silkimen/http/HttpRequest.java
  24. 58
    0
      node_modules/cordova-plugin-advanced-http/src/android/com/silkimen/http/JsonUtils.java
  25. 57
    0
      node_modules/cordova-plugin-advanced-http/src/android/com/silkimen/http/KeyChainKeyManager.java
  26. 63
    0
      node_modules/cordova-plugin-advanced-http/src/android/com/silkimen/http/TLSConfiguration.java
  27. 63
    0
      node_modules/cordova-plugin-advanced-http/src/android/com/silkimen/http/TLSSocketFactory.java
  28. 283
    0
      node_modules/cordova-plugin-advanced-http/src/browser/cordova-http-plugin.js
  29. 353
    0
      node_modules/cordova-plugin-advanced-http/src/ios/AFNetworking/AFHTTPSessionManager.h
  30. 464
    0
      node_modules/cordova-plugin-advanced-http/src/ios/AFNetworking/AFHTTPSessionManager.m
  31. 206
    0
      node_modules/cordova-plugin-advanced-http/src/ios/AFNetworking/AFNetworkReachabilityManager.h
  32. 263
    0
      node_modules/cordova-plugin-advanced-http/src/ios/AFNetworking/AFNetworkReachabilityManager.m
  33. 41
    0
      node_modules/cordova-plugin-advanced-http/src/ios/AFNetworking/AFNetworking.h
  34. 154
    0
      node_modules/cordova-plugin-advanced-http/src/ios/AFNetworking/AFSecurityPolicy.h
  35. 353
    0
      node_modules/cordova-plugin-advanced-http/src/ios/AFNetworking/AFSecurityPolicy.m
  36. 479
    0
      node_modules/cordova-plugin-advanced-http/src/ios/AFNetworking/AFURLRequestSerialization.h
  37. 1355
    0
      node_modules/cordova-plugin-advanced-http/src/ios/AFNetworking/AFURLRequestSerialization.m
  38. 318
    0
      node_modules/cordova-plugin-advanced-http/src/ios/AFNetworking/AFURLResponseSerialization.h
  39. 806
    0
      node_modules/cordova-plugin-advanced-http/src/ios/AFNetworking/AFURLResponseSerialization.m
  40. 500
    0
      node_modules/cordova-plugin-advanced-http/src/ios/AFNetworking/AFURLSessionManager.h
  41. 1239
    0
      node_modules/cordova-plugin-advanced-http/src/ios/AFNetworking/AFURLSessionManager.m
  42. 8
    0
      node_modules/cordova-plugin-advanced-http/src/ios/BinaryRequestSerializer.h
  43. 53
    0
      node_modules/cordova-plugin-advanced-http/src/ios/BinaryRequestSerializer.m
  44. 8
    0
      node_modules/cordova-plugin-advanced-http/src/ios/BinaryResponseSerializer.h
  45. 126
    0
      node_modules/cordova-plugin-advanced-http/src/ios/BinaryResponseSerializer.m
  46. 19
    0
      node_modules/cordova-plugin-advanced-http/src/ios/CordovaHttpPlugin.h
  47. 565
    0
      node_modules/cordova-plugin-advanced-http/src/ios/CordovaHttpPlugin.m
  48. 20
    0
      node_modules/cordova-plugin-advanced-http/src/ios/SDNetworkActivityIndicator/LICENSE
  49. 52
    0
      node_modules/cordova-plugin-advanced-http/src/ios/SDNetworkActivityIndicator/README.md
  50. 18
    0
      node_modules/cordova-plugin-advanced-http/src/ios/SDNetworkActivityIndicator/SDNetworkActivityIndicator.h
  51. 70
    0
      node_modules/cordova-plugin-advanced-http/src/ios/SDNetworkActivityIndicator/SDNetworkActivityIndicator.m
  52. 8
    0
      node_modules/cordova-plugin-advanced-http/src/ios/TextRequestSerializer.h
  53. 53
    0
      node_modules/cordova-plugin-advanced-http/src/ios/TextRequestSerializer.m
  54. 8
    0
      node_modules/cordova-plugin-advanced-http/src/ios/TextResponseSerializer.h
  55. 145
    0
      node_modules/cordova-plugin-advanced-http/src/ios/TextResponseSerializer.m
  56. 25
    0
      node_modules/cordova-plugin-advanced-http/www/advanced-http.js
  57. 70
    0
      node_modules/cordova-plugin-advanced-http/www/cookie-handler.js
  58. 43
    0
      node_modules/cordova-plugin-advanced-http/www/dependency-validator.js
  59. 9
    0
      node_modules/cordova-plugin-advanced-http/www/error-codes.js
  60. 8
    0
      node_modules/cordova-plugin-advanced-http/www/global-configs.js
  61. 503
    0
      node_modules/cordova-plugin-advanced-http/www/helpers.js
  62. 32
    0
      node_modules/cordova-plugin-advanced-http/www/js-util.js
  63. 181
    0
      node_modules/cordova-plugin-advanced-http/www/local-storage-store.js
  64. 20
    0
      node_modules/cordova-plugin-advanced-http/www/lodash.js
  65. 32
    0
      node_modules/cordova-plugin-advanced-http/www/messages.js
  66. 47
    0
      node_modules/cordova-plugin-advanced-http/www/ponyfills.js
  67. 202
    0
      node_modules/cordova-plugin-advanced-http/www/public-interface.js
  68. 5089
    0
      node_modules/cordova-plugin-advanced-http/www/umd-tough-cookie.js
  69. 103
    0
      node_modules/cordova-plugin-advanced-http/www/url-util.js
  70. 30
    0
      node_modules/cordova-plugin-file/.jshintrc
  71. 1
    0
      node_modules/cordova-plugin-file/.ratignore
  72. 37
    0
      node_modules/cordova-plugin-file/CONTRIBUTING.md
  73. 202
    0
      node_modules/cordova-plugin-file/LICENSE
  74. 5
    0
      node_modules/cordova-plugin-file/NOTICE
  75. 833
    0
      node_modules/cordova-plugin-file/README.md
  76. 496
    0
      node_modules/cordova-plugin-file/RELEASENOTES.md
  77. 120
    0
      node_modules/cordova-plugin-file/doc/plugins.md
  78. 87
    0
      node_modules/cordova-plugin-file/package.json
  79. 260
    0
      node_modules/cordova-plugin-file/plugin.xml
  80. 294
    0
      node_modules/cordova-plugin-file/src/android/AssetFilesystem.java
  81. 223
    0
      node_modules/cordova-plugin-file/src/android/ContentFilesystem.java
  82. 134
    0
      node_modules/cordova-plugin-file/src/android/DirectoryManager.java
  83. 29
    0
      node_modules/cordova-plugin-file/src/android/EncodingException.java
  84. 29
    0
      node_modules/cordova-plugin-file/src/android/FileExistsException.java
  85. 1225
    0
      node_modules/cordova-plugin-file/src/android/FileUtils.java
  86. 331
    0
      node_modules/cordova-plugin-file/src/android/Filesystem.java
  87. 30
    0
      node_modules/cordova-plugin-file/src/android/InvalidModificationException.java
  88. 513
    0
      node_modules/cordova-plugin-file/src/android/LocalFilesystem.java
  89. 64
    0
      node_modules/cordova-plugin-file/src/android/LocalFilesystemURL.java
  90. 29
    0
      node_modules/cordova-plugin-file/src/android/NoModificationAllowedException.java
  91. 94
    0
      node_modules/cordova-plugin-file/src/android/PendingRequests.java
  92. 30
    0
      node_modules/cordova-plugin-file/src/android/TypeMismatchException.java
  93. 47
    0
      node_modules/cordova-plugin-file/src/android/build-extras.gradle
  94. 1059
    0
      node_modules/cordova-plugin-file/src/browser/FileProxy.js
  95. 30
    0
      node_modules/cordova-plugin-file/src/ios/CDVAssetLibraryFilesystem.h
  96. 253
    0
      node_modules/cordova-plugin-file/src/ios/CDVAssetLibraryFilesystem.m
  97. 157
    0
      node_modules/cordova-plugin-file/src/ios/CDVFile.h
  98. 1119
    0
      node_modules/cordova-plugin-file/src/ios/CDVFile.m
  99. 32
    0
      node_modules/cordova-plugin-file/src/ios/CDVLocalFilesystem.h
  100. 0
    0
      node_modules/cordova-plugin-file/src/ios/CDVLocalFilesystem.m

+ 19
- 0
node_modules/cordova-plugin-advanced-http/.editorconfig Visa fil

@@ -0,0 +1,19 @@
1
+# EditorConfig helps developers define and maintain consistent
2
+# coding styles between different editors and IDEs
3
+# editorconfig.org
4
+
5
+root = true
6
+
7
+[*]
8
+# Change these settings to your own preference
9
+indent_style = space
10
+indent_size = 2
11
+
12
+# We recommend you to keep these unchanged
13
+end_of_line = lf
14
+charset = utf-8
15
+trim_trailing_whitespace = true
16
+insert_final_newline = true
17
+
18
+[*.md]
19
+trim_trailing_whitespace = false

+ 33
- 0
node_modules/cordova-plugin-advanced-http/.github/ISSUE_TEMPLATE/--bug-report.md Visa fil

@@ -0,0 +1,33 @@
1
+---
2
+name: "\U0001F41BBug report"
3
+about: Create a report to help us improve
4
+title: "[Bug] [platform] your issue title"
5
+labels: ''
6
+assignees: ''
7
+
8
+---
9
+
10
+**Describe the bug**
11
+A clear and concise description of what the bug is and what you expected to happen.
12
+
13
+**System info**
14
+ - affected HTTP plugin version: [e.g. 2.1.1]
15
+ - affected platform(s) and version(s): [e.g. iOS 12.2]
16
+ - affected device(s): [e.g. iPhone 8]
17
+ - cordova version: [e.g. 6.5.0]
18
+ - cordova platform version(s): [e.g. android 7.0.0, browser 5.0.3]
19
+
20
+**Are you using ionic-native-wrapper?**
21
+ - ionic-native-wrapper version: [e.g. 5.8.0]
22
+ - did you check [ionic-native issue tracker](https://github.com/ionic-team/ionic-native/issues) for your problem?
23
+
24
+**Minimum viable code to reproduce**
25
+If applicable, add formatted sample coding to help explain your problem.
26
+
27
+e.g.:
28
+```js
29
+cordova.plugin.http.setDataSerializer('urlencoded');
30
+```
31
+
32
+**Screenshots**
33
+If applicable, add screenshots to help explain your problem.

+ 21
- 0
node_modules/cordova-plugin-advanced-http/.github/ISSUE_TEMPLATE/--feature-request.md Visa fil

@@ -0,0 +1,21 @@
1
+---
2
+name: "\U0001F680Feature request"
3
+about: Suggest an idea for this project
4
+title: "[Feature]"
5
+labels: ''
6
+assignees: ''
7
+
8
+---
9
+
10
+**Is your feature request related to a problem? Please describe.**
11
+A clear and concise description of what the problem is. e.g. I'm always frustrated when [...]
12
+
13
+**Describe the solution you'd like**
14
+A clear and concise description of what you want to happen. If applicable, add formatted sample coding to help explain your idea.
15
+
16
+```js
17
+// do some fancy stuff here
18
+```
19
+
20
+**Describe alternatives you've considered**
21
+A clear and concise description of any alternative solutions or features you've considered.

+ 18
- 0
node_modules/cordova-plugin-advanced-http/.github/ISSUE_TEMPLATE/--support-question.md Visa fil

@@ -0,0 +1,18 @@
1
+---
2
+name: "\U0001F914Support question"
3
+about: Ask the community
4
+title: ''
5
+labels: question
6
+assignees: ''
7
+
8
+---
9
+
10
+**You've got questions?**
11
+
12
+We primarily use GitHub as an issue tracker; for usage and support questions, please check out these resources below. Thanks! 😁
13
+
14
+* README.md: https://github.com/silkimen/cordova-plugin-advanced-http/blob/master/README.md
15
+* StackOverflow: https://stackoverflow.com/questions/tagged/cordova-plugin-advanced-http using the tag `cordova-plugin-advanced-http`
16
+* Wiki: https://github.com/silkimen/cordova-plugin-advanced-http/wiki
17
+
18
+And don't forget: If you get help, help others. Good karma rulez!

+ 65
- 0
node_modules/cordova-plugin-advanced-http/.github/workflows/ci.yml Visa fil

@@ -0,0 +1,65 @@
1
+name: Cordova HTTP Plugin CI
2
+
3
+on: [push]
4
+
5
+env:
6
+  nodejs: '10.x'
7
+
8
+jobs:
9
+  test-www-interface:
10
+    runs-on: ubuntu-latest
11
+    steps:
12
+    - uses: actions/checkout@v1
13
+    - name: Install Node.js ${{ env.nodejs }}
14
+      uses: actions/setup-node@v1
15
+      with:
16
+        node-version: ${{ env.nodejs }}
17
+    - name: Install node modules
18
+      run: npm ci
19
+    - name: Run WWW interface tests
20
+      run: npm run testjs
21
+
22
+  build-ios:
23
+    runs-on: macOS-latest
24
+    steps:
25
+    - uses: actions/checkout@v1
26
+    - name: Install Node.js ${{ env.nodejs }}
27
+      uses: actions/setup-node@v1
28
+      with:
29
+        node-version: ${{ env.nodejs }}
30
+    - name: Install node modules
31
+      run: npm ci
32
+    - name: Update test cert for httpbin.org
33
+      run: npm run updatecert
34
+    - name: Build test app
35
+      run: scripts/build-test-app.sh --ios --emulator
36
+
37
+  build-android:
38
+    runs-on: ubuntu-latest
39
+    env:
40
+      BROWSERSTACK_USERNAME: ${{ secrets.BROWSERSTACK_USERNAME }}
41
+      BROWSERSTACK_ACCESS_KEY: ${{ secrets.BROWSERSTACK_ACCESS_KEY }}
42
+    steps:
43
+    - uses: actions/checkout@v1
44
+    - name: Install Node.js ${{ env.nodejs }}
45
+      uses: actions/setup-node@v1
46
+      with:
47
+        node-version: ${{ env.nodejs }}
48
+    - name: Install node modules
49
+      run: npm ci
50
+    - name: Install JDK 1.8
51
+      uses: actions/setup-java@v1
52
+      with:
53
+        java-version: 1.8
54
+    - name: Update test cert for httpbin.org
55
+      run: npm run updatecert
56
+    - name: Add workaround for mipsel reference
57
+      run: sudo mkdir -p $ANDROID_HOME/ndk-bundle/toolchains/mips64el-linux-android-4.9/prebuilt/linux-x86_64
58
+    - name: Build test app
59
+      run: scripts/build-test-app.sh --android --device
60
+    - name: Upload artifact to BrowserStack
61
+      if: env.BROWSERSTACK_USERNAME != ''
62
+      run: scripts/upload-browserstack.sh --android
63
+    - name: Run e2e tests
64
+      if: env.BROWSERSTACK_USERNAME != ''
65
+      run: scripts/test-app.sh --android --device

+ 61
- 0
node_modules/cordova-plugin-advanced-http/.travis.yml Visa fil

@@ -0,0 +1,61 @@
1
+notifications:
2
+  slack:
3
+    secure: twDT06GAiu0jsKizow7TcghZj70KbuuTrlo02QGmbSxBk2rJfsXSrHAsA3+s/9Q4mudENk6na7fs1aPCxz+u2etUGp+2PaJKVKR5n3jrNNt3SnYeWsBgVo7o7H1aLXatX3a+TdPXh1F5gQ4Ycr93nTYbW/077jsOholwbOHDZE3VcU9dzNPwFaEvhrDbr/ei3tef0ZiM1qxIad74TgwWMKClwai3I7HCVkZOPsyV+ve6cdIJ8Dt47JzFUHSW3SZuoe5Kywxvp0VvMo/QAJw95y3edNafx4EXHwbaN71rpGWSJXIKSZzcSQalZJ9DxGYspIBkWvGsNuQRzG9CzIoNQK10iERlIVC5vKDfKX22gayOQPSDkswJzIduylBUC8zdTPCndXyNEM/Lrj6hg+ksFWN58vYNPgfUeiga7X+LV5HytftsMFW+xx2kbnGeU8doGeX8Q8G7h9OIkHCTTG7R0ldYMIqTm8YJGPkRIv4OReC5ZOhiZD+wSg4KQ0wmMeRi+hyn+I5UPnKEOHAIN8FmLNCZFbgr1wuPFp9xnJIOcumQnQVZ2t6vk6IjIbwhYPWCnf7Sr4BvJxE8eyiLrEaXK0FiPb3My9wK9tLFjj1zdD7e4+SLq+WFMeCxp2eXOGF0Bu+2VK2tGjgWhaudaIpjbRQAAQ5nPa43h16NruEvNWI=
4
+
5
+cache:
6
+  directories:
7
+    - node_modules
8
+
9
+addons:
10
+  sauce_connect: true
11
+
12
+matrix:
13
+  include:
14
+  - name: "iOS Build & Test"
15
+    language: objective-c
16
+    sudo: false
17
+    os: osx
18
+    osx_image: xcode10.1
19
+
20
+    before_install:
21
+    - export LANG=en_US.UTF-8
22
+
23
+    install:
24
+    - npm install
25
+
26
+    script:
27
+    - npm run testjs &&
28
+      npm run updatecert &&
29
+      scripts/build-test-app.sh --ios --emulator &&
30
+      scripts/upload-saucelabs.sh --ios &&
31
+      scripts/test-app.sh --ios --emulator;
32
+
33
+  - name: "Android Build & Test"
34
+    language: android
35
+    sudo : required
36
+
37
+    android:
38
+      components:
39
+        - tools
40
+        - platform-tools
41
+        - build-tools-28.0.3
42
+        - android-28
43
+        - extra-android-support
44
+        - extra-android-m2repository
45
+        - extra-google-m2repository
46
+
47
+    before_install:
48
+    - export LANG=en_US.UTF-8 &&
49
+      curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash - &&
50
+      sudo apt-get install -y nodejs
51
+    - yes | sdkmanager --update
52
+
53
+    install:
54
+    - npm install
55
+
56
+    script:
57
+    - npm run testjs &&
58
+      npm run updatecert &&
59
+      scripts/build-test-app.sh --android --emulator &&
60
+      scripts/upload-saucelabs.sh --android &&
61
+      scripts/test-app.sh --android --emulator;

+ 3
- 0
node_modules/cordova-plugin-advanced-http/.vscode/settings.json Visa fil

@@ -0,0 +1,3 @@
1
+{
2
+    "editor.tabSize": 2
3
+}

+ 343
- 0
node_modules/cordova-plugin-advanced-http/CHANGELOG.md Visa fil

@@ -0,0 +1,343 @@
1
+# Changelog
2
+
3
+## 3.0.1
4
+
5
+- Fixed #359: memory leakage leads to app crashes on Android
6
+- Fixed #355: responseType "json" not working with valid JSON response on browser (thanks millerg6711)
7
+
8
+## 3.0.0
9
+
10
+- Feature #158: support removing headers which were previously set via "setHeader"
11
+
12
+- Fixed #345: empty file names are not handled correctly (thanks ikosta)
13
+
14
+- :warning: **Breaking Change**: Dropped support for Android < 5.1
15
+- :warning: **Breaking Change**: Removed "disableRedirect", use "setFollowRedirect" instead
16
+- :warning: **Breaking Change**: Removed "setSSLCertMode", use "setServerTrustMode" instead
17
+
18
+## 2.5.1
19
+
20
+- Fixed #334: empty JSON response triggers error even though request is successful (thanks antikalk)
21
+- Fixed #248: clearCookies() does not work on iOS
22
+
23
+## 2.5.0
24
+
25
+- Feature #56: add support for X.509 client certificate based authentication
26
+
27
+## 2.4.1
28
+
29
+- Fixed #296: multipart requests are not serialized on browser platform
30
+- Fixed #301: data is not decoded correctly when responseType is "json" (thanks antikalk)
31
+- Fixed #300: FormData object containing null or undefined value is not serialized correctly
32
+
33
+## 2.4.0
34
+
35
+- Feature #291: add support for sending 'raw' requests (thanks to jachstet-sea and chuchuva)
36
+- Feature #155: add OPTIONS method
37
+- Feature #283: improve error message on timeout on browser platform
38
+
39
+## 2.3.1
40
+
41
+- Fixed #275: getAllCookies() is broken because of a typo (thanks ath0mas)
42
+
43
+## 2.3.0
44
+
45
+- Feature #101: Support "multipart/form-data" requests (thanks SDA SE Open Industry Solutions)
46
+
47
+#### Important information
48
+This feature depends on several Web APIs. See https://github.com/silkimen/cordova-plugin-advanced-http/wiki/Web-APIs-required-for-Multipart-requests for more info.
49
+
50
+## 2.2.0
51
+
52
+- Feature #239: add enumeration style object for error codes
53
+- Feature #253: add support for response type "json"
54
+- Feature #127: add multiple file upload (thanks SDA SE Open Industry Solutions and nilswitschel)
55
+
56
+## 2.1.1
57
+
58
+- Fixed #224: response type "arraybuffer" and "blob" not working on browser platform
59
+
60
+## 2.1.0
61
+
62
+- Feature #216: Support for response type `arraybuffer`
63
+- Feature #171: Support for response type `blob`
64
+- Feature #205: Add preference for configuring OKHTTP version (thanks RougeCiel)
65
+
66
+## 2.0.11
67
+
68
+- Fixed #221: headers not set on Android when request fails due to non-success status code
69
+
70
+## 2.0.10
71
+
72
+- Fixed #218: headers are used as params on browser platform
73
+
74
+## 2.0.9
75
+
76
+- Fixed #204: broken support for cordova-android  < 7.0
77
+
78
+- :warning: **Deprecation**: Deprecated "disableRedirect" in favor of "setFollowRedirect"
79
+
80
+## 2.0.8
81
+
82
+- Fixed #198: cookie header is always passed even if there is no cookie
83
+- Fixed #201: browser implementation is broken due to broken dependency
84
+- Fixed #197: iOS crashes when multiple request are done simultaneously (reverted a8e3637)
85
+- Fixed #189: error code mappings are not precise
86
+- Fixed #200: compatibility with Java 6 is broken due to string switch on Android
87
+
88
+- :warning: **Deprecation**: Deprecated "setSSLCertMode" in favor of "setServerTrustMode"
89
+
90
+## 2.0.7
91
+
92
+- Fixed #195: URLs are double-encoded on Android
93
+
94
+## 2.0.6
95
+
96
+- Fixed #187: setSSLCertMode with "default" throws an error on Android
97
+- Fixed #115: HTTP connections are not kept alive on iOS (thanks MorpheusDe97)
98
+
99
+## 2.0.5
100
+
101
+- Fixed #185: need more detailed SSL error message
102
+
103
+## 2.0.4
104
+
105
+- Fixed #179: sending empty string with utf8 serializer throws an exception
106
+
107
+## 2.0.3
108
+
109
+- Fixed #172: plugin does not respect user installed CA certs on Android
110
+
111
+#### Important information
112
+We've changed a default behavior on Android. User installed CA certs are respected now.
113
+If you don't want this for your needs, you can switch back to old behavior by setting SSL cert mode to `legacy`.
114
+
115
+## 2.0.2
116
+
117
+- Fixed #142: Plugin affected by REDoS Issue of tough-cookie
118
+- Fixed #157: Arguments are double URL-encoded on "downloadFile" (thanks TheZopo)
119
+- Fixed #164: Arguments are double URL-encoded on "head" (thanks ath0mas)
120
+
121
+## 2.0.1
122
+
123
+- Fixed #136: Content-Type header non-overwritable on browser platform
124
+
125
+## 2.0.0
126
+
127
+- Feature #103: implement HTTP SSL cert modes
128
+
129
+- :warning: **Breaking Change**: Removed AngularJS (v1) integration service
130
+- :warning: **Breaking Change**: Removed "enableSSLPinning" and "acceptAllCerts", use "setSSLCertMode" instead
131
+- :warning: **Breaking Change**: Certificates must be placed in "www/certificates" folder
132
+
133
+## 1.11.1
134
+
135
+- Fixed #92: headers not deserialized on platform "browser"
136
+
137
+## 1.11.0
138
+
139
+- Feature #77: allow overriding global settings for each single request
140
+- Feature #11: add support for "browser" platform
141
+
142
+## 1.10.2
143
+
144
+- Fixed #78: overriding header "Content-Type" not working on Android
145
+- Fixed #79: PATCH operation not working on Android API level 19 and older (thanks chax)
146
+- Fixed #83: App crashes on error during download operation on iOS (thanks troyanskiy)
147
+- Fixed #76: upload sequence is not respecting order of operations needed by some sites (thanks Johny101)
148
+
149
+- :warning: **Deprecation**: AngularJS service is deprecated now and will be removed anytime soon
150
+
151
+## 1.10.1
152
+
153
+- Fixed #71: does not encode query string in URL correctly on Android
154
+- Fixed #72: app crashes if response encoding is not UTF-8 (thanks jkfb)
155
+
156
+## 1.10.0
157
+
158
+- Feature #34: add new serializer "utf8" sending utf-8 encoded plain text (thanks robertocapuano)
159
+
160
+## 1.9.1
161
+
162
+- Fixed #45: does not encode arrays correctly as HTTP GET parameter on Android
163
+- Fixed #54: requests are not responding on iOS with non-string values in header object
164
+- Fixed #58: white-list of allowed content-types should be removed for iOS
165
+
166
+## v1.9.0
167
+
168
+- Feature #44: "getCookieString" method is exposed
169
+- Feature #43: added support for content type "application/javascript" on iOS (thanks wh33ler)
170
+- Feature #46: "setCookie" allows adding custom cookies
171
+
172
+## v1.8.1
173
+
174
+- Fixed #27: "uploadFile" method doesn't return data object on iOS (thanks Faisalali23 and laiyinjie)
175
+- Fixed #40: generic error codes are different on Android and iOS
176
+
177
+## v1.8.0
178
+
179
+- Feature #33: response object contains response url
180
+
181
+## v1.7.1
182
+
183
+- Fixed #36: setting basic authentication not working correctly (thanks jkfb)
184
+- Fixed #35: Android headers are not normalized (not returned in lowercase)
185
+- Fixed #26: JSON request with array data is not working on Android (JSON error)
186
+
187
+## v1.7.0
188
+
189
+- Feature #24: "setHeader" allows configuring headers for specified host
190
+
191
+## v1.6.2
192
+
193
+- Change #29: removed "validateDomainName" (see info notice)
194
+- Fixed #31: request fails throwing error on erroneous cookies
195
+- Fixed #28: added support for content type "application/hal+json" on iOS (thanks ryandegruyter)
196
+
197
+#### Important information
198
+We've decided to remove the `validateDomainName()` method, because people were complaining that `acceptAllCerts(true)` is not behaving as expected. And also it's not a good idea to disable domain name validation while using valid certs, because it pretends having a secure connection, but it isn't.
199
+
200
+You should either use valid certs with domain name validation enabled (safe for production use) or accept any certs without domain name validation (only for private dev environments). I strongly discourage using fake certs in public networks.
201
+
202
+Therefore we are disabling domain name validation automatically, when you set `acceptAllCerts(true)`. So if you were using `validateDomainName()` function, you need to remove this function call for v1.6.2+.
203
+
204
+## v1.6.1
205
+
206
+- Fixed #23: PATCH method broken on android
207
+
208
+## v1.6.0
209
+
210
+- Feature #18: implemented PATCH method (thanks akhatri for android implementation)
211
+- Feature #21: added redirection control (thanks to notsyncing and kesozjura)
212
+- Fixed #16: cordova tries to run build script during plugin install
213
+
214
+## v1.5.10
215
+
216
+- Fixed #10: fix gzip decompression when request header accepts gzip compression (thanks to DayBr3ak)
217
+- Fixed #13: fix angular integration for `setDataSerializer` (thanks to RangerRick)
218
+- Added some missing documentation (thanks to RangerRick)
219
+
220
+## v1.5.9
221
+
222
+- Fixed case-sensitive folder name of Android source files
223
+
224
+## v1.5.8
225
+
226
+- Use the same error codes if a request timed out
227
+
228
+## v1.5.7
229
+
230
+- Fixed a bug in cookie handling (cookies containing an "Expires" string)
231
+- Added setRequestTimeout function to set the timeout in seconds for all further requests
232
+
233
+## v1.5.6
234
+
235
+- All response header keys are converted to lowercase (iOS only)
236
+
237
+## v1.5.5
238
+
239
+- added a function to remove all cookies for a URL
240
+
241
+## v1.5.4
242
+
243
+- fixed an error if the response has no "headers" field
244
+
245
+## v1.5.3
246
+
247
+- handles cookies correctly on non-success response from server
248
+- throws error when a callback function is missing
249
+
250
+## v1.5.2
251
+
252
+- fixed missing file "umd-tough-cookie.js“ (caused by missing file ".npmignore")
253
+
254
+## v1.5.1
255
+
256
+- fixed case-sensitive path name of android source files ("CordovaHTTP" --> "cordovahttp")
257
+
258
+## v1.5.0
259
+
260
+- added cookie handling
261
+- cookies are persisted via web storage API
262
+
263
+## v1.4.0
264
+
265
+- forked from "cordova-plugin-http" v1.2.0 (see https://github.com/wymsee/cordova-HTTP)
266
+- added configuration for data serializer
267
+- added HTTP methods PUT and DELETE
268
+
269
+# Previous changelog (cordova-plugin-http)
270
+
271
+## v1.2.0
272
+
273
+- Added support for TLSv1.1 and TLSv1.2 for android versions 4.1-4.4 (API levels 16-19)
274
+
275
+### Potentially Breaking Changes that really shouldn't matter because you shouldn't be using SSLv3
276
+
277
+- Dropped SSLv3 support for all API Levels < 20.  It will now only work on API Levels 20-22.
278
+
279
+## v1.1.0
280
+
281
+- Fixed the body of errors not being returned in iOS
282
+- Updated AFNetworking to 3.1.0
283
+
284
+### Potentially Breaking Changes
285
+
286
+- Disable encoding get() URLS in android (Thanks to devgeeks)
287
+
288
+## v1.0.3
289
+
290
+- Fixed version number in plugin.xml
291
+
292
+## v1.0.2
293
+
294
+- Fixed bug using useBasicAuth and setHeader from angular
295
+
296
+## v1.0.1
297
+
298
+- updated README
299
+
300
+## v1.0.0
301
+
302
+- Added getBasicAuthHeader function
303
+- Added necessary iOS framework (Thanks to EddyVerbruggen)
304
+- Request internet permission in android (Thanks to mbektchiev)
305
+- Fix acceptAllCerts doesn't call callbacks (Thanks to EddyVerbruggen)
306
+- Add validateDomainName (Thanks to denisbabineau)
307
+- Add HEAD request support (untested) (Thanks to denisbabineau)
308
+
309
+### Potentially Breaking Changes
310
+
311
+- Update cordova file plugin dependency (Thanks to denisbabineau)
312
+- useBasicAuthHeader and setHeader are now synchronous functions
313
+- updated AFNetworking to 3.0.4 - only iOS 7+ is now supported
314
+- updated http-request to 6.0
315
+
316
+## v0.1.4
317
+
318
+- Support for certificates in www/certificates folder (Thanks to EddyVerbruggen)
319
+
320
+## v0.1.3
321
+
322
+- Update AFNetworking to 2.4.1 for iOS bug fix in Xcode 6
323
+
324
+## v0.1.2
325
+
326
+- Fixed plugin.xml for case sensitive filesystems (Thanks to andrey-tsaplin)
327
+
328
+## v0.1.1
329
+
330
+- Fixed a bug that prevented building
331
+
332
+## v0.1.0
333
+
334
+- Initial release
335
+
336
+
337
+## Contributions not noted above
338
+
339
+- Fixed examples (Thanks to devgeeks)
340
+- Reports SSL Handshake errors rather than giving a generic error (Thanks to devgeeks)
341
+- Exporting http as a module (Thanks to pvsaikrishna)
342
+- Added Limitations section to readme (Thanks to cvillerm)
343
+- Fixed examples (Thanks to hideov)

+ 82
- 0
node_modules/cordova-plugin-advanced-http/CONTRIBUTING.md Visa fil

@@ -0,0 +1,82 @@
1
+# Contributing to Advanced HTTP Plugin
2
+
3
+We'd love for you to contribute to our source code and to make Advanced HTTP even better than it is
4
+today! Here are the guidelines we'd like you to follow:
5
+
6
+ - [Issues and Bugs](#issue)
7
+ - [Feature Requests](#feature)
8
+ - [Submission Guidelines](#submit)
9
+
10
+## <a name="issue"></a> Found an Issue?
11
+
12
+If you find a bug in the source code or a mistake in the documentation, you can help us by
13
+submitting an issue to our [GitHub Repository](https://github.com/silkimen/cordova-plugin-advanced-http/issues).
14
+Even better you can submit a Pull Request with a fix.
15
+
16
+## <a name="feature"></a> Want a Feature?
17
+
18
+You can request a new feature by submitting an issue to our
19
+[GitHub Repository](https://github.com/silkimen/cordova-plugin-advanced-http/issues).
20
+If you would like to implement a new feature then consider what kind of change it is:
21
+
22
+* **Major Changes** that you wish to contribute to the project should be discussed first so that we
23
+  can better coordinate our efforts, prevent duplication of work, and help you to craft the change
24
+  so that it is successfully accepted into the project. Please submit an issue to our GitHub Repository
25
+  for discussion.
26
+* **Small Changes** can be crafted and submitted to the GitHub Repository as a Pull Request.
27
+
28
+## <a name="submit"></a> Submission Guidelines
29
+
30
+### Submitting an Issue
31
+Before you submit your issue search the archive, maybe your question was already answered.
32
+
33
+If your issue appears to be a bug, and hasn't been reported, open a new issue. Help us to maximize
34
+the effort we can spend fixing issues and adding new features, by not reporting duplicate issues.
35
+Providing the following information will increase the chances of your issue being dealt with
36
+quickly:
37
+
38
+* **Overview of the Issue** - if an error is being thrown a non-minified stack trace helps
39
+* **Motivation for or Use Case** - explain why this is a bug for you
40
+* **Advanced HTTP Version(s)** - is it a regression?
41
+* **Operating System** - is this a problem with all supported OS or only specific ones?
42
+* **Related Issues** - has a similar issue been reported before?
43
+* **Suggest a Fix** - if you can't fix the bug yourself, perhaps you can point to what might be
44
+  causing the problem (line of code or commit)
45
+
46
+**If you get help, help others. Good karma rulez!**
47
+
48
+### Submitting a Pull Request
49
+Before you submit your pull request consider the following guidelines:
50
+
51
+* Search [GitHub](https://github.com/silkimen/cordova-plugin-advanced-http/pulls) for an open or
52
+  closed Pull Request that relates to your submission. You don't want to duplicate effort.
53
+* Make your changes in a new git branch:
54
+
55
+    ```shell
56
+    git checkout -b my-fix-branch master
57
+    ```
58
+* Create your patch
59
+* Commit your changes using a descriptive commit message
60
+* Push your branch to GitHub:
61
+
62
+    ```shell
63
+    git push origin my-fix-branch
64
+    ```
65
+
66
+In GitHub, send a pull request to `cordova-plugin-advanced-http:master`.
67
+If we suggest changes or the [CI build fails](#cibuild), then:
68
+
69
+* Make the required updates.
70
+* Commit your changes to your branch (e.g. `my-fix-branch`).
71
+* Push the changes to your GitHub repository (this will update your Pull Request).
72
+
73
+That's it! Thank you for your contribution!
74
+
75
+### <a name="cibuild"></a> Pull Request Feedback
76
+You can always check the results of the latest CI builds on
77
+[Travis CI](https://travis-ci.org/silkimen/cordova-plugin-advanced-http/).
78
+You can use this information to inspect failing tests in your PR.
79
+
80
+## Attribution
81
+This document is adapted from
82
+[AngularJS' Contribution Guidelines](https://github.com/angular/angular.js/blob/master/CONTRIBUTING.md)

+ 23
- 0
node_modules/cordova-plugin-advanced-http/LICENSE Visa fil

@@ -0,0 +1,23 @@
1
+The MIT License (MIT)
2
+
3
+Copyright (c) 2019 Sefa Ilkimen
4
+Copyright (c) 2017 Mobisys GmbH
5
+Copyright (c) 2014 Wymsee, Inc
6
+
7
+Permission is hereby granted, free of charge, to any person obtaining a copy
8
+of this software and associated documentation files (the "Software"), to deal
9
+in the Software without restriction, including without limitation the rights
10
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+copies of the Software, and to permit persons to whom the Software is
12
+furnished to do so, subject to the following conditions:
13
+
14
+The above copyright notice and this permission notice shall be included in all
15
+copies or substantial portions of the Software.
16
+
17
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+SOFTWARE.

+ 443
- 0
node_modules/cordova-plugin-advanced-http/README.md Visa fil

@@ -0,0 +1,443 @@
1
+Cordova Advanced HTTP
2
+=====================
3
+[![npm version](https://img.shields.io/npm/v/cordova-plugin-advanced-http)](https://www.npmjs.com/package/cordova-plugin-advanced-http?activeTab=versions)
4
+[![MIT Licence](https://img.shields.io/badge/license-MIT-blue?style=flat)](https://opensource.org/licenses/mit-license.php)
5
+[![downloads/month](https://img.shields.io/npm/dm/cordova-plugin-advanced-http.svg)](https://www.npmjs.com/package/cordova-plugin-advanced-http)
6
+
7
+[![Travis Build Status](https://img.shields.io/travis/silkimen/cordova-plugin-advanced-http/master?label=Travis%20CI)](https://travis-ci.org/silkimen/cordova-plugin-advanced-http)
8
+[![GitHub Build Status](https://img.shields.io/github/workflow/status/silkimen/cordova-plugin-advanced-http/Cordova%20HTTP%20Plugin%20CI/master?label=GitHub%20Actions)](https://github.com/silkimen/cordova-plugin-advanced-http/actions)
9
+
10
+
11
+Cordova / Phonegap plugin for communicating with HTTP servers.  Supports iOS, Android and [Browser](#browserSupport).
12
+
13
+This is a fork of [Wymsee's Cordova-HTTP plugin](https://github.com/wymsee/cordova-HTTP).
14
+
15
+## Advantages over Javascript requests
16
+
17
+ - SSL / TLS Pinning
18
+ - CORS restrictions do not apply
19
+ - X.509 client certificate based authentication
20
+ - Handling of HTTP code 401 - read more at [Issue CB-2415](https://issues.apache.org/jira/browse/CB-2415)
21
+
22
+## Updates
23
+
24
+Please check [CHANGELOG.md](CHANGELOG.md) for details about updating to a new version.
25
+
26
+## Installation
27
+
28
+The plugin conforms to the Cordova plugin specification, it can be installed
29
+using the Cordova / Phonegap command line interface.
30
+
31
+```shell
32
+phonegap plugin add cordova-plugin-advanced-http
33
+
34
+cordova plugin add cordova-plugin-advanced-http
35
+```
36
+
37
+## Usage
38
+
39
+### Plain Cordova
40
+
41
+This plugin registers a global object located at `cordova.plugin.http`.
42
+
43
+### With Ionic-native wrapper
44
+
45
+Check the [Ionic docs](https://ionicframework.com/docs/native/http/) for how to use this plugin with Ionic-native.
46
+
47
+## Synchronous Functions
48
+
49
+### getBasicAuthHeader
50
+This returns an object representing a basic HTTP Authorization header of the form `{'Authorization': 'Basic base64encodedusernameandpassword'}`
51
+
52
+```js
53
+var header = cordova.plugin.http.getBasicAuthHeader('user', 'password');
54
+```
55
+
56
+### useBasicAuth
57
+This sets up all future requests to use Basic HTTP authentication with the given username and password.
58
+
59
+```js
60
+cordova.plugin.http.useBasicAuth('user', 'password');
61
+```
62
+
63
+### setHeader<a name="setHeader"></a>
64
+Set a header for all future requests to a specified host. Takes a hostname, a header and a value (must be a string value or null).
65
+
66
+```js
67
+cordova.plugin.http.setHeader('Hostname', 'Header', 'Value');
68
+```
69
+
70
+You can also define headers used for all hosts by using wildcard character "\*" or providing only two params.
71
+
72
+```js
73
+cordova.plugin.http.setHeader('*', 'Header', 'Value');
74
+cordova.plugin.http.setHeader('Header', 'Value');
75
+```
76
+
77
+The hostname also includes the port number. If you define a header for `www.example.com` it will not match following URL `http://www.example.com:8080`.
78
+
79
+```js
80
+// will match http://www.example.com/...
81
+cordova.plugin.http.setHeader('www.example.com', 'Header', 'Value');
82
+
83
+// will match http://www.example.com:8080/...
84
+cordova.plugin.http.setHeader('www.example.com:8080', 'Header', 'Value');
85
+```
86
+
87
+### setDataSerializer<a name="setDataSerializer"></a>
88
+Set the data serializer which will be used for all future PATCH, POST and PUT requests. Takes a string representing the name of the serializer.
89
+
90
+```js
91
+cordova.plugin.http.setDataSerializer('urlencoded');
92
+```
93
+
94
+You can choose one of these:
95
+* `urlencoded`: send data as url encoded content in body
96
+  * default content type "application/x-www-form-urlencoded"
97
+  * data must be an dictionary style `Object`
98
+* `json`: send data as JSON encoded content in body
99
+  * default content type "application/json"
100
+  * data must be an `Array` or an dictionary style `Object`
101
+* `utf8`: send data as plain UTF8 encoded string in body
102
+  * default content type "plain/text"
103
+  * data must be a `String`
104
+* `multipart`: send FormData objects as multipart content in body
105
+  * default content type "multipart/form-data"
106
+  * data must be an `FormData` instance
107
+* `raw`: send data as is, without any processing
108
+  * default content type "application/octet-stream"
109
+  * data must be an `Uint8Array` or an `ArrayBuffer`
110
+
111
+This defaults to `urlencoded`. You can also override the default content type headers by specifying your own headers (see [setHeader](#setHeader)).
112
+
113
+:warning: `urlencoded` does not support serializing deep structures whereas `json` does.
114
+
115
+:warning: `multipart` depends on several Web API standards which need to be supported in your web view. Check out https://github.com/silkimen/cordova-plugin-advanced-http/wiki/Web-APIs-required-for-Multipart-requests for more info.
116
+
117
+### setRequestTimeout
118
+Set the "read" timeout in seconds. This is the timeout interval to use when waiting for additional data.
119
+
120
+```js
121
+cordova.plugin.http.setRequestTimeout(5.0);
122
+```
123
+
124
+### setFollowRedirect<a name="setFollowRedirect"></a>
125
+Configure if it should follow redirects automatically. This defaults to true.
126
+
127
+```js
128
+cordova.plugin.http.setFollowRedirect(true);
129
+```
130
+
131
+### getCookieString
132
+Returns saved cookies (as string) matching given URL.
133
+
134
+```js
135
+cordova.plugin.http.getCookieString(url);
136
+```
137
+
138
+### setCookie
139
+Add a custom cookie. Takes a URL, a cookie string and an options object. See [ToughCookie documentation](https://github.com/salesforce/tough-cookie#setcookiecookieorstring-currenturl-options-cberrcookie) for allowed options.
140
+
141
+```js
142
+cordova.plugin.http.setCookie(url, cookie, options);
143
+```
144
+
145
+### clearCookies
146
+Clear the cookie store.
147
+
148
+```js
149
+cordova.plugin.http.clearCookies();
150
+```
151
+
152
+## Asynchronous Functions
153
+These functions all take success and error callbacks as their last 2 arguments.
154
+
155
+### setServerTrustMode<a name="setServerTrustMode"></a>
156
+Set server trust mode, being one of the following values:
157
+
158
+* `default`: default SSL trustship and hostname verification handling using system's CA certs
159
+* `legacy`: use legacy default behavior (< 2.0.3), excluding user installed CA certs (only for Android)
160
+* `nocheck`: disable SSL certificate checking and hostname verification, trusting all certs (meant to be used only for testing purposes)
161
+* `pinned`: trust only provided certificates
162
+
163
+To use SSL pinning you must include at least one `.cer` SSL certificate in your app project.  You can pin to your server certificate or to one of the issuing CA certificates. Include your certificate in the `www/certificates` folder. All `.cer` files found there will be loaded automatically.
164
+
165
+:warning: Your certificate must be DER encoded! If you only have a PEM encoded certificate read this [stackoverflow answer](http://stackoverflow.com/a/16583429/3182729). You want to convert it to a DER encoded certificate with a .cer extension.
166
+
167
+```js
168
+// enable SSL pinning
169
+cordova.plugin.http.setServerTrustMode('pinned', function() {
170
+  console.log('success!');
171
+}, function() {
172
+  console.log('error :(');
173
+});
174
+
175
+// use system's default CA certs
176
+cordova.plugin.http.setServerTrustMode('default', function() {
177
+  console.log('success!');
178
+}, function() {
179
+  console.log('error :(');
180
+});
181
+
182
+// disable SSL cert checking, only meant for testing purposes, do NOT use in production!
183
+cordova.plugin.http.setServerTrustMode('nocheck', function() {
184
+  console.log('success!');
185
+}, function() {
186
+  console.log('error :(');
187
+});
188
+```
189
+
190
+### setClientAuthMode<a name="setClientAuthMode"></a>
191
+Configure X.509 client certificate authentication. Takes mode and options. `mode` being one of following values:
192
+
193
+* `none`: disable client certificate authentication
194
+* `systemstore` (only on Android): use client certificate installed in the Android system store; user will be presented with a list of all installed certificates
195
+* `buffer`: use given client certificate; you will need to provide an options object:
196
+  * `rawPkcs`: ArrayBuffer containing raw PKCS12 container with client certificate and private key
197
+  * `pkcsPassword`: password of the PKCS container
198
+
199
+```js
200
+  // enable client auth using PKCS12 container given in ArrayBuffer `myPkcs12ArrayBuffer`
201
+  cordova.plugin.http.setClientAuthMode('buffer', {
202
+    rawPkcs: myPkcs12ArrayBuffer,
203
+    pkcsPassword: 'mySecretPassword'
204
+  }, success, fail);
205
+
206
+  // enable client auth using certificate in system store (only on Android)
207
+  cordova.plugin.http.setClientAuthMode('systemstore', {}, success, fail);
208
+
209
+  // disable client auth
210
+  cordova.plugin.http.setClientAuthMode('none', {}, success, fail);
211
+```
212
+
213
+### removeCookies
214
+Remove all cookies associated with a given URL.
215
+
216
+```js
217
+cordova.plugin.http.removeCookies(url, callback);
218
+```
219
+
220
+### sendRequest<a name="sendRequest"></a>
221
+Execute a HTTP request.  Takes a URL and an options object. This is the internally used implementation of the following shorthand functions ([post](#post), [get](#get), [put](#put), [patch](#patch), [delete](#delete), [head](#head), [uploadFile](#uploadFile) and [downloadFile](#downloadFile)). You can use this function, if you want to override global settings for each single request. Check the documentation of the respective shorthand function for details on what is returned on success and failure.
222
+
223
+:warning: You need to encode the base URL yourself if it contains special characters like whitespaces. You can use `encodeURI()` for this purpose.
224
+
225
+The options object contains following keys:
226
+
227
+* `method`: HTTP method to be used, defaults to `get`, needs to be one of the following values:
228
+  * `get`, `post`, `put`, `patch`, `head`, `delete`, `options`, `upload`, `download`
229
+* `data`: payload to be send to the server (only applicable on `post`, `put` or `patch` methods)
230
+* `params`: query params to be appended to the URL (only applicable on `get`, `head`, `delete`, `upload` or `download` methods)
231
+* `serializer`: data serializer to be used (only applicable on `post`, `put` or `patch` methods), defaults to global serializer value, see [setDataSerializer](#setDataSerializer) for supported values
232
+* `responseType`: expected response type, defaults to `text`, needs to be one of the following values:
233
+  * `text`: data is returned as decoded string, use this for all kinds of string responses (e.g. XML, HTML, plain text, etc.)
234
+  * `json` data is treated as JSON and returned as parsed object, returns `undefined` when response body is empty
235
+  * `arraybuffer`: data is returned as [ArrayBuffer instance](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), returns `null` when response body is empty
236
+  * `blob`: data is returned as [Blob instance](https://developer.mozilla.org/en-US/docs/Web/API/Blob), returns `null` when response body is empty
237
+* `timeout`: timeout value for the request in seconds, defaults to global timeout value
238
+* `followRedirect`: enable or disable automatically following redirects
239
+* `headers`: headers object (key value pair), will be merged with global values
240
+* `filePath`: file path(s) to be used during upload and download see [uploadFile](#uploadFile) and [downloadFile](#downloadFile) for detailed information
241
+* `name`: name(s) to be used during upload see [uploadFile](#uploadFile) for detailed information
242
+
243
+Here's a quick example:
244
+
245
+```js
246
+const options = {
247
+  method: 'post',
248
+  data: { id: 12, message: 'test' },
249
+  headers: { Authorization: 'OAuth2: token' }
250
+};
251
+
252
+cordova.plugin.http.sendRequest('https://google.com/', options, function(response) {
253
+  // prints 200
254
+  console.log(response.status);
255
+}, function(response) {
256
+  // prints 403
257
+  console.log(response.status);
258
+
259
+  //prints Permission denied
260
+  console.log(response.error);
261
+});
262
+```
263
+
264
+### post<a name="post"></a>
265
+Execute a POST request.  Takes a URL, data, and headers.
266
+
267
+```js
268
+cordova.plugin.http.post('https://google.com/', {
269
+  test: 'testString'
270
+}, {
271
+  Authorization: 'OAuth2: token'
272
+}, function(response) {
273
+  console.log(response.status);
274
+}, function(response) {
275
+  console.error(response.error);
276
+});
277
+```
278
+
279
+#### success
280
+The success function receives a response object with 4 properties: status, data, url, and headers.  **status** is the HTTP response code as numeric value. **data** is the response from the server as a string. **url** is the final URL obtained after any redirects as a string. **headers** is an object with the headers. The keys of the returned object are the header names and the values are the respective header values. All header names are lowercase.
281
+
282
+Here's a quick example:
283
+
284
+```js
285
+{
286
+  status: 200,
287
+  data: '{"id": 12, "message": "test"}',
288
+  url: 'http://example.net/rest'
289
+  headers: {
290
+    'content-length': '247'
291
+  }
292
+}
293
+```
294
+
295
+Most apis will return JSON meaning you'll want to parse the data like in the example below:
296
+
297
+```js
298
+cordova.plugin.http.post('https://google.com/', {
299
+  id: 12,
300
+  message: 'test'
301
+}, { Authorization: 'OAuth2: token' }, function(response) {
302
+  // prints 200
303
+  console.log(response.status);
304
+  try {
305
+    response.data = JSON.parse(response.data);
306
+    // prints test
307
+    console.log(response.data.message);
308
+  } catch(e) {
309
+    console.error('JSON parsing error');
310
+  }
311
+}, function(response) {
312
+  // prints 403
313
+  console.log(response.status);
314
+
315
+  //prints Permission denied
316
+  console.log(response.error);
317
+});
318
+```
319
+
320
+#### failure
321
+The error function receives a response object with 4 properties: status, error, url, and headers (url and headers being optional).  **status** is a HTTP response code or an internal error code. Positive values are HTTP status codes whereas negative values do represent internal error codes. **error** is the error response from the server as a string or an internal error message. **url** is the final URL obtained after any redirects as a string. **headers** is an object with the headers. The keys of the returned object are the header names and the values are the respective header values. All header names are lowercase.
322
+
323
+Here's a quick example:
324
+
325
+```js
326
+{
327
+  status: 403,
328
+  error: 'Permission denied',
329
+  url: 'http://example.net/noperm'
330
+  headers: {
331
+    'content-length': '247'
332
+  }
333
+}
334
+```
335
+
336
+:warning: An enumeration style object is exposed as `cordova.plugin.http.ErrorCode`. You can use it to check against internal error codes.
337
+
338
+### get<a name="get"></a>
339
+Execute a GET request.  Takes a URL, parameters, and headers.  See the [post](#post) documentation for details on what is returned on success and failure.
340
+
341
+```js
342
+cordova.plugin.http.get('https://google.com/', {
343
+  id: '12',
344
+  message: 'test'
345
+}, { Authorization: 'OAuth2: token' }, function(response) {
346
+  console.log(response.status);
347
+}, function(response) {
348
+  console.error(response.error);
349
+});
350
+```
351
+
352
+### put<a name="put"></a>
353
+Execute a PUT request.  Takes a URL, data, and headers.  See the [post](#post) documentation for details on what is returned on success and failure.
354
+
355
+### patch<a name="patch"></a>
356
+Execute a PATCH request.  Takes a URL, data, and headers.  See the [post](#post) documentation for details on what is returned on success and failure.
357
+
358
+### delete<a name="delete"></a>
359
+Execute a DELETE request.  Takes a URL, parameters, and headers.  See the [post](#post) documentation for details on what is returned on success and failure.
360
+
361
+### head<a name="head"></a>
362
+Execute a HEAD request.  Takes a URL, parameters, and headers.  See the [post](#post) documentation for details on what is returned on success and failure.
363
+
364
+### options<a name="options"></a>
365
+Execute a OPTIONS request.  Takes a URL, parameters, and headers.  See the [post](#post) documentation for details on what is returned on success and failure.
366
+
367
+### uploadFile<a name="uploadFile"></a>
368
+Uploads one or more file(s) saved on the device.  Takes a URL, parameters, headers, filePath(s), and the name(s) of the parameter to pass the file along as.  See the [post](#post) documentation for details on what is returned on success and failure.
369
+
370
+```js
371
+// e.g. for single file
372
+const filePath = 'file:///somepicture.jpg';
373
+const name = 'picture';
374
+
375
+// e.g. for multiple files
376
+const filePath = ['file:///somepicture.jpg', 'file:///somedocument.doc'];
377
+const name = ['picture', 'document'];
378
+
379
+cordova.plugin.http.uploadFile("https://google.com/", {
380
+    id: '12',
381
+    message: 'test'
382
+}, { Authorization: 'OAuth2: token' }, filePath, name, function(response) {
383
+    console.log(response.status);
384
+}, function(response) {
385
+    console.error(response.error);
386
+});
387
+```
388
+
389
+### downloadFile<a name="downloadFile"></a>
390
+Downloads a file and saves it to the device.  Takes a URL, parameters, headers, and a filePath.  See [post](#post) documentation for details on what is returned on failure.  On success this function returns a cordova [FileEntry object](http://cordova.apache.org/docs/en/3.3.0/cordova_file_file.md.html#FileEntry).
391
+
392
+```js
393
+cordova.plugin.http.downloadFile("https://google.com/", {
394
+  id: '12',
395
+  message: 'test'
396
+}, { Authorization: 'OAuth2: token' }, 'file:///somepicture.jpg', function(entry) {
397
+  // prints the filename
398
+  console.log(entry.name);
399
+
400
+  // prints the filePath
401
+  console.log(entry.fullPath);
402
+}, function(response) {
403
+  console.error(response.error);
404
+});
405
+```
406
+
407
+## Browser support<a name="browserSupport"></a>
408
+
409
+This plugin supports a very restricted set of functions on the browser platform.
410
+It's meant for testing purposes, not for production grade usage.
411
+
412
+Following features are *not* supported:
413
+
414
+* Manipulating Cookies
415
+* Uploading and Downloading files
416
+* Pinning SSL certificate
417
+* Disabling SSL certificate check
418
+* Disabling transparently following redirects (HTTP codes 3xx)
419
+* Circumventing CORS restrictions
420
+
421
+## Libraries
422
+
423
+This plugin utilizes some awesome open source libraries:
424
+
425
+ - iOS - [AFNetworking](https://github.com/AFNetworking/AFNetworking) (MIT licensed)
426
+ - Android - [http-request](https://github.com/kevinsawicki/http-request) (MIT licensed)
427
+ - Cookie handling - [tough-cookie](https://github.com/salesforce/tough-cookie) (BSD-3-Clause licensed)
428
+
429
+We made a few modifications to the networking libraries.
430
+
431
+## CI Builds & E2E Testing
432
+
433
+This plugin uses amazing cloud services to maintain quality. CI Builds and E2E testing are powered by:
434
+
435
+* [GitHub Actions](https://github.com/features/actions)
436
+* [Travis CI](https://travis-ci.org/)
437
+* [BrowserStack](https://www.browserstack.com/)
438
+* [Sauce Labs](https://saucelabs.com/)
439
+* [httpbin.org](https://httpbin.org/)
440
+
441
+## Contribute & Develop
442
+
443
+We've set up a separate document for our [contribution guidelines](CONTRIBUTING.md).

+ 115
- 0
node_modules/cordova-plugin-advanced-http/package.json Visa fil

@@ -0,0 +1,115 @@
1
+{
2
+  "_from": "cordova-plugin-advanced-http",
3
+  "_id": "cordova-plugin-advanced-http@3.0.1",
4
+  "_inBundle": false,
5
+  "_integrity": "sha512-7P3ZoSvxvYZXNYsygkxrUIw+pnzsCVvQgRsm26XhymNqqmD9yZIcF878p6wfFVQfLzf5iRHQRwgAMcrcm+cnow==",
6
+  "_location": "/cordova-plugin-advanced-http",
7
+  "_phantomChildren": {},
8
+  "_requested": {
9
+    "type": "tag",
10
+    "registry": true,
11
+    "raw": "cordova-plugin-advanced-http",
12
+    "name": "cordova-plugin-advanced-http",
13
+    "escapedName": "cordova-plugin-advanced-http",
14
+    "rawSpec": "",
15
+    "saveSpec": null,
16
+    "fetchSpec": "latest"
17
+  },
18
+  "_requiredBy": [
19
+    "#DEV:/",
20
+    "#USER"
21
+  ],
22
+  "_resolved": "https://registry.npmjs.org/cordova-plugin-advanced-http/-/cordova-plugin-advanced-http-3.0.1.tgz",
23
+  "_shasum": "13e3fb7c4185598b2a173051187c87cca13fd54c",
24
+  "_spec": "cordova-plugin-advanced-http",
25
+  "_where": "C:\\Users\\Chuch\\Documents\\Cordova\\artesanias",
26
+  "author": {
27
+    "name": "Wymsee"
28
+  },
29
+  "bugs": {
30
+    "url": "https://github.com/silkimen/cordova-plugin-advanced-http/issues"
31
+  },
32
+  "bundleDependencies": false,
33
+  "contributors": [
34
+    {
35
+      "name": "devgeeks"
36
+    },
37
+    {
38
+      "name": "EddyVerbruggen"
39
+    },
40
+    {
41
+      "name": "mbektchiev"
42
+    },
43
+    {
44
+      "name": "denisbabineau"
45
+    },
46
+    {
47
+      "name": "andrey-tsaplin"
48
+    },
49
+    {
50
+      "name": "pvsaikrishna"
51
+    },
52
+    {
53
+      "name": "cvillerm"
54
+    },
55
+    {
56
+      "name": "hideov"
57
+    },
58
+    {
59
+      "name": "silkimen"
60
+    }
61
+  ],
62
+  "cordova": {
63
+    "id": "cordova-plugin-advanced-http",
64
+    "platforms": [
65
+      "ios",
66
+      "android"
67
+    ]
68
+  },
69
+  "deprecated": false,
70
+  "description": "Cordova / Phonegap plugin for communicating with HTTP servers using SSL pinning",
71
+  "devDependencies": {
72
+    "chai": "4.2.0",
73
+    "colors": "1.4.0",
74
+    "cordova": "9.0.0",
75
+    "mocha": "8.0.1",
76
+    "umd-tough-cookie": "2.4.3",
77
+    "wd": "1.12.1",
78
+    "xml2js": "0.4.23"
79
+  },
80
+  "engines": [
81
+    {
82
+      "name": "cordova",
83
+      "version": ">=4.0.0"
84
+    }
85
+  ],
86
+  "homepage": "https://github.com/silkimen/cordova-plugin-advanced-http#readme",
87
+  "keywords": [
88
+    "cordova",
89
+    "device",
90
+    "ecosystem:cordova",
91
+    "cordova-ios",
92
+    "cordova-android",
93
+    "ssl",
94
+    "tls"
95
+  ],
96
+  "license": "MIT",
97
+  "name": "cordova-plugin-advanced-http",
98
+  "repository": {
99
+    "type": "git",
100
+    "url": "git+https://github.com/silkimen/cordova-plugin-advanced-http.git"
101
+  },
102
+  "scripts": {
103
+    "buildandroid": "./scripts/build-test-app.sh --android --emulator",
104
+    "buildbrowser": "./scripts/build-test-app.sh --browser",
105
+    "buildios": "./scripts/build-test-app.sh --ios --emulator",
106
+    "release": "npm run test && ./scripts/release.sh",
107
+    "test": "npm run testjs && npm run testapp",
108
+    "testandroid": "npm run updatecert && npm run buildandroid && ./scripts/test-app.sh --android --emulator",
109
+    "testapp": "npm run testandroid && npm run testios",
110
+    "testios": "npm run updatecert && npm run buildios && ./scripts/test-app.sh --ios --emulator",
111
+    "testjs": "mocha ./test/js-specs.js",
112
+    "updatecert": "node ./scripts/update-e2e-server-cert.js && node ./scripts/update-e2e-client-cert.js"
113
+  },
114
+  "version": "3.0.1"
115
+}

+ 95
- 0
node_modules/cordova-plugin-advanced-http/plugin.xml Visa fil

@@ -0,0 +1,95 @@
1
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2
+<plugin xmlns="http://www.phonegap.com/ns/plugins/1.0" xmlns:android="http://schemas.android.com/apk/res/android" id="cordova-plugin-advanced-http" version="3.0.1">
3
+  <name>Advanced HTTP plugin</name>
4
+  <description>
5
+        Cordova / Phonegap plugin for communicating with HTTP servers using SSL pinning
6
+	 </description>
7
+  <engines>
8
+    <engine name="cordova" version=">=4.0.0"/>
9
+  </engines>
10
+  <dependency id="cordova-plugin-file" version=">=2.0.0"/>
11
+  <js-module src="www/cookie-handler.js" name="cookie-handler"/>
12
+  <js-module src="www/dependency-validator.js" name="dependency-validator"/>
13
+  <js-module src="www/error-codes.js" name="error-codes"/>
14
+  <js-module src="www/global-configs.js" name="global-configs"/>
15
+  <js-module src="www/helpers.js" name="helpers"/>
16
+  <js-module src="www/js-util.js" name="js-util"/>
17
+  <js-module src="www/local-storage-store.js" name="local-storage-store"/>
18
+  <js-module src="www/lodash.js" name="lodash"/>
19
+  <js-module src="www/messages.js" name="messages"/>
20
+  <js-module src="www/ponyfills.js" name="ponyfills"/>
21
+  <js-module src="www/public-interface.js" name="public-interface"/>
22
+  <js-module src="www/umd-tough-cookie.js" name="tough-cookie"/>
23
+  <js-module src="www/url-util.js" name="url-util"/>
24
+  <js-module src="www/advanced-http.js" name="http">
25
+    <clobbers target="cordova.plugin.http"/>
26
+  </js-module>
27
+  <platform name="ios">
28
+    <config-file target="config.xml" parent="/*">
29
+      <feature name="CordovaHttpPlugin">
30
+        <param name="ios-package" value="CordovaHttpPlugin"/>
31
+      </feature>
32
+    </config-file>
33
+    <header-file src="src/ios/CordovaHttpPlugin.h"/>
34
+    <header-file src="src/ios/BinaryRequestSerializer.h"/>
35
+    <header-file src="src/ios/BinaryResponseSerializer.h"/>
36
+    <header-file src="src/ios/TextResponseSerializer.h"/>
37
+    <header-file src="src/ios/TextRequestSerializer.h"/>
38
+    <header-file src="src/ios/AFNetworking/AFHTTPSessionManager.h"/>
39
+    <header-file src="src/ios/AFNetworking/AFNetworking.h"/>
40
+    <header-file src="src/ios/AFNetworking/AFNetworkReachabilityManager.h"/>
41
+    <header-file src="src/ios/AFNetworking/AFSecurityPolicy.h"/>
42
+    <header-file src="src/ios/AFNetworking/AFURLRequestSerialization.h"/>
43
+    <header-file src="src/ios/AFNetworking/AFURLResponseSerialization.h"/>
44
+    <header-file src="src/ios/AFNetworking/AFURLSessionManager.h"/>
45
+    <header-file src="src/ios/SDNetworkActivityIndicator/SDNetworkActivityIndicator.h"/>
46
+    <source-file src="src/ios/CordovaHttpPlugin.m"/>
47
+    <source-file src="src/ios/BinaryRequestSerializer.m"/>
48
+    <source-file src="src/ios/BinaryResponseSerializer.m"/>
49
+    <source-file src="src/ios/TextResponseSerializer.m"/>
50
+    <source-file src="src/ios/TextRequestSerializer.m"/>
51
+    <source-file src="src/ios/AFNetworking/AFHTTPSessionManager.m"/>
52
+    <source-file src="src/ios/AFNetworking/AFNetworkReachabilityManager.m"/>
53
+    <source-file src="src/ios/AFNetworking/AFSecurityPolicy.m"/>
54
+    <source-file src="src/ios/AFNetworking/AFURLRequestSerialization.m"/>
55
+    <source-file src="src/ios/AFNetworking/AFURLResponseSerialization.m"/>
56
+    <source-file src="src/ios/AFNetworking/AFURLSessionManager.m"/>
57
+    <source-file src="src/ios/SDNetworkActivityIndicator/SDNetworkActivityIndicator.m"/>
58
+    <framework src="Security.framework"/>
59
+    <framework src="SystemConfiguration.framework"/>
60
+  </platform>
61
+  <platform name="android">
62
+    <config-file target="res/xml/config.xml" parent="/*">
63
+      <feature name="CordovaHttpPlugin">
64
+        <param name="android-package" value="com.silkimen.cordovahttp.CordovaHttpPlugin"/>
65
+      </feature>
66
+    </config-file>
67
+    <config-file target="AndroidManifest.xml" parent="/manifest">
68
+      <uses-permission android:name="android.permission.INTERNET"/>
69
+    </config-file>
70
+    <source-file src="src/android/com/silkimen/cordovahttp/CordovaClientAuth.java" target-dir="src/com/silkimen/cordovahttp"/>
71
+    <source-file src="src/android/com/silkimen/cordovahttp/CordovaHttpBase.java" target-dir="src/com/silkimen/cordovahttp"/>
72
+    <source-file src="src/android/com/silkimen/cordovahttp/CordovaHttpDownload.java" target-dir="src/com/silkimen/cordovahttp"/>
73
+    <source-file src="src/android/com/silkimen/cordovahttp/CordovaHttpOperation.java" target-dir="src/com/silkimen/cordovahttp"/>
74
+    <source-file src="src/android/com/silkimen/cordovahttp/CordovaHttpPlugin.java" target-dir="src/com/silkimen/cordovahttp"/>
75
+    <source-file src="src/android/com/silkimen/cordovahttp/CordovaHttpResponse.java" target-dir="src/com/silkimen/cordovahttp"/>
76
+    <source-file src="src/android/com/silkimen/cordovahttp/CordovaHttpUpload.java" target-dir="src/com/silkimen/cordovahttp"/>
77
+    <source-file src="src/android/com/silkimen/cordovahttp/CordovaServerTrust.java" target-dir="src/com/silkimen/cordovahttp"/>
78
+    <source-file src="src/android/com/silkimen/http/HttpBodyDecoder.java" target-dir="src/com/silkimen/http"/>
79
+    <source-file src="src/android/com/silkimen/http/HttpRequest.java" target-dir="src/com/silkimen/http"/>
80
+    <source-file src="src/android/com/silkimen/http/JsonUtils.java" target-dir="src/com/silkimen/http"/>
81
+    <source-file src="src/android/com/silkimen/http/KeyChainKeyManager.java" target-dir="src/com/silkimen/http"/>
82
+    <source-file src="src/android/com/silkimen/http/TLSConfiguration.java" target-dir="src/com/silkimen/http"/>
83
+    <source-file src="src/android/com/silkimen/http/TLSSocketFactory.java" target-dir="src/com/silkimen/http"/>
84
+  </platform>
85
+  <platform name="browser">
86
+    <config-file target="config.xml" parent="/*">
87
+      <feature name="CordovaHttpPlugin">
88
+        <param name="browser-package" value="CordovaHttpPlugin"/>
89
+      </feature>
90
+    </config-file>
91
+    <js-module src="src/browser/cordova-http-plugin.js" name="http-proxy">
92
+      <runs/>
93
+    </js-module>
94
+  </platform>
95
+</plugin>

+ 113
- 0
node_modules/cordova-plugin-advanced-http/src/android/com/silkimen/cordovahttp/CordovaClientAuth.java Visa fil

@@ -0,0 +1,113 @@
1
+package com.silkimen.cordovahttp;
2
+
3
+import android.app.Activity;
4
+import android.content.Context;
5
+import android.security.KeyChain;
6
+import android.security.KeyChainAliasCallback;
7
+import android.util.Log;
8
+
9
+import java.io.ByteArrayInputStream;
10
+import java.io.InputStream;
11
+import java.net.URI;
12
+import java.security.KeyStore;
13
+import java.security.PrivateKey;
14
+import java.security.cert.X509Certificate;
15
+
16
+import javax.net.ssl.KeyManager;
17
+import javax.net.ssl.KeyManagerFactory;
18
+
19
+import org.apache.cordova.CallbackContext;
20
+
21
+import com.silkimen.http.KeyChainKeyManager;
22
+import com.silkimen.http.TLSConfiguration;
23
+
24
+class CordovaClientAuth implements Runnable, KeyChainAliasCallback {
25
+  private static final String TAG = "Cordova-Plugin-HTTP";
26
+
27
+  private String mode;
28
+  private String aliasString;
29
+  private byte[] rawPkcs;
30
+  private String pkcsPassword;
31
+  private Activity activity;
32
+  private Context context;
33
+  private TLSConfiguration tlsConfiguration;
34
+  private CallbackContext callbackContext;
35
+
36
+  public CordovaClientAuth(final String mode, final String aliasString, final byte[] rawPkcs,
37
+      final String pkcsPassword, final Activity activity, final Context context, final TLSConfiguration configContainer,
38
+      final CallbackContext callbackContext) {
39
+
40
+    this.mode = mode;
41
+    this.aliasString = aliasString;
42
+    this.rawPkcs = rawPkcs;
43
+    this.pkcsPassword = pkcsPassword;
44
+    this.activity = activity;
45
+    this.tlsConfiguration = configContainer;
46
+    this.context = context;
47
+    this.callbackContext = callbackContext;
48
+  }
49
+
50
+  @Override
51
+  public void run() {
52
+    if ("systemstore".equals(this.mode)) {
53
+      this.loadFromSystemStore();
54
+    } else if ("buffer".equals(this.mode)) {
55
+      this.loadFromBuffer();
56
+    } else {
57
+      this.disableClientAuth();
58
+    }
59
+  }
60
+
61
+  private void loadFromSystemStore() {
62
+    if (this.aliasString == null) {
63
+      KeyChain.choosePrivateKeyAlias(this.activity, this, null, null, null, -1, null);
64
+    } else {
65
+      this.alias(this.aliasString);
66
+    }
67
+  }
68
+
69
+  private void loadFromBuffer() {
70
+    try {
71
+      KeyStore keyStore = KeyStore.getInstance("PKCS12");
72
+      String keyManagerFactoryAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
73
+      KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(keyManagerFactoryAlgorithm);
74
+      ByteArrayInputStream stream = new ByteArrayInputStream(this.rawPkcs);
75
+
76
+      keyStore.load(stream, this.pkcsPassword.toCharArray());
77
+      keyManagerFactory.init(keyStore, this.pkcsPassword.toCharArray());
78
+
79
+      this.tlsConfiguration.setKeyManagers(keyManagerFactory.getKeyManagers());
80
+      this.callbackContext.success();
81
+    } catch (Exception e) {
82
+      Log.e(TAG, "Couldn't load given PKCS12 container for authentication", e);
83
+      this.callbackContext.error("Couldn't load given PKCS12 container for authentication");
84
+    }
85
+  }
86
+
87
+  private void disableClientAuth() {
88
+    this.tlsConfiguration.setKeyManagers(null);
89
+    this.callbackContext.success();
90
+  }
91
+
92
+  @Override
93
+  public void alias(final String alias) {
94
+    try {
95
+      if (alias == null) {
96
+        throw new Exception("Couldn't get a consent for private key access");
97
+      }
98
+
99
+      PrivateKey key = KeyChain.getPrivateKey(this.context, alias);
100
+      X509Certificate[] chain = KeyChain.getCertificateChain(this.context, alias);
101
+      KeyManager keyManager = new KeyChainKeyManager(alias, key, chain);
102
+
103
+      this.tlsConfiguration.setKeyManagers(new KeyManager[] { keyManager });
104
+
105
+      this.callbackContext.success(alias);
106
+    } catch (Exception e) {
107
+      Log.e(TAG, "Couldn't load private key and certificate pair with given alias \"" + alias + "\" for authentication",
108
+          e);
109
+      this.callbackContext.error(
110
+          "Couldn't load private key and certificate pair with given alias \"" + alias + "\" for authentication");
111
+    }
112
+  }
113
+}

+ 205
- 0
node_modules/cordova-plugin-advanced-http/src/android/com/silkimen/cordovahttp/CordovaHttpBase.java Visa fil

@@ -0,0 +1,205 @@
1
+package com.silkimen.cordovahttp;
2
+
3
+import java.io.ByteArrayInputStream;
4
+import java.io.ByteArrayOutputStream;
5
+import java.io.InputStream;
6
+import java.io.IOException;
7
+
8
+import java.net.SocketTimeoutException;
9
+import java.net.UnknownHostException;
10
+
11
+import java.nio.ByteBuffer;
12
+
13
+import javax.net.ssl.SSLException;
14
+
15
+import com.silkimen.http.HttpBodyDecoder;
16
+import com.silkimen.http.HttpRequest;
17
+import com.silkimen.http.HttpRequest.HttpRequestException;
18
+import com.silkimen.http.JsonUtils;
19
+import com.silkimen.http.TLSConfiguration;
20
+
21
+import org.apache.cordova.CallbackContext;
22
+
23
+import org.json.JSONArray;
24
+import org.json.JSONException;
25
+import org.json.JSONObject;
26
+
27
+import android.util.Base64;
28
+import android.util.Log;
29
+
30
+abstract class CordovaHttpBase implements Runnable {
31
+  protected static final String TAG = "Cordova-Plugin-HTTP";
32
+
33
+  protected String method;
34
+  protected String url;
35
+  protected String serializer = "none";
36
+  protected String responseType;
37
+  protected Object data;
38
+  protected JSONObject headers;
39
+  protected int timeout;
40
+  protected boolean followRedirects;
41
+  protected TLSConfiguration tlsConfiguration;
42
+  protected CallbackContext callbackContext;
43
+
44
+  public CordovaHttpBase(String method, String url, String serializer, Object data, JSONObject headers, int timeout,
45
+      boolean followRedirects, String responseType, TLSConfiguration tlsConfiguration,
46
+      CallbackContext callbackContext) {
47
+
48
+    this.method = method;
49
+    this.url = url;
50
+    this.serializer = serializer;
51
+    this.data = data;
52
+    this.headers = headers;
53
+    this.timeout = timeout;
54
+    this.followRedirects = followRedirects;
55
+    this.responseType = responseType;
56
+    this.tlsConfiguration = tlsConfiguration;
57
+    this.callbackContext = callbackContext;
58
+  }
59
+
60
+  public CordovaHttpBase(String method, String url, JSONObject headers, int timeout, boolean followRedirects,
61
+      String responseType, TLSConfiguration tlsConfiguration, CallbackContext callbackContext) {
62
+
63
+    this.method = method;
64
+    this.url = url;
65
+    this.headers = headers;
66
+    this.timeout = timeout;
67
+    this.followRedirects = followRedirects;
68
+    this.responseType = responseType;
69
+    this.tlsConfiguration = tlsConfiguration;
70
+    this.callbackContext = callbackContext;
71
+  }
72
+
73
+  @Override
74
+  public void run() {
75
+    CordovaHttpResponse response = new CordovaHttpResponse();
76
+
77
+    try {
78
+      HttpRequest request = this.createRequest();
79
+      this.prepareRequest(request);
80
+      this.sendBody(request);
81
+      this.processResponse(request, response);
82
+      request.disconnect();
83
+    } catch (HttpRequestException e) {
84
+      if (e.getCause() instanceof SSLException) {
85
+        response.setStatus(-2);
86
+        response.setErrorMessage("TLS connection could not be established: " + e.getMessage());
87
+        Log.w(TAG, "TLS connection could not be established", e);
88
+      } else if (e.getCause() instanceof UnknownHostException) {
89
+        response.setStatus(-3);
90
+        response.setErrorMessage("Host could not be resolved: " + e.getMessage());
91
+        Log.w(TAG, "Host could not be resolved", e);
92
+      } else if (e.getCause() instanceof SocketTimeoutException) {
93
+        response.setStatus(-4);
94
+        response.setErrorMessage("Request timed out: " + e.getMessage());
95
+        Log.w(TAG, "Request timed out", e);
96
+      } else {
97
+        response.setStatus(-1);
98
+        response.setErrorMessage("There was an error with the request: " + e.getCause().getMessage());
99
+        Log.w(TAG, "Generic request error", e);
100
+      }
101
+    } catch (Exception e) {
102
+      response.setStatus(-1);
103
+      response.setErrorMessage(e.getMessage());
104
+      Log.e(TAG, "An unexpected error occured", e);
105
+    }
106
+
107
+    try {
108
+      if (response.hasFailed()) {
109
+        this.callbackContext.error(response.toJSON());
110
+      } else {
111
+        this.callbackContext.success(response.toJSON());
112
+      }
113
+    } catch (JSONException e) {
114
+      Log.e(TAG, "An unexpected error occured while creating HTTP response object", e);
115
+    }
116
+  }
117
+
118
+  protected HttpRequest createRequest() throws JSONException {
119
+    return new HttpRequest(this.url, this.method);
120
+  }
121
+
122
+  protected void prepareRequest(HttpRequest request) throws JSONException, IOException {
123
+    request.followRedirects(this.followRedirects);
124
+    request.readTimeout(this.timeout);
125
+    request.acceptCharset("UTF-8");
126
+    request.uncompress(true);
127
+
128
+    if (this.tlsConfiguration.getHostnameVerifier() != null) {
129
+      request.setHostnameVerifier(this.tlsConfiguration.getHostnameVerifier());
130
+    }
131
+
132
+    request.setSSLSocketFactory(this.tlsConfiguration.getTLSSocketFactory());
133
+
134
+    // setup content type before applying headers, so user can override it
135
+    this.setContentType(request);
136
+
137
+    request.headers(JsonUtils.getStringMap(this.headers));
138
+  }
139
+
140
+  protected void setContentType(HttpRequest request) {
141
+    if ("json".equals(this.serializer)) {
142
+      request.contentType("application/json", "UTF-8");
143
+    } else if ("utf8".equals(this.serializer)) {
144
+      request.contentType("text/plain", "UTF-8");
145
+    } else if ("raw".equals(this.serializer)) {
146
+      request.contentType("application/octet-stream");
147
+    } else if ("urlencoded".equals(this.serializer)) {
148
+      // intentionally left blank, because content type is set in HttpRequest.form()
149
+    } else if ("multipart".equals(this.serializer)) {
150
+      request.contentType("multipart/form-data");
151
+    }
152
+  }
153
+
154
+  protected void sendBody(HttpRequest request) throws Exception {
155
+    if (this.data == null) {
156
+      return;
157
+    }
158
+
159
+    if ("json".equals(this.serializer)) {
160
+      request.send(this.data.toString());
161
+    } else if ("utf8".equals(this.serializer)) {
162
+      request.send(((JSONObject) this.data).getString("text"));
163
+    } else if ("raw".equals(this.serializer)) {
164
+      request.send(Base64.decode((String)this.data, Base64.DEFAULT));
165
+    } else if ("urlencoded".equals(this.serializer)) {
166
+      request.form(JsonUtils.getObjectMap((JSONObject) this.data));
167
+    } else if ("multipart".equals(this.serializer)) {
168
+      JSONArray buffers = ((JSONObject) this.data).getJSONArray("buffers");
169
+      JSONArray names = ((JSONObject) this.data).getJSONArray("names");
170
+      JSONArray fileNames = ((JSONObject) this.data).getJSONArray("fileNames");
171
+      JSONArray types = ((JSONObject) this.data).getJSONArray("types");
172
+
173
+      for (int i = 0; i < buffers.length(); ++i) {
174
+        byte[] bytes = Base64.decode(buffers.getString(i), Base64.DEFAULT);
175
+        String name = names.getString(i);
176
+
177
+        if (fileNames.isNull(i)) {
178
+          request.part(name, new String(bytes, "UTF-8"));
179
+        } else {
180
+          request.part(name, fileNames.getString(i), types.getString(i), new ByteArrayInputStream(bytes));
181
+        }
182
+      }
183
+    }
184
+  }
185
+
186
+  protected void processResponse(HttpRequest request, CordovaHttpResponse response) throws Exception {
187
+    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
188
+    request.receive(outputStream);
189
+
190
+    response.setStatus(request.code());
191
+    response.setUrl(request.url().toString());
192
+    response.setHeaders(request.headers());
193
+
194
+    if (request.code() >= 200 && request.code() < 300) {
195
+      if ("text".equals(this.responseType) || "json".equals(this.responseType)) {
196
+        String decoded = HttpBodyDecoder.decodeBody(outputStream.toByteArray(), request.charset());
197
+        response.setBody(decoded);
198
+      } else {
199
+        response.setData(outputStream.toByteArray());
200
+      }
201
+    } else {
202
+      response.setErrorMessage(HttpBodyDecoder.decodeBody(outputStream.toByteArray(), request.charset()));
203
+    }
204
+  }
205
+}

+ 42
- 0
node_modules/cordova-plugin-advanced-http/src/android/com/silkimen/cordovahttp/CordovaHttpDownload.java Visa fil

@@ -0,0 +1,42 @@
1
+package com.silkimen.cordovahttp;
2
+
3
+import java.io.File;
4
+import java.net.URI;
5
+
6
+import javax.net.ssl.HostnameVerifier;
7
+import javax.net.ssl.SSLSocketFactory;
8
+
9
+import com.silkimen.http.HttpRequest;
10
+import com.silkimen.http.TLSConfiguration;
11
+
12
+import org.apache.cordova.CallbackContext;
13
+import org.apache.cordova.file.FileUtils;
14
+import org.json.JSONObject;
15
+
16
+class CordovaHttpDownload extends CordovaHttpBase {
17
+  private String filePath;
18
+
19
+  public CordovaHttpDownload(String url, JSONObject headers, String filePath, int timeout, boolean followRedirects,
20
+      TLSConfiguration tlsConfiguration, CallbackContext callbackContext) {
21
+
22
+    super("GET", url, headers, timeout, followRedirects, "text", tlsConfiguration, callbackContext);
23
+    this.filePath = filePath;
24
+  }
25
+
26
+  @Override
27
+  protected void processResponse(HttpRequest request, CordovaHttpResponse response) throws Exception {
28
+    response.setStatus(request.code());
29
+    response.setUrl(request.url().toString());
30
+    response.setHeaders(request.headers());
31
+
32
+    if (request.code() >= 200 && request.code() < 300) {
33
+      File file = new File(new URI(this.filePath));
34
+      JSONObject fileEntry = FileUtils.getFilePlugin().getEntryForFile(file);
35
+
36
+      request.receive(file);
37
+      response.setFileEntry(fileEntry);
38
+    } else {
39
+      response.setErrorMessage("There was an error downloading the file");
40
+    }
41
+  }
42
+}

+ 25
- 0
node_modules/cordova-plugin-advanced-http/src/android/com/silkimen/cordovahttp/CordovaHttpOperation.java Visa fil

@@ -0,0 +1,25 @@
1
+package com.silkimen.cordovahttp;
2
+
3
+import javax.net.ssl.HostnameVerifier;
4
+import javax.net.ssl.SSLSocketFactory;
5
+
6
+import com.silkimen.http.TLSConfiguration;
7
+
8
+import org.apache.cordova.CallbackContext;
9
+import org.json.JSONObject;
10
+
11
+class CordovaHttpOperation extends CordovaHttpBase {
12
+  public CordovaHttpOperation(String method, String url, String serializer, Object data, JSONObject headers,
13
+      int timeout, boolean followRedirects, String responseType, TLSConfiguration tlsConfiguration,
14
+      CallbackContext callbackContext) {
15
+
16
+    super(method, url, serializer, data, headers, timeout, followRedirects, responseType, tlsConfiguration,
17
+        callbackContext);
18
+  }
19
+
20
+  public CordovaHttpOperation(String method, String url, JSONObject headers, int timeout, boolean followRedirects,
21
+      String responseType, TLSConfiguration tlsConfiguration, CallbackContext callbackContext) {
22
+
23
+    super(method, url, headers, timeout, followRedirects, responseType, tlsConfiguration, callbackContext);
24
+  }
25
+}

+ 169
- 0
node_modules/cordova-plugin-advanced-http/src/android/com/silkimen/cordovahttp/CordovaHttpPlugin.java Visa fil

@@ -0,0 +1,169 @@
1
+package com.silkimen.cordovahttp;
2
+
3
+import java.security.KeyStore;
4
+
5
+import com.silkimen.http.TLSConfiguration;
6
+
7
+import org.apache.cordova.CallbackContext;
8
+import org.apache.cordova.CordovaInterface;
9
+import org.apache.cordova.CordovaPlugin;
10
+import org.apache.cordova.CordovaWebView;
11
+import org.json.JSONArray;
12
+import org.json.JSONException;
13
+import org.json.JSONObject;
14
+
15
+import android.util.Log;
16
+import android.util.Base64;
17
+
18
+import javax.net.ssl.TrustManagerFactory;
19
+
20
+public class CordovaHttpPlugin extends CordovaPlugin {
21
+  private static final String TAG = "Cordova-Plugin-HTTP";
22
+
23
+  private TLSConfiguration tlsConfiguration;
24
+
25
+  @Override
26
+  public void initialize(CordovaInterface cordova, CordovaWebView webView) {
27
+    super.initialize(cordova, webView);
28
+
29
+    this.tlsConfiguration = new TLSConfiguration();
30
+
31
+    try {
32
+      KeyStore store = KeyStore.getInstance("AndroidCAStore");
33
+      String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
34
+      TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
35
+
36
+      store.load(null);
37
+      tmf.init(store);
38
+
39
+      this.tlsConfiguration.setHostnameVerifier(null);
40
+      this.tlsConfiguration.setTrustManagers(tmf.getTrustManagers());
41
+    } catch (Exception e) {
42
+      Log.e(TAG, "An error occured while loading system's CA certificates", e);
43
+    }
44
+  }
45
+
46
+  @Override
47
+  public boolean execute(String action, final JSONArray args, final CallbackContext callbackContext)
48
+      throws JSONException {
49
+
50
+    if (action == null) {
51
+      return false;
52
+    }
53
+
54
+    if ("get".equals(action)) {
55
+      return this.executeHttpRequestWithoutData(action, args, callbackContext);
56
+    } else if ("head".equals(action)) {
57
+      return this.executeHttpRequestWithoutData(action, args, callbackContext);
58
+    } else if ("delete".equals(action)) {
59
+      return this.executeHttpRequestWithoutData(action, args, callbackContext);
60
+    } else if ("options".equals(action)) {
61
+      return this.executeHttpRequestWithoutData(action, args, callbackContext);
62
+    } else if ("post".equals(action)) {
63
+      return this.executeHttpRequestWithData(action, args, callbackContext);
64
+    } else if ("put".equals(action)) {
65
+      return this.executeHttpRequestWithData(action, args, callbackContext);
66
+    } else if ("patch".equals(action)) {
67
+      return this.executeHttpRequestWithData(action, args, callbackContext);
68
+    } else if ("uploadFiles".equals(action)) {
69
+      return this.uploadFiles(args, callbackContext);
70
+    } else if ("downloadFile".equals(action)) {
71
+      return this.downloadFile(args, callbackContext);
72
+    } else if ("setServerTrustMode".equals(action)) {
73
+      return this.setServerTrustMode(args, callbackContext);
74
+    } else if ("setClientAuthMode".equals(action)) {
75
+      return this.setClientAuthMode(args, callbackContext);
76
+    } else {
77
+      return false;
78
+    }
79
+  }
80
+
81
+  private boolean executeHttpRequestWithoutData(final String method, final JSONArray args,
82
+      final CallbackContext callbackContext) throws JSONException {
83
+
84
+    String url = args.getString(0);
85
+    JSONObject headers = args.getJSONObject(1);
86
+    int timeout = args.getInt(2) * 1000;
87
+    boolean followRedirect = args.getBoolean(3);
88
+    String responseType = args.getString(4);
89
+
90
+    CordovaHttpOperation request = new CordovaHttpOperation(method.toUpperCase(), url, headers, timeout, followRedirect,
91
+        responseType, this.tlsConfiguration, callbackContext);
92
+
93
+    cordova.getThreadPool().execute(request);
94
+
95
+    return true;
96
+  }
97
+
98
+  private boolean executeHttpRequestWithData(final String method, final JSONArray args,
99
+      final CallbackContext callbackContext) throws JSONException {
100
+
101
+    String url = args.getString(0);
102
+    Object data = args.get(1);
103
+    String serializer = args.getString(2);
104
+    JSONObject headers = args.getJSONObject(3);
105
+    int timeout = args.getInt(4) * 1000;
106
+    boolean followRedirect = args.getBoolean(5);
107
+    String responseType = args.getString(6);
108
+
109
+    CordovaHttpOperation request = new CordovaHttpOperation(method.toUpperCase(), url, serializer, data, headers,
110
+        timeout, followRedirect, responseType, this.tlsConfiguration, callbackContext);
111
+
112
+    cordova.getThreadPool().execute(request);
113
+
114
+    return true;
115
+  }
116
+
117
+  private boolean uploadFiles(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
118
+    String url = args.getString(0);
119
+    JSONObject headers = args.getJSONObject(1);
120
+    JSONArray filePaths = args.getJSONArray(2);
121
+    JSONArray uploadNames = args.getJSONArray(3);
122
+    int timeout = args.getInt(4) * 1000;
123
+    boolean followRedirect = args.getBoolean(5);
124
+    String responseType = args.getString(6);
125
+
126
+    CordovaHttpUpload upload = new CordovaHttpUpload(url, headers, filePaths, uploadNames, timeout, followRedirect,
127
+        responseType, this.tlsConfiguration, this.cordova.getActivity().getApplicationContext(), callbackContext);
128
+
129
+    cordova.getThreadPool().execute(upload);
130
+
131
+    return true;
132
+  }
133
+
134
+  private boolean downloadFile(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
135
+    String url = args.getString(0);
136
+    JSONObject headers = args.getJSONObject(1);
137
+    String filePath = args.getString(2);
138
+    int timeout = args.getInt(3) * 1000;
139
+    boolean followRedirect = args.getBoolean(4);
140
+
141
+    CordovaHttpDownload download = new CordovaHttpDownload(url, headers, filePath, timeout, followRedirect,
142
+        this.tlsConfiguration, callbackContext);
143
+
144
+    cordova.getThreadPool().execute(download);
145
+
146
+    return true;
147
+  }
148
+
149
+  private boolean setServerTrustMode(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
150
+    CordovaServerTrust runnable = new CordovaServerTrust(args.getString(0), this.cordova.getActivity(),
151
+        this.tlsConfiguration, callbackContext);
152
+
153
+    cordova.getThreadPool().execute(runnable);
154
+
155
+    return true;
156
+  }
157
+
158
+  private boolean setClientAuthMode(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
159
+    byte[] pkcs = args.isNull(2) ? null : Base64.decode(args.getString(2), Base64.DEFAULT);
160
+
161
+    CordovaClientAuth runnable = new CordovaClientAuth(args.getString(0), args.isNull(1) ? null : args.getString(1),
162
+        pkcs, args.getString(3), this.cordova.getActivity(), this.cordova.getActivity().getApplicationContext(),
163
+        this.tlsConfiguration, callbackContext);
164
+
165
+    cordova.getThreadPool().execute(runnable);
166
+
167
+    return true;
168
+  }
169
+}

+ 100
- 0
node_modules/cordova-plugin-advanced-http/src/android/com/silkimen/cordovahttp/CordovaHttpResponse.java Visa fil

@@ -0,0 +1,100 @@
1
+package com.silkimen.cordovahttp;
2
+
3
+import java.nio.ByteBuffer;
4
+
5
+import java.util.HashMap;
6
+import java.util.List;
7
+import java.util.Map;
8
+
9
+import org.json.JSONException;
10
+import org.json.JSONObject;
11
+
12
+import android.text.TextUtils;
13
+import android.util.Log;
14
+import android.util.Base64;
15
+
16
+class CordovaHttpResponse {
17
+  private int status;
18
+  private String url;
19
+  private Map<String, List<String>> headers;
20
+  private String body;
21
+  private byte[] rawData;
22
+  private JSONObject fileEntry;
23
+  private boolean hasFailed;
24
+  private boolean isFileOperation;
25
+  private boolean isRawResponse;
26
+  private String error;
27
+
28
+  public void setStatus(int status) {
29
+    this.status = status;
30
+  }
31
+
32
+  public void setUrl(String url) {
33
+    this.url = url;
34
+  }
35
+
36
+  public void setHeaders(Map<String, List<String>> headers) {
37
+    this.headers = headers;
38
+  }
39
+
40
+  public void setBody(String body) {
41
+    this.body = body;
42
+  }
43
+
44
+  public void setData(byte[] rawData) {
45
+    this.isRawResponse = true;
46
+    this.rawData = rawData;
47
+  }
48
+
49
+  public void setFileEntry(JSONObject entry) {
50
+    this.isFileOperation = true;
51
+    this.fileEntry = entry;
52
+  }
53
+
54
+  public void setErrorMessage(String message) {
55
+    this.hasFailed = true;
56
+    this.error = message;
57
+  }
58
+
59
+  public boolean hasFailed() {
60
+    return this.hasFailed;
61
+  }
62
+
63
+  public JSONObject toJSON() throws JSONException {
64
+    JSONObject json = new JSONObject();
65
+
66
+    json.put("status", this.status);
67
+    json.put("url", this.url);
68
+
69
+    if (this.headers != null && !this.headers.isEmpty()) {
70
+      json.put("headers", new JSONObject(getFilteredHeaders()));
71
+    }
72
+
73
+    if (this.hasFailed) {
74
+      json.put("error", this.error);
75
+    } else if (this.isFileOperation) {
76
+      json.put("file", this.fileEntry);
77
+    } else if (this.isRawResponse) {
78
+      json.put("data", Base64.encodeToString(this.rawData, Base64.DEFAULT));
79
+    } else {
80
+      json.put("data", this.body);
81
+    }
82
+
83
+    return json;
84
+  }
85
+
86
+  private Map<String, String> getFilteredHeaders() throws JSONException {
87
+    Map<String, String> filteredHeaders = new HashMap<String, String>();
88
+
89
+    for (Map.Entry<String, List<String>> entry : this.headers.entrySet()) {
90
+      String key = entry.getKey();
91
+      List<String> value = entry.getValue();
92
+
93
+      if ((key != null) && (!value.isEmpty())) {
94
+        filteredHeaders.put(key.toLowerCase(), TextUtils.join(", ", value));
95
+      }
96
+    }
97
+
98
+    return filteredHeaders;
99
+  }
100
+}

+ 92
- 0
node_modules/cordova-plugin-advanced-http/src/android/com/silkimen/cordovahttp/CordovaHttpUpload.java Visa fil

@@ -0,0 +1,92 @@
1
+package com.silkimen.cordovahttp;
2
+
3
+import android.content.ContentResolver;
4
+import android.content.Context;
5
+import android.database.Cursor;
6
+import android.net.Uri;
7
+import android.provider.OpenableColumns;
8
+import android.webkit.MimeTypeMap;
9
+
10
+import com.silkimen.http.HttpRequest;
11
+import com.silkimen.http.TLSConfiguration;
12
+
13
+import java.io.File;
14
+import java.io.InputStream;
15
+import java.net.URI;
16
+
17
+import javax.net.ssl.HostnameVerifier;
18
+import javax.net.ssl.SSLSocketFactory;
19
+
20
+import org.apache.cordova.CallbackContext;
21
+import org.json.JSONArray;
22
+import org.json.JSONObject;
23
+
24
+class CordovaHttpUpload extends CordovaHttpBase {
25
+  private JSONArray filePaths;
26
+  private JSONArray uploadNames;
27
+  private Context applicationContext;
28
+
29
+  public CordovaHttpUpload(String url, JSONObject headers, JSONArray filePaths, JSONArray uploadNames, int timeout,
30
+      boolean followRedirects, String responseType, TLSConfiguration tlsConfiguration,
31
+      Context applicationContext, CallbackContext callbackContext) {
32
+
33
+    super("POST", url, headers, timeout, followRedirects, responseType, tlsConfiguration, callbackContext);
34
+    this.filePaths = filePaths;
35
+    this.uploadNames = uploadNames;
36
+    this.applicationContext = applicationContext;
37
+  }
38
+
39
+  @Override
40
+  protected void sendBody(HttpRequest request) throws Exception {
41
+    for (int i = 0; i < this.filePaths.length(); ++i) {
42
+      String uploadName = this.uploadNames.getString(i);
43
+      String filePath = this.filePaths.getString(i);
44
+
45
+      Uri fileUri = Uri.parse(filePath);
46
+
47
+      // File Scheme
48
+      if (ContentResolver.SCHEME_FILE.equals(fileUri.getScheme())) {
49
+        File file = new File(new URI(filePath));
50
+        String fileName = file.getName().trim();
51
+        String mimeType = this.getMimeTypeFromFileName(fileName);
52
+
53
+        request.part(uploadName, fileName, mimeType, file);
54
+      }
55
+
56
+      // Content Scheme
57
+      if (ContentResolver.SCHEME_CONTENT.equals(fileUri.getScheme())) {
58
+        InputStream inputStream = this.applicationContext.getContentResolver().openInputStream(fileUri);
59
+        String fileName = this.getFileNameFromContentScheme(fileUri, this.applicationContext).trim();
60
+        String mimeType = this.getMimeTypeFromFileName(fileName);
61
+
62
+        request.part(uploadName, fileName, mimeType, inputStream);
63
+      }
64
+    }
65
+  }
66
+
67
+  private String getFileNameFromContentScheme(Uri contentSchemeUri, Context applicationContext) {
68
+    Cursor returnCursor = applicationContext.getContentResolver().query(contentSchemeUri, null, null, null, null);
69
+
70
+    if (returnCursor == null || !returnCursor.moveToFirst()) {
71
+      return null;
72
+    }
73
+
74
+    int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
75
+    String fileName = returnCursor.getString(nameIndex);
76
+    returnCursor.close();
77
+
78
+    return fileName;
79
+  }
80
+
81
+  private String getMimeTypeFromFileName(String fileName) {
82
+    if (fileName == null || !fileName.contains(".")) {
83
+      return null;
84
+    }
85
+
86
+    MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
87
+    int extIndex = fileName.lastIndexOf('.') + 1;
88
+    String extension = fileName.substring(extIndex).toLowerCase();
89
+
90
+    return mimeTypeMap.getMimeTypeFromExtension(extension);
91
+  }
92
+}

+ 124
- 0
node_modules/cordova-plugin-advanced-http/src/android/com/silkimen/cordovahttp/CordovaServerTrust.java Visa fil

@@ -0,0 +1,124 @@
1
+package com.silkimen.cordovahttp;
2
+
3
+import java.io.IOException;
4
+import java.security.GeneralSecurityException;
5
+import java.security.KeyStore;
6
+import java.security.cert.CertificateFactory;
7
+import java.security.cert.X509Certificate;
8
+
9
+import com.silkimen.http.TLSConfiguration;
10
+
11
+import org.apache.cordova.CallbackContext;
12
+
13
+import android.app.Activity;
14
+import android.util.Log;
15
+import android.content.res.AssetManager;
16
+
17
+import javax.net.ssl.HostnameVerifier;
18
+import javax.net.ssl.SSLSession;
19
+import javax.net.ssl.TrustManager;
20
+import javax.net.ssl.TrustManagerFactory;
21
+import javax.net.ssl.X509TrustManager;
22
+
23
+class CordovaServerTrust implements Runnable {
24
+  private static final String TAG = "Cordova-Plugin-HTTP";
25
+
26
+  private final TrustManager[] noOpTrustManagers;
27
+  private final HostnameVerifier noOpVerifier;
28
+
29
+  private String mode;
30
+  private Activity activity;
31
+  private TLSConfiguration tlsConfiguration;
32
+  private CallbackContext callbackContext;
33
+
34
+  public CordovaServerTrust(final String mode, final Activity activity, final TLSConfiguration configContainer,
35
+      final CallbackContext callbackContext) {
36
+
37
+    this.mode = mode;
38
+    this.activity = activity;
39
+    this.tlsConfiguration = configContainer;
40
+    this.callbackContext = callbackContext;
41
+
42
+    this.noOpTrustManagers = new TrustManager[] { new X509TrustManager() {
43
+      public X509Certificate[] getAcceptedIssuers() {
44
+        return new X509Certificate[0];
45
+      }
46
+
47
+      public void checkClientTrusted(X509Certificate[] chain, String authType) {
48
+        // intentionally left blank
49
+      }
50
+
51
+      public void checkServerTrusted(X509Certificate[] chain, String authType) {
52
+        // intentionally left blank
53
+      }
54
+    } };
55
+
56
+    this.noOpVerifier = new HostnameVerifier() {
57
+      public boolean verify(String hostname, SSLSession session) {
58
+        return true;
59
+      }
60
+    };
61
+  }
62
+
63
+  @Override
64
+  public void run() {
65
+    try {
66
+      if ("legacy".equals(this.mode)) {
67
+        this.tlsConfiguration.setHostnameVerifier(null);
68
+        this.tlsConfiguration.setTrustManagers(null);
69
+      } else if ("nocheck".equals(this.mode)) {
70
+        this.tlsConfiguration.setHostnameVerifier(this.noOpVerifier);
71
+        this.tlsConfiguration.setTrustManagers(this.noOpTrustManagers);
72
+      } else if ("pinned".equals(this.mode)) {
73
+        this.tlsConfiguration.setHostnameVerifier(null);
74
+        this.tlsConfiguration.setTrustManagers(this.getTrustManagers(this.getCertsFromBundle("www/certificates")));
75
+      } else {
76
+        this.tlsConfiguration.setHostnameVerifier(null);
77
+        this.tlsConfiguration.setTrustManagers(this.getTrustManagers(this.getCertsFromKeyStore("AndroidCAStore")));
78
+      }
79
+
80
+      callbackContext.success();
81
+    } catch (Exception e) {
82
+      Log.e(TAG, "An error occured while configuring SSL cert mode", e);
83
+      callbackContext.error("An error occured while configuring SSL cert mode");
84
+    }
85
+  }
86
+
87
+  private TrustManager[] getTrustManagers(KeyStore store) throws GeneralSecurityException {
88
+    String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
89
+    TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
90
+    tmf.init(store);
91
+
92
+    return tmf.getTrustManagers();
93
+  }
94
+
95
+  private KeyStore getCertsFromBundle(String path) throws GeneralSecurityException, IOException {
96
+    AssetManager assetManager = this.activity.getAssets();
97
+    String[] files = assetManager.list(path);
98
+
99
+    CertificateFactory cf = CertificateFactory.getInstance("X.509");
100
+    String keyStoreType = KeyStore.getDefaultType();
101
+    KeyStore keyStore = KeyStore.getInstance(keyStoreType);
102
+
103
+    keyStore.load(null, null);
104
+
105
+    for (int i = 0; i < files.length; i++) {
106
+      int index = files[i].lastIndexOf('.');
107
+
108
+      if (index == -1 || !files[i].substring(index).equals(".cer")) {
109
+        continue;
110
+      }
111
+
112
+      keyStore.setCertificateEntry("CA" + i, cf.generateCertificate(assetManager.open(path + "/" + files[i])));
113
+    }
114
+
115
+    return keyStore;
116
+  }
117
+
118
+  private KeyStore getCertsFromKeyStore(String storeType) throws GeneralSecurityException, IOException {
119
+    KeyStore store = KeyStore.getInstance(storeType);
120
+    store.load(null);
121
+
122
+    return store;
123
+  }
124
+}

+ 55
- 0
node_modules/cordova-plugin-advanced-http/src/android/com/silkimen/http/HttpBodyDecoder.java Visa fil

@@ -0,0 +1,55 @@
1
+package com.silkimen.http;
2
+
3
+import java.nio.ByteBuffer;
4
+import java.nio.charset.CharacterCodingException;
5
+import java.nio.charset.Charset;
6
+import java.nio.charset.CharsetDecoder;
7
+import java.nio.charset.CodingErrorAction;
8
+import java.nio.charset.MalformedInputException;
9
+
10
+public class HttpBodyDecoder {
11
+  private static final String[] ACCEPTED_CHARSETS = new String[] { "UTF-8", "ISO-8859-1" };
12
+
13
+  public static String decodeBody(byte[] body, String charsetName)
14
+      throws CharacterCodingException, MalformedInputException {
15
+
16
+    return decodeBody(ByteBuffer.wrap(body), charsetName);
17
+  }
18
+
19
+  public static String decodeBody(ByteBuffer body, String charsetName)
20
+      throws CharacterCodingException, MalformedInputException {
21
+
22
+    if (charsetName == null) {
23
+      return tryDecodeByteBuffer(body);
24
+    } else {
25
+      return decodeByteBuffer(body, charsetName);
26
+    }
27
+  }
28
+
29
+  private static String tryDecodeByteBuffer(ByteBuffer buffer)
30
+      throws CharacterCodingException, MalformedInputException {
31
+
32
+    for (int i = 0; i < ACCEPTED_CHARSETS.length - 1; i++) {
33
+      try {
34
+        return decodeByteBuffer(buffer, ACCEPTED_CHARSETS[i]);
35
+      } catch (MalformedInputException e) {
36
+        continue;
37
+      } catch (CharacterCodingException e) {
38
+        continue;
39
+      }
40
+    }
41
+
42
+    return decodeBody(buffer, ACCEPTED_CHARSETS[ACCEPTED_CHARSETS.length - 1]);
43
+  }
44
+
45
+  private static String decodeByteBuffer(ByteBuffer buffer, String charsetName)
46
+      throws CharacterCodingException, MalformedInputException {
47
+
48
+    return createCharsetDecoder(charsetName).decode(buffer).toString();
49
+  }
50
+
51
+  private static CharsetDecoder createCharsetDecoder(String charsetName) {
52
+    return Charset.forName(charsetName).newDecoder().onMalformedInput(CodingErrorAction.REPORT)
53
+        .onUnmappableCharacter(CodingErrorAction.REPORT);
54
+  }
55
+}

+ 3095
- 0
node_modules/cordova-plugin-advanced-http/src/android/com/silkimen/http/HttpRequest.java
Filskillnaden har hållits tillbaka eftersom den är för stor
Visa fil


+ 58
- 0
node_modules/cordova-plugin-advanced-http/src/android/com/silkimen/http/JsonUtils.java Visa fil

@@ -0,0 +1,58 @@
1
+package com.silkimen.http;
2
+
3
+import java.util.ArrayList;
4
+import java.util.HashMap;
5
+import java.util.Iterator;
6
+
7
+import org.json.JSONArray;
8
+import org.json.JSONException;
9
+import org.json.JSONObject;
10
+
11
+public class JsonUtils {
12
+  public static HashMap<String, String> getStringMap(JSONObject object) throws JSONException {
13
+    HashMap<String, String> map = new HashMap<String, String>();
14
+
15
+    if (object == null) {
16
+      return map;
17
+    }
18
+
19
+    Iterator<?> i = object.keys();
20
+
21
+    while (i.hasNext()) {
22
+      String key = (String) i.next();
23
+      map.put(key, object.getString(key));
24
+    }
25
+    return map;
26
+  }
27
+
28
+  public static HashMap<String, Object> getObjectMap(JSONObject object) throws JSONException {
29
+    HashMap<String, Object> map = new HashMap<String, Object>();
30
+
31
+    if (object == null) {
32
+      return map;
33
+    }
34
+
35
+    Iterator<?> i = object.keys();
36
+
37
+    while (i.hasNext()) {
38
+      String key = (String) i.next();
39
+      Object value = object.get(key);
40
+
41
+      if (value instanceof JSONArray) {
42
+        map.put(key, getObjectList((JSONArray) value));
43
+      } else {
44
+        map.put(key, object.get(key));
45
+      }
46
+    }
47
+    return map;
48
+  }
49
+
50
+  public static ArrayList<Object> getObjectList(JSONArray array) throws JSONException {
51
+    ArrayList<Object> list = new ArrayList<Object>();
52
+
53
+    for (int i = 0; i < array.length(); i++) {
54
+      list.add(array.get(i));
55
+    }
56
+    return list;
57
+  }
58
+}

+ 57
- 0
node_modules/cordova-plugin-advanced-http/src/android/com/silkimen/http/KeyChainKeyManager.java Visa fil

@@ -0,0 +1,57 @@
1
+package com.silkimen.http;
2
+
3
+import android.content.Context;
4
+import android.security.KeyChain;
5
+
6
+import java.net.Socket;
7
+import java.security.Principal;
8
+import java.security.PrivateKey;
9
+import java.security.cert.CertificateException;
10
+import java.security.cert.X509Certificate;
11
+
12
+import javax.net.ssl.X509ExtendedKeyManager;
13
+
14
+public class KeyChainKeyManager extends X509ExtendedKeyManager {
15
+  private final String alias;
16
+  private final X509Certificate[] chain;
17
+  private final PrivateKey key;
18
+
19
+  public KeyChainKeyManager(String alias, PrivateKey key, X509Certificate[] chain) {
20
+    this.alias = alias;
21
+    this.key = key;
22
+    this.chain = chain;
23
+  }
24
+
25
+  @Override
26
+  public String chooseClientAlias(String[] keyTypes, Principal[] issuers, Socket socket) {
27
+    return this.alias;
28
+  }
29
+
30
+  @Override
31
+  public X509Certificate[] getCertificateChain(String alias) {
32
+    return chain;
33
+  }
34
+
35
+  @Override
36
+  public PrivateKey getPrivateKey(String alias) {
37
+    return key;
38
+  }
39
+
40
+  @Override
41
+  public final String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) {
42
+    // not a client SSLSocket callback
43
+    throw new UnsupportedOperationException();
44
+  }
45
+
46
+  @Override
47
+  public final String[] getClientAliases(String keyType, Principal[] issuers) {
48
+    // not a client SSLSocket callback
49
+    throw new UnsupportedOperationException();
50
+  }
51
+
52
+  @Override
53
+  public final String[] getServerAliases(String keyType, Principal[] issuers) {
54
+    // not a client SSLSocket callback
55
+    throw new UnsupportedOperationException();
56
+  }
57
+}

+ 63
- 0
node_modules/cordova-plugin-advanced-http/src/android/com/silkimen/http/TLSConfiguration.java Visa fil

@@ -0,0 +1,63 @@
1
+package com.silkimen.http;
2
+
3
+import java.io.IOException;
4
+import java.security.GeneralSecurityException;
5
+import java.security.SecureRandom;
6
+
7
+import javax.net.ssl.HostnameVerifier;
8
+import javax.net.ssl.KeyManager;
9
+import javax.net.ssl.SSLContext;
10
+import javax.net.ssl.SSLSocketFactory;
11
+import javax.net.ssl.TrustManager;
12
+
13
+import com.silkimen.http.TLSSocketFactory;
14
+
15
+public class TLSConfiguration {
16
+  private TrustManager[] trustManagers;
17
+  private KeyManager[] keyManagers;
18
+  private HostnameVerifier hostnameVerifier;
19
+
20
+  private SSLSocketFactory socketFactory;
21
+
22
+  public void setHostnameVerifier(HostnameVerifier hostnameVerifier) {
23
+    this.hostnameVerifier = hostnameVerifier;
24
+  }
25
+
26
+  public void setKeyManagers(KeyManager[] keyManagers) {
27
+    this.keyManagers = keyManagers;
28
+    this.socketFactory = null;
29
+  }
30
+
31
+  public void setTrustManagers(TrustManager[] trustManagers) {
32
+    this.trustManagers = trustManagers;
33
+    this.socketFactory = null;
34
+  }
35
+
36
+  public HostnameVerifier getHostnameVerifier() {
37
+    return this.hostnameVerifier;
38
+  }
39
+
40
+  public SSLSocketFactory getTLSSocketFactory() throws IOException {
41
+    if (this.socketFactory != null) {
42
+      return this.socketFactory;
43
+    }
44
+
45
+    try {
46
+      SSLContext context = SSLContext.getInstance("TLS");
47
+
48
+      context.init(this.keyManagers, this.trustManagers, new SecureRandom());
49
+
50
+      if (android.os.Build.VERSION.SDK_INT < 20) {
51
+        this.socketFactory = new TLSSocketFactory(context);
52
+      } else {
53
+        this.socketFactory = context.getSocketFactory();
54
+      }
55
+
56
+      return this.socketFactory;
57
+    } catch (GeneralSecurityException e) {
58
+      IOException ioException = new IOException("Security exception occured while configuring TLS context");
59
+      ioException.initCause(e);
60
+      throw ioException;
61
+    }
62
+  }
63
+}

+ 63
- 0
node_modules/cordova-plugin-advanced-http/src/android/com/silkimen/http/TLSSocketFactory.java Visa fil

@@ -0,0 +1,63 @@
1
+package com.silkimen.http;
2
+
3
+import java.io.IOException;
4
+import java.net.InetAddress;
5
+import java.net.Socket;
6
+import java.net.UnknownHostException;
7
+
8
+import javax.net.ssl.SSLContext;
9
+import javax.net.ssl.SSLSocket;
10
+import javax.net.ssl.SSLSocketFactory;
11
+
12
+public class TLSSocketFactory extends SSLSocketFactory {
13
+
14
+  private SSLSocketFactory delegate;
15
+
16
+  public TLSSocketFactory(SSLContext context) {
17
+    delegate = context.getSocketFactory();
18
+  }
19
+
20
+  @Override
21
+  public String[] getDefaultCipherSuites() {
22
+    return delegate.getDefaultCipherSuites();
23
+  }
24
+
25
+  @Override
26
+  public String[] getSupportedCipherSuites() {
27
+    return delegate.getSupportedCipherSuites();
28
+  }
29
+
30
+  @Override
31
+  public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException {
32
+    return enableTLSOnSocket(delegate.createSocket(socket, host, port, autoClose));
33
+  }
34
+
35
+  @Override
36
+  public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
37
+    return enableTLSOnSocket(delegate.createSocket(host, port));
38
+  }
39
+
40
+  @Override
41
+  public Socket createSocket(String host, int port, InetAddress localHost, int localPort)
42
+      throws IOException, UnknownHostException {
43
+    return enableTLSOnSocket(delegate.createSocket(host, port, localHost, localPort));
44
+  }
45
+
46
+  @Override
47
+  public Socket createSocket(InetAddress host, int port) throws IOException {
48
+    return enableTLSOnSocket(delegate.createSocket(host, port));
49
+  }
50
+
51
+  @Override
52
+  public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort)
53
+      throws IOException {
54
+    return enableTLSOnSocket(delegate.createSocket(address, port, localAddress, localPort));
55
+  }
56
+
57
+  private Socket enableTLSOnSocket(Socket socket) {
58
+    if (socket != null && (socket instanceof SSLSocket)) {
59
+      ((SSLSocket) socket).setEnabledProtocols(new String[] { "TLSv1", "TLSv1.1", "TLSv1.2" });
60
+    }
61
+    return socket;
62
+  }
63
+}

+ 283
- 0
node_modules/cordova-plugin-advanced-http/src/browser/cordova-http-plugin.js Visa fil

@@ -0,0 +1,283 @@
1
+var pluginId = module.id.slice(0, module.id.lastIndexOf('.'));
2
+
3
+var cordovaProxy = require('cordova/exec/proxy');
4
+var jsUtil = require(pluginId + '.js-util');
5
+
6
+function serializeJsonData(data) {
7
+  try {
8
+    return JSON.stringify(data);
9
+  } catch (err) {
10
+    return null;
11
+  }
12
+}
13
+
14
+function serializePrimitive(key, value) {
15
+  if (value === null || value === undefined) {
16
+    return encodeURIComponent(key) + '=';
17
+  }
18
+
19
+  return encodeURIComponent(key) + '=' + encodeURIComponent(value);
20
+}
21
+
22
+function serializeArray(key, values) {
23
+  return values.map(function (value) {
24
+    return encodeURIComponent(key) + '[]=' + encodeURIComponent(value);
25
+  }).join('&');
26
+}
27
+
28
+function serializeParams(params) {
29
+  if (params === null) return '';
30
+
31
+  return Object.keys(params).map(function (key) {
32
+    if (jsUtil.getTypeOf(params[key]) === 'Array') {
33
+      return serializeArray(key, params[key]);
34
+    }
35
+
36
+    return serializePrimitive(key, params[key]);
37
+  }).join('&');
38
+}
39
+
40
+function decodeB64(dataString) {
41
+  var binaryString = atob(dataString);
42
+  var bytes = new Uint8Array(binaryString.length);
43
+
44
+  for (var i = 0; i < binaryString.length; ++i) {
45
+    bytes[i] = binaryString.charCodeAt(i);
46
+  }
47
+
48
+  return bytes.buffer;
49
+}
50
+
51
+function processMultipartData(data) {
52
+  if (!data) return null;
53
+
54
+  var fd = new FormData();
55
+
56
+  for (var i = 0; i < data.buffers.length; ++i) {
57
+    var buffer = data.buffers[i];
58
+    var name = data.names[i];
59
+    var fileName = data.fileNames[i];
60
+    var type = data.types[i];
61
+
62
+    if (fileName) {
63
+      fd.append(name, new Blob([decodeB64(buffer)], { type: type }), fileName);
64
+    } else {
65
+      // we assume it's plain text if no filename was given
66
+      fd.append(name, atob(buffer));
67
+    }
68
+  }
69
+
70
+  return fd;
71
+}
72
+
73
+function deserializeResponseHeaders(headers) {
74
+  var headerMap = {};
75
+  var arr = headers.trim().split(/[\r\n]+/);
76
+
77
+  arr.forEach(function (line) {
78
+    var parts = line.split(': ');
79
+    var header = parts.shift().toLowerCase();
80
+    var value = parts.join(': ');
81
+
82
+    headerMap[header] = value;
83
+  });
84
+
85
+  return headerMap;
86
+}
87
+
88
+function getResponseData(xhr) {
89
+  if (xhr.responseType !== 'text' || jsUtil.getTypeOf(xhr.responseText) !== 'String') {
90
+    return xhr.response;
91
+  }
92
+
93
+  return xhr.responseText;
94
+}
95
+
96
+function createXhrSuccessObject(xhr) {
97
+  return {
98
+    url: xhr.responseURL,
99
+    status: xhr.status,
100
+    data: getResponseData(xhr),
101
+    headers: deserializeResponseHeaders(xhr.getAllResponseHeaders())
102
+  };
103
+}
104
+
105
+function createXhrFailureObject(xhr) {
106
+  var obj = {};
107
+
108
+  obj.headers = xhr.getAllResponseHeaders();
109
+  obj.error = getResponseData(xhr);
110
+  obj.error = obj.error || 'advanced-http: please check browser console for error messages';
111
+
112
+  if (xhr.responseURL) obj.url = xhr.responseURL;
113
+  if (xhr.status) obj.status = xhr.status;
114
+
115
+  return obj;
116
+}
117
+
118
+function getHeaderValue(headers, headerName) {
119
+  let result = null;
120
+
121
+  Object.keys(headers).forEach(function (key) {
122
+    if (key.toLowerCase() === headerName.toLowerCase()) {
123
+      result = headers[key];
124
+    }
125
+  });
126
+
127
+  return result;
128
+}
129
+
130
+function setDefaultContentType(headers, contentType) {
131
+  if (getHeaderValue(headers, 'Content-Type') === null) {
132
+    headers['Content-Type'] = contentType;
133
+  }
134
+}
135
+
136
+function setHeaders(xhr, headers) {
137
+  Object.keys(headers).forEach(function (key) {
138
+    if (key.toLowerCase() === 'cookie') return;
139
+
140
+    xhr.setRequestHeader(key, headers[key]);
141
+  });
142
+}
143
+
144
+function sendRequest(method, withData, opts, success, failure) {
145
+  var data, serializer, headers, timeout, followRedirect, responseType;
146
+  var url = opts[0];
147
+
148
+  if (withData) {
149
+    data = opts[1];
150
+    serializer = opts[2];
151
+    headers = opts[3];
152
+    timeout = opts[4];
153
+    followRedirect = opts[5];
154
+    responseType = opts[6];
155
+  } else {
156
+    headers = opts[1];
157
+    timeout = opts[2];
158
+    followRedirect = opts[3];
159
+    responseType = opts[4];
160
+
161
+  }
162
+
163
+  var processedData = null;
164
+  var xhr = new XMLHttpRequest();
165
+
166
+  xhr.open(method, url);
167
+
168
+  if (headers.Cookie && headers.Cookie.length > 0) {
169
+    return failure('advanced-http: custom cookies not supported on browser platform');
170
+  }
171
+
172
+  if (!followRedirect) {
173
+    return failure('advanced-http: disabling follow redirect not supported on browser platform');
174
+  }
175
+
176
+  switch (serializer) {
177
+    case 'json':
178
+      setDefaultContentType(headers, 'application/json; charset=utf8');
179
+      processedData = serializeJsonData(data);
180
+
181
+      if (processedData === null) {
182
+        return failure('advanced-http: failed serializing data');
183
+      }
184
+
185
+      break;
186
+
187
+    case 'utf8':
188
+      setDefaultContentType(headers, 'text/plain; charset=utf8');
189
+      processedData = data.text;
190
+      break;
191
+
192
+    case 'urlencoded':
193
+      setDefaultContentType(headers, 'application/x-www-form-urlencoded');
194
+      processedData = serializeParams(data);
195
+      break;
196
+
197
+    case 'multipart':
198
+      const contentType = getHeaderValue(headers, 'Content-Type');
199
+
200
+      // intentionally don't set a default content type
201
+      // it's set by the browser together with the content disposition string
202
+      if (contentType) {
203
+        headers['Content-Type'] = contentType;
204
+      }
205
+
206
+      processedData = processMultipartData(data);
207
+      break;
208
+
209
+    case 'raw':
210
+      setDefaultContentType(headers, 'application/octet-stream');
211
+      processedData = data;
212
+      break;
213
+  }
214
+
215
+  // requesting text instead of JSON because it's parsed in the response handler
216
+  xhr.responseType = responseType === 'json' ? 'text' : responseType;
217
+  xhr.timeout = timeout * 1000;
218
+  setHeaders(xhr, headers);
219
+
220
+  xhr.onerror = function () {
221
+    return failure(createXhrFailureObject(xhr));
222
+  };
223
+
224
+  xhr.ontimeout = function () {
225
+    return failure({
226
+      status: -4,
227
+      error: 'Request timed out',
228
+      url: url,
229
+      headers: {}
230
+    });
231
+  };
232
+
233
+  xhr.onload = function () {
234
+    if (xhr.readyState !== xhr.DONE) return;
235
+
236
+    if (xhr.status < 200 || xhr.status > 299) {
237
+      return failure(createXhrFailureObject(xhr));
238
+    }
239
+
240
+    return success(createXhrSuccessObject(xhr));
241
+  };
242
+
243
+  xhr.send(processedData);
244
+}
245
+
246
+var browserInterface = {
247
+  get: function (success, failure, opts) {
248
+    return sendRequest('get', false, opts, success, failure);
249
+  },
250
+  head: function (success, failure, opts) {
251
+    return sendRequest('head', false, opts, success, failure);
252
+  },
253
+  delete: function (success, failure, opts) {
254
+    return sendRequest('delete', false, opts, success, failure);
255
+  },
256
+  post: function (success, failure, opts) {
257
+    return sendRequest('post', true, opts, success, failure);
258
+  },
259
+  put: function (success, failure, opts) {
260
+    return sendRequest('put', true, opts, success, failure);
261
+  },
262
+  patch: function (success, failure, opts) {
263
+    return sendRequest('patch', true, opts, success, failure);
264
+  },
265
+  uploadFile: function (success, failure, opts) {
266
+    return failure('advanced-http: function "uploadFile" not supported on browser platform');
267
+  },
268
+  uploadFiles: function (success, failure, opts) {
269
+    return failure('advanced-http: function "uploadFiles" not supported on browser platform');
270
+  },
271
+  downloadFile: function (success, failure, opts) {
272
+    return failure('advanced-http: function "downloadFile" not supported on browser platform');
273
+  },
274
+  setServerTrustMode: function (success, failure, opts) {
275
+    return failure('advanced-http: function "setServerTrustMode" not supported on browser platform');
276
+  },
277
+  setClientAuthMode: function (success, failure, opts) {
278
+    return failure('advanced-http: function "setClientAuthMode" not supported on browser platform');
279
+  }
280
+};
281
+
282
+module.exports = browserInterface;
283
+cordovaProxy.add('CordovaHttpPlugin', browserInterface);

+ 353
- 0
node_modules/cordova-plugin-advanced-http/src/ios/AFNetworking/AFHTTPSessionManager.h Visa fil

@@ -0,0 +1,353 @@
1
+// AFHTTPSessionManager.h
2
+// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3
+//
4
+// Permission is hereby granted, free of charge, to any person obtaining a copy
5
+// of this software and associated documentation files (the "Software"), to deal
6
+// in the Software without restriction, including without limitation the rights
7
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+// copies of the Software, and to permit persons to whom the Software is
9
+// furnished to do so, subject to the following conditions:
10
+//
11
+// The above copyright notice and this permission notice shall be included in
12
+// all copies or substantial portions of the Software.
13
+//
14
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20
+// THE SOFTWARE.
21
+
22
+#import <Foundation/Foundation.h>
23
+#if !TARGET_OS_WATCH
24
+#import <SystemConfiguration/SystemConfiguration.h>
25
+#endif
26
+#import <TargetConditionals.h>
27
+
28
+#if TARGET_OS_IOS || TARGET_OS_WATCH || TARGET_OS_TV
29
+#import <MobileCoreServices/MobileCoreServices.h>
30
+#else
31
+#import <CoreServices/CoreServices.h>
32
+#endif
33
+
34
+#import "AFURLSessionManager.h"
35
+
36
+/**
37
+ `AFHTTPSessionManager` is a subclass of `AFURLSessionManager` with convenience methods for making HTTP requests. When a `baseURL` is provided, requests made with the `GET` / `POST` / et al. convenience methods can be made with relative paths.
38
+
39
+ ## Subclassing Notes
40
+
41
+ Developers targeting iOS 7 or Mac OS X 10.9 or later that deal extensively with a web service are encouraged to subclass `AFHTTPSessionManager`, providing a class method that returns a shared singleton object on which authentication and other configuration can be shared across the application.
42
+
43
+ For developers targeting iOS 6 or Mac OS X 10.8 or earlier, `AFHTTPRequestOperationManager` may be used to similar effect.
44
+
45
+ ## Methods to Override
46
+
47
+ To change the behavior of all data task operation construction, which is also used in the `GET` / `POST` / et al. convenience methods, override `dataTaskWithRequest:completionHandler:`.
48
+
49
+ ## Serialization
50
+
51
+ Requests created by an HTTP client will contain default headers and encode parameters according to the `requestSerializer` property, which is an object conforming to `<AFURLRequestSerialization>`.
52
+
53
+ Responses received from the server are automatically validated and serialized by the `responseSerializers` property, which is an object conforming to `<AFURLResponseSerialization>`
54
+
55
+ ## URL Construction Using Relative Paths
56
+
57
+ For HTTP convenience methods, the request serializer constructs URLs from the path relative to the `-baseURL`, using `NSURL +URLWithString:relativeToURL:`, when provided. If `baseURL` is `nil`, `path` needs to resolve to a valid `NSURL` object using `NSURL +URLWithString:`.
58
+
59
+ Below are a few examples of how `baseURL` and relative paths interact:
60
+
61
+    NSURL *baseURL = [NSURL URLWithString:@"http://example.com/v1/"];
62
+    [NSURL URLWithString:@"foo" relativeToURL:baseURL];                  // http://example.com/v1/foo
63
+    [NSURL URLWithString:@"foo?bar=baz" relativeToURL:baseURL];          // http://example.com/v1/foo?bar=baz
64
+    [NSURL URLWithString:@"/foo" relativeToURL:baseURL];                 // http://example.com/foo
65
+    [NSURL URLWithString:@"foo/" relativeToURL:baseURL];                 // http://example.com/v1/foo
66
+    [NSURL URLWithString:@"/foo/" relativeToURL:baseURL];                // http://example.com/foo/
67
+    [NSURL URLWithString:@"http://example2.com/" relativeToURL:baseURL]; // http://example2.com/
68
+
69
+ Also important to note is that a trailing slash will be added to any `baseURL` without one. This would otherwise cause unexpected behavior when constructing URLs using paths without a leading slash.
70
+
71
+ @warning Managers for background sessions must be owned for the duration of their use. This can be accomplished by creating an application-wide or shared singleton instance.
72
+ */
73
+
74
+NS_ASSUME_NONNULL_BEGIN
75
+
76
+@interface AFHTTPSessionManager : AFURLSessionManager <NSSecureCoding, NSCopying>
77
+
78
+/**
79
+ The URL used to construct requests from relative paths in methods like `requestWithMethod:URLString:parameters:`, and the `GET` / `POST` / et al. convenience methods.
80
+ */
81
+@property (readonly, nonatomic, strong, nullable) NSURL *baseURL;
82
+
83
+/**
84
+ Requests created with `requestWithMethod:URLString:parameters:` & `multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:` are constructed with a set of default headers using a parameter serialization specified by this property. By default, this is set to an instance of `AFHTTPRequestSerializer`, which serializes query string parameters for `GET`, `HEAD`, and `DELETE` requests, or otherwise URL-form-encodes HTTP message bodies.
85
+
86
+ @warning `requestSerializer` must not be `nil`.
87
+ */
88
+@property (nonatomic, strong) AFHTTPRequestSerializer <AFURLRequestSerialization> * requestSerializer;
89
+
90
+/**
91
+ Responses sent from the server in data tasks created with `dataTaskWithRequest:success:failure:` and run using the `GET` / `POST` / et al. convenience methods are automatically validated and serialized by the response serializer. By default, this property is set to an instance of `AFJSONResponseSerializer`.
92
+
93
+ @warning `responseSerializer` must not be `nil`.
94
+ */
95
+@property (nonatomic, strong) AFHTTPResponseSerializer <AFURLResponseSerialization> * responseSerializer;
96
+
97
+///---------------------
98
+/// @name Initialization
99
+///---------------------
100
+
101
+/**
102
+ Creates and returns an `AFHTTPSessionManager` object.
103
+ */
104
++ (instancetype)manager;
105
+
106
+/**
107
+ Initializes an `AFHTTPSessionManager` object with the specified base URL.
108
+
109
+ @param url The base URL for the HTTP client.
110
+
111
+ @return The newly-initialized HTTP client
112
+ */
113
+- (instancetype)initWithBaseURL:(nullable NSURL *)url;
114
+
115
+/**
116
+ Initializes an `AFHTTPSessionManager` object with the specified base URL.
117
+
118
+ This is the designated initializer.
119
+
120
+ @param url The base URL for the HTTP client.
121
+ @param configuration The configuration used to create the managed session.
122
+
123
+ @return The newly-initialized HTTP client
124
+ */
125
+- (instancetype)initWithBaseURL:(nullable NSURL *)url
126
+           sessionConfiguration:(nullable NSURLSessionConfiguration *)configuration NS_DESIGNATED_INITIALIZER;
127
+
128
+///---------------------------
129
+/// @name Making HTTP Requests
130
+///---------------------------
131
+
132
+/**
133
+ Creates and runs an `NSURLSessionDataTask` with a `GET` request.
134
+
135
+ @param URLString The URL string used to create the request URL.
136
+ @param parameters The parameters to be encoded according to the client request serializer.
137
+ @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.
138
+ @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.
139
+
140
+ @see -dataTaskWithRequest:completionHandler:
141
+ */
142
+- (nullable NSURLSessionDataTask *)GET:(NSString *)URLString
143
+                   parameters:(nullable id)parameters
144
+                      success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
145
+                      failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure DEPRECATED_ATTRIBUTE;
146
+
147
+
148
+/**
149
+ Creates and runs an `NSURLSessionDataTask` with a `GET` request.
150
+
151
+ @param URLString The URL string used to create the request URL.
152
+ @param parameters The parameters to be encoded according to the client request serializer.
153
+ @param downloadProgress A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue.
154
+ @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.
155
+ @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.
156
+
157
+ @see -dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler:
158
+ */
159
+- (nullable NSURLSessionDataTask *)GET:(NSString *)URLString
160
+                            parameters:(nullable id)parameters
161
+                              progress:(nullable void (^)(NSProgress *downloadProgress))downloadProgress
162
+                               success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
163
+                               failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure;
164
+
165
+/**
166
+ Creates and runs an `NSURLSessionDataTask` with a `HEAD` request.
167
+
168
+ @param URLString The URL string used to create the request URL.
169
+ @param parameters The parameters to be encoded according to the client request serializer.
170
+ @param success A block object to be executed when the task finishes successfully. This block has no return value and takes a single arguments: the data task.
171
+ @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.
172
+
173
+ @see -dataTaskWithRequest:completionHandler:
174
+ */
175
+- (nullable NSURLSessionDataTask *)HEAD:(NSString *)URLString
176
+                    parameters:(nullable id)parameters
177
+                       success:(nullable void (^)(NSURLSessionDataTask *task))success
178
+                       failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure;
179
+
180
+/**
181
+ Creates and runs an `NSURLSessionDataTask` with a `POST` request.
182
+
183
+ @param URLString The URL string used to create the request URL.
184
+ @param parameters The parameters to be encoded according to the client request serializer.
185
+ @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.
186
+ @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.
187
+
188
+ @see -dataTaskWithRequest:completionHandler:
189
+ */
190
+- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString
191
+                    parameters:(nullable id)parameters
192
+                       success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
193
+                       failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure DEPRECATED_ATTRIBUTE;
194
+
195
+/**
196
+ Creates and runs an `NSURLSessionDataTask` with a `POST` request.
197
+
198
+ @param URLString The URL string used to create the request URL.
199
+ @param parameters The parameters to be encoded according to the client request serializer.
200
+ @param uploadProgress A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue.
201
+ @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.
202
+ @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.
203
+
204
+ @see -dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler:
205
+ */
206
+- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString
207
+                             parameters:(nullable id)parameters
208
+                               progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgress
209
+                                success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
210
+                                failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure;
211
+
212
+/**
213
+ Creates and runs an `NSURLSessionDataTask` with a multipart `POST` request.
214
+
215
+ @param URLString The URL string used to create the request URL.
216
+ @param parameters The parameters to be encoded according to the client request serializer.
217
+ @param block A block that takes a single argument and appends data to the HTTP body. The block argument is an object adopting the `AFMultipartFormData` protocol.
218
+ @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.
219
+ @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.
220
+
221
+ @see -dataTaskWithRequest:completionHandler:
222
+ */
223
+- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString
224
+                    parameters:(nullable id)parameters
225
+     constructingBodyWithBlock:(nullable void (^)(id <AFMultipartFormData> formData))block
226
+                       success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
227
+                       failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure DEPRECATED_ATTRIBUTE;
228
+
229
+/**
230
+ Creates and runs an `NSURLSessionDataTask` with a multipart `POST` request.
231
+
232
+ @param URLString The URL string used to create the request URL.
233
+ @param parameters The parameters to be encoded according to the client request serializer.
234
+ @param block A block that takes a single argument and appends data to the HTTP body. The block argument is an object adopting the `AFMultipartFormData` protocol.
235
+ @param uploadProgress A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue.
236
+ @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.
237
+ @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.
238
+
239
+ @see -dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler:
240
+ */
241
+- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString
242
+                             parameters:(nullable id)parameters
243
+              constructingBodyWithBlock:(nullable void (^)(id <AFMultipartFormData> formData))block
244
+                               progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgress
245
+                                success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
246
+                                failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure;
247
+
248
+/**
249
+ Creates and runs an `NSURLSessionDataTask` with a `PUT` request.
250
+
251
+ @param URLString The URL string used to create the request URL.
252
+ @param parameters The parameters to be encoded according to the client request serializer.
253
+ @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.
254
+ @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.
255
+
256
+ @see -dataTaskWithRequest:completionHandler:
257
+ */
258
+- (nullable NSURLSessionDataTask *)PUT:(NSString *)URLString
259
+                   parameters:(nullable id)parameters
260
+                      success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
261
+                      failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure;
262
+
263
+/**
264
+ Creates and runs an `NSURLSessionDataTask` with a `PATCH` request.
265
+
266
+ @param URLString The URL string used to create the request URL.
267
+ @param parameters The parameters to be encoded according to the client request serializer.
268
+ @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.
269
+ @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.
270
+
271
+ @see -dataTaskWithRequest:completionHandler:
272
+ */
273
+- (nullable NSURLSessionDataTask *)PATCH:(NSString *)URLString
274
+                     parameters:(nullable id)parameters
275
+                        success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
276
+                        failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure;
277
+
278
+/**
279
+ Creates and runs an `NSURLSessionDataTask` with a `DELETE` request.
280
+
281
+ @param URLString The URL string used to create the request URL.
282
+ @param parameters The parameters to be encoded according to the client request serializer.
283
+ @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.
284
+ @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.
285
+
286
+ @see -dataTaskWithRequest:completionHandler:
287
+ */
288
+- (nullable NSURLSessionDataTask *)DELETE:(NSString *)URLString
289
+                      parameters:(nullable id)parameters
290
+                         success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
291
+                         failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure;
292
+
293
+/**
294
+ Creates and runs an `NSURLSessionDataTask` with a multipart request using given HTTP method.
295
+
296
+ @param HTTPMethod The HTTP method used to create the request.
297
+ @param URLString The URL string used to create the request URL.
298
+ @param parameters The parameters to be encoded according to the client request serializer.
299
+ @param block A block that takes a single argument and appends data to the HTTP body. The block argument is an object adopting the `AFMultipartFormData` protocol.
300
+ @param uploadProgress A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue.
301
+ @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.
302
+ @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.
303
+
304
+ @see -dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler:
305
+ */
306
+- (nullable NSURLSessionDataTask *)uploadTaskWithHTTPMethod:(NSString *)HTTPMethod
307
+                                                  URLString:(NSString *)URLString
308
+                                                 parameters:(nullable id)parameters
309
+                                  constructingBodyWithBlock:(nullable void (^)(id <AFMultipartFormData> formData))block
310
+                                                   progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgress
311
+                                                    success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
312
+                                                    failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure;
313
+
314
+/**
315
+ Creates and runs an `NSURLSessionDataTask` with given HTTP method.
316
+
317
+ @param URLString The URL string used to create the request URL.
318
+ @param parameters The parameters to be encoded according to the client request serializer.
319
+ @param uploadProgress A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue.
320
+ @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.
321
+ @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.
322
+
323
+ @see -dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler:
324
+ */
325
+- (nullable NSURLSessionDataTask *)uploadTaskWithHTTPMethod:(NSString *)HTTPMethod
326
+                                                  URLString:(NSString *)URLString
327
+                                                 parameters:(nullable id)parameters
328
+                                                   progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgress
329
+                                                    success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
330
+                                                    failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure;
331
+
332
+/**
333
+ Creates and runs an `NSURLSessionDataTask` with a given HTTP method.
334
+
335
+ @param HTTPMethod The HTTP method used to create the request.
336
+ @param URLString The URL string used to create the request URL.
337
+ @param parameters The parameters to be encoded according to the client request serializer.
338
+ @param downloadProgress A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue.
339
+ @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.
340
+ @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.
341
+
342
+ @see -dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler:
343
+ */
344
+- (nullable NSURLSessionDataTask *)downloadTaskWithHTTPMethod:(NSString *)HTTPMethod
345
+                                                    URLString:(NSString *)URLString
346
+                                                   parameters:(nullable id)parameters
347
+                                                     progress:(nullable void (^)(NSProgress *downloadProgress))downloadProgress
348
+                                                      success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
349
+                                                      failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure;
350
+
351
+@end
352
+
353
+NS_ASSUME_NONNULL_END

+ 464
- 0
node_modules/cordova-plugin-advanced-http/src/ios/AFNetworking/AFHTTPSessionManager.m Visa fil

@@ -0,0 +1,464 @@
1
+// AFHTTPSessionManager.m
2
+// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3
+//
4
+// Permission is hereby granted, free of charge, to any person obtaining a copy
5
+// of this software and associated documentation files (the "Software"), to deal
6
+// in the Software without restriction, including without limitation the rights
7
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+// copies of the Software, and to permit persons to whom the Software is
9
+// furnished to do so, subject to the following conditions:
10
+//
11
+// The above copyright notice and this permission notice shall be included in
12
+// all copies or substantial portions of the Software.
13
+//
14
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20
+// THE SOFTWARE.
21
+
22
+#import "AFHTTPSessionManager.h"
23
+
24
+#import "AFURLRequestSerialization.h"
25
+#import "AFURLResponseSerialization.h"
26
+
27
+#import <Availability.h>
28
+#import <TargetConditionals.h>
29
+#import <Security/Security.h>
30
+
31
+#import <netinet/in.h>
32
+#import <netinet6/in6.h>
33
+#import <arpa/inet.h>
34
+#import <ifaddrs.h>
35
+#import <netdb.h>
36
+
37
+#if TARGET_OS_IOS || TARGET_OS_TV
38
+#import <UIKit/UIKit.h>
39
+#elif TARGET_OS_WATCH
40
+#import <WatchKit/WatchKit.h>
41
+#endif
42
+
43
+@interface AFHTTPSessionManager ()
44
+@property (readwrite, nonatomic, strong) NSURL *baseURL;
45
+@end
46
+
47
+@implementation AFHTTPSessionManager
48
+@dynamic responseSerializer;
49
+
50
++ (instancetype)manager {
51
+    return [[[self class] alloc] initWithBaseURL:nil];
52
+}
53
+
54
+- (instancetype)init {
55
+    return [self initWithBaseURL:nil];
56
+}
57
+
58
+- (instancetype)initWithBaseURL:(NSURL *)url {
59
+    return [self initWithBaseURL:url sessionConfiguration:nil];
60
+}
61
+
62
+- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration {
63
+    return [self initWithBaseURL:nil sessionConfiguration:configuration];
64
+}
65
+
66
+- (instancetype)initWithBaseURL:(NSURL *)url
67
+           sessionConfiguration:(NSURLSessionConfiguration *)configuration
68
+{
69
+    self = [super initWithSessionConfiguration:configuration];
70
+    if (!self) {
71
+        return nil;
72
+    }
73
+
74
+    // Ensure terminal slash for baseURL path, so that NSURL +URLWithString:relativeToURL: works as expected
75
+    if ([[url path] length] > 0 && ![[url absoluteString] hasSuffix:@"/"]) {
76
+        url = [url URLByAppendingPathComponent:@""];
77
+    }
78
+
79
+    self.baseURL = url;
80
+
81
+    self.requestSerializer = [AFHTTPRequestSerializer serializer];
82
+    self.responseSerializer = [AFJSONResponseSerializer serializer];
83
+
84
+    return self;
85
+}
86
+
87
+#pragma mark -
88
+
89
+- (void)setRequestSerializer:(AFHTTPRequestSerializer <AFURLRequestSerialization> *)requestSerializer {
90
+    NSParameterAssert(requestSerializer);
91
+
92
+    _requestSerializer = requestSerializer;
93
+}
94
+
95
+- (void)setResponseSerializer:(AFHTTPResponseSerializer <AFURLResponseSerialization> *)responseSerializer {
96
+    NSParameterAssert(responseSerializer);
97
+
98
+    [super setResponseSerializer:responseSerializer];
99
+}
100
+
101
+#pragma mark -
102
+
103
+- (NSURLSessionDataTask *)GET:(NSString *)URLString
104
+                   parameters:(id)parameters
105
+                      success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
106
+                      failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
107
+{
108
+
109
+    return [self GET:URLString parameters:parameters progress:nil success:success failure:failure];
110
+}
111
+
112
+- (NSURLSessionDataTask *)GET:(NSString *)URLString
113
+                   parameters:(id)parameters
114
+                     progress:(void (^)(NSProgress * _Nonnull))downloadProgress
115
+                      success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success
116
+                      failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure
117
+{
118
+
119
+    NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"GET"
120
+                                                        URLString:URLString
121
+                                                       parameters:parameters
122
+                                                   uploadProgress:nil
123
+                                                 downloadProgress:downloadProgress
124
+                                                          success:success
125
+                                                          failure:failure];
126
+
127
+    [dataTask resume];
128
+
129
+    return dataTask;
130
+}
131
+
132
+- (NSURLSessionDataTask *)HEAD:(NSString *)URLString
133
+                    parameters:(id)parameters
134
+                       success:(void (^)(NSURLSessionDataTask *task))success
135
+                       failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
136
+{
137
+    NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"HEAD" URLString:URLString parameters:parameters uploadProgress:nil downloadProgress:nil success:^(NSURLSessionDataTask *task, __unused id responseObject) {
138
+        if (success) {
139
+            success(task);
140
+        }
141
+    } failure:failure];
142
+
143
+    [dataTask resume];
144
+
145
+    return dataTask;
146
+}
147
+
148
+- (NSURLSessionDataTask *)POST:(NSString *)URLString
149
+                    parameters:(id)parameters
150
+                       success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
151
+                       failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
152
+{
153
+    return [self POST:URLString parameters:parameters progress:nil success:success failure:failure];
154
+}
155
+
156
+- (NSURLSessionDataTask *)POST:(NSString *)URLString
157
+                    parameters:(id)parameters
158
+                      progress:(void (^)(NSProgress * _Nonnull))uploadProgress
159
+                       success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success
160
+                       failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure
161
+{
162
+    NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"POST" URLString:URLString parameters:parameters uploadProgress:uploadProgress downloadProgress:nil success:success failure:failure];
163
+
164
+    [dataTask resume];
165
+
166
+    return dataTask;
167
+}
168
+
169
+- (NSURLSessionDataTask *)POST:(NSString *)URLString
170
+                    parameters:(nullable id)parameters
171
+     constructingBodyWithBlock:(nullable void (^)(id<AFMultipartFormData> _Nonnull))block
172
+                       success:(nullable void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success
173
+                       failure:(nullable void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure
174
+{
175
+    return [self POST:URLString parameters:parameters constructingBodyWithBlock:block progress:nil success:success failure:failure];
176
+}
177
+
178
+- (NSURLSessionDataTask *)POST:(NSString *)URLString
179
+                    parameters:(id)parameters
180
+     constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
181
+                      progress:(nullable void (^)(NSProgress * _Nonnull))uploadProgress
182
+                       success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
183
+                       failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
184
+{
185
+    NSError *serializationError = nil;
186
+    NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters constructingBodyWithBlock:block error:&serializationError];
187
+    [request setHTTPShouldHandleCookies:NO];
188
+    
189
+    if (serializationError) {
190
+        if (failure) {
191
+            dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{
192
+                failure(nil, serializationError);
193
+            });
194
+        }
195
+
196
+        return nil;
197
+    }
198
+
199
+    __block NSURLSessionDataTask *task = [self uploadTaskWithStreamedRequest:request progress:uploadProgress completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) {
200
+        if (error) {
201
+            if (failure) {
202
+                failure(task, error);
203
+            }
204
+        } else {
205
+            if (success) {
206
+                success(task, responseObject);
207
+            }
208
+        }
209
+    }];
210
+
211
+    [task resume];
212
+
213
+    return task;
214
+}
215
+
216
+- (NSURLSessionDataTask *)PUT:(NSString *)URLString
217
+                   parameters:(id)parameters
218
+                      success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
219
+                      failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
220
+{
221
+    NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"PUT" URLString:URLString parameters:parameters uploadProgress:nil downloadProgress:nil success:success failure:failure];
222
+
223
+    [dataTask resume];
224
+
225
+    return dataTask;
226
+}
227
+
228
+- (NSURLSessionDataTask *)PUT:(NSString *)URLString
229
+                    parameters:(id)parameters
230
+     constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
231
+                      progress:(nullable void (^)(NSProgress * _Nonnull))uploadProgress
232
+                       success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
233
+                       failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
234
+{
235
+    NSError *serializationError = nil;
236
+    NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters constructingBodyWithBlock:block error:&serializationError];
237
+    [request setHTTPShouldHandleCookies:NO];
238
+
239
+    if (serializationError) {
240
+        if (failure) {
241
+            dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{
242
+                failure(nil, serializationError);
243
+            });
244
+        }
245
+
246
+        return nil;
247
+    }
248
+
249
+    __block NSURLSessionDataTask *task = [self uploadTaskWithStreamedRequest:request progress:uploadProgress completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) {
250
+        if (error) {
251
+            if (failure) {
252
+                failure(task, error);
253
+            }
254
+        } else {
255
+            if (success) {
256
+                success(task, responseObject);
257
+            }
258
+        }
259
+    }];
260
+
261
+    [task resume];
262
+
263
+    return task;
264
+}
265
+
266
+- (NSURLSessionDataTask *)PATCH:(NSString *)URLString
267
+                     parameters:(id)parameters
268
+                        success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
269
+                        failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
270
+{
271
+    NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"PATCH" URLString:URLString parameters:parameters uploadProgress:nil downloadProgress:nil success:success failure:failure];
272
+
273
+    [dataTask resume];
274
+
275
+    return dataTask;
276
+}
277
+
278
+- (NSURLSessionDataTask *)DELETE:(NSString *)URLString
279
+                      parameters:(id)parameters
280
+                         success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
281
+                         failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
282
+{
283
+    NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"DELETE" URLString:URLString parameters:parameters uploadProgress:nil downloadProgress:nil success:success failure:failure];
284
+
285
+    [dataTask resume];
286
+
287
+    return dataTask;
288
+}
289
+
290
+- (NSURLSessionDataTask *)uploadTaskWithHTTPMethod:(NSString *)method
291
+                                         URLString:(NSString *)URLString
292
+                                        parameters:(id)parameters
293
+                         constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
294
+                                          progress:(nullable void (^)(NSProgress * _Nonnull))uploadProgress
295
+                                           success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
296
+                                           failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
297
+{
298
+    NSError *serializationError = nil;
299
+    NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:method URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters constructingBodyWithBlock:block error:&serializationError];
300
+    [request setHTTPShouldHandleCookies:NO];
301
+
302
+    if (serializationError) {
303
+        if (failure) {
304
+            dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{
305
+                failure(nil, serializationError);
306
+            });
307
+        }
308
+
309
+        return nil;
310
+    }
311
+
312
+    __block NSURLSessionDataTask *task = [self uploadTaskWithStreamedRequest:request progress:uploadProgress completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) {
313
+        if (error) {
314
+            if (failure) {
315
+                failure(task, error);
316
+            }
317
+        } else {
318
+            if (success) {
319
+                success(task, responseObject);
320
+            }
321
+        }
322
+    }];
323
+
324
+    [task resume];
325
+
326
+    return task;
327
+}
328
+
329
+- (NSURLSessionDataTask *)uploadTaskWithHTTPMethod:(NSString *)method
330
+                                        URLString:(NSString *)URLString
331
+                                       parameters:(id)parameters
332
+                                         progress:(void (^)(NSProgress * _Nonnull))uploadProgress
333
+                                          success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success
334
+                                          failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure
335
+{
336
+    NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:method URLString:URLString parameters:parameters uploadProgress:uploadProgress downloadProgress:nil success:success failure:failure];
337
+
338
+    [dataTask resume];
339
+
340
+    return dataTask;
341
+}
342
+
343
+- (NSURLSessionDataTask *)downloadTaskWithHTTPMethod:(NSString *)method
344
+                                           URLString:(NSString *)URLString
345
+                                          parameters:(id)parameters
346
+                                            progress:(nullable void (^)(NSProgress * _Nonnull))downloadProgress
347
+                                             success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success
348
+                                             failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure
349
+{
350
+    NSURLSessionDataTask *task = [self dataTaskWithHTTPMethod:method URLString:URLString parameters:parameters uploadProgress:nil downloadProgress:downloadProgress success:success failure:failure];
351
+
352
+    [task resume];
353
+
354
+    return task;
355
+}
356
+
357
+- (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method
358
+                                       URLString:(NSString *)URLString
359
+                                      parameters:(id)parameters
360
+                                  uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgress
361
+                                downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgress
362
+                                         success:(void (^)(NSURLSessionDataTask *, id))success
363
+                                         failure:(void (^)(NSURLSessionDataTask *, NSError *))failure
364
+{
365
+    NSError *serializationError = nil;
366
+    NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:method URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:&serializationError];
367
+    [request setHTTPShouldHandleCookies:NO];
368
+    
369
+    if (serializationError) {
370
+        if (failure) {
371
+            dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{
372
+                failure(nil, serializationError);
373
+            });
374
+        }
375
+
376
+        return nil;
377
+    }
378
+
379
+    __block NSURLSessionDataTask *dataTask = nil;
380
+    dataTask = [self dataTaskWithRequest:request
381
+                          uploadProgress:uploadProgress
382
+                        downloadProgress:downloadProgress
383
+                       completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) {
384
+        if (error) {
385
+            if (failure) {
386
+                failure(dataTask, error);
387
+            }
388
+        } else {
389
+            if (success) {
390
+                success(dataTask, responseObject);
391
+            }
392
+        }
393
+    }];
394
+
395
+    return dataTask;
396
+}
397
+
398
+#pragma mark - NSObject
399
+
400
+- (NSString *)description {
401
+    return [NSString stringWithFormat:@"<%@: %p, baseURL: %@, session: %@, operationQueue: %@>", NSStringFromClass([self class]), self, [self.baseURL absoluteString], self.session, self.operationQueue];
402
+}
403
+
404
+#pragma mark - NSSecureCoding
405
+
406
++ (BOOL)supportsSecureCoding {
407
+    return YES;
408
+}
409
+
410
+- (instancetype)initWithCoder:(NSCoder *)decoder {
411
+    NSURL *baseURL = [decoder decodeObjectOfClass:[NSURL class] forKey:NSStringFromSelector(@selector(baseURL))];
412
+    NSURLSessionConfiguration *configuration = [decoder decodeObjectOfClass:[NSURLSessionConfiguration class] forKey:@"sessionConfiguration"];
413
+    if (!configuration) {
414
+        NSString *configurationIdentifier = [decoder decodeObjectOfClass:[NSString class] forKey:@"identifier"];
415
+        if (configurationIdentifier) {
416
+#if (defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1100)
417
+            configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:configurationIdentifier];
418
+#else
419
+            configuration = [NSURLSessionConfiguration backgroundSessionConfiguration:configurationIdentifier];
420
+#endif
421
+        }
422
+    }
423
+
424
+    self = [self initWithBaseURL:baseURL sessionConfiguration:configuration];
425
+    if (!self) {
426
+        return nil;
427
+    }
428
+
429
+    self.requestSerializer = [decoder decodeObjectOfClass:[AFHTTPRequestSerializer class] forKey:NSStringFromSelector(@selector(requestSerializer))];
430
+    self.responseSerializer = [decoder decodeObjectOfClass:[AFHTTPResponseSerializer class] forKey:NSStringFromSelector(@selector(responseSerializer))];
431
+    AFSecurityPolicy *decodedPolicy = [decoder decodeObjectOfClass:[AFSecurityPolicy class] forKey:NSStringFromSelector(@selector(securityPolicy))];
432
+    if (decodedPolicy) {
433
+        self.securityPolicy = decodedPolicy;
434
+    }
435
+
436
+    return self;
437
+}
438
+
439
+- (void)encodeWithCoder:(NSCoder *)coder {
440
+    [super encodeWithCoder:coder];
441
+
442
+    [coder encodeObject:self.baseURL forKey:NSStringFromSelector(@selector(baseURL))];
443
+    if ([self.session.configuration conformsToProtocol:@protocol(NSCoding)]) {
444
+        [coder encodeObject:self.session.configuration forKey:@"sessionConfiguration"];
445
+    } else {
446
+        [coder encodeObject:self.session.configuration.identifier forKey:@"identifier"];
447
+    }
448
+    [coder encodeObject:self.requestSerializer forKey:NSStringFromSelector(@selector(requestSerializer))];
449
+    [coder encodeObject:self.responseSerializer forKey:NSStringFromSelector(@selector(responseSerializer))];
450
+    [coder encodeObject:self.securityPolicy forKey:NSStringFromSelector(@selector(securityPolicy))];
451
+}
452
+
453
+#pragma mark - NSCopying
454
+
455
+- (instancetype)copyWithZone:(NSZone *)zone {
456
+    AFHTTPSessionManager *HTTPClient = [[[self class] allocWithZone:zone] initWithBaseURL:self.baseURL sessionConfiguration:self.session.configuration];
457
+
458
+    HTTPClient.requestSerializer = [self.requestSerializer copyWithZone:zone];
459
+    HTTPClient.responseSerializer = [self.responseSerializer copyWithZone:zone];
460
+    HTTPClient.securityPolicy = [self.securityPolicy copyWithZone:zone];
461
+    return HTTPClient;
462
+}
463
+
464
+@end

+ 206
- 0
node_modules/cordova-plugin-advanced-http/src/ios/AFNetworking/AFNetworkReachabilityManager.h Visa fil

@@ -0,0 +1,206 @@
1
+// AFNetworkReachabilityManager.h
2
+// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3
+//
4
+// Permission is hereby granted, free of charge, to any person obtaining a copy
5
+// of this software and associated documentation files (the "Software"), to deal
6
+// in the Software without restriction, including without limitation the rights
7
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+// copies of the Software, and to permit persons to whom the Software is
9
+// furnished to do so, subject to the following conditions:
10
+//
11
+// The above copyright notice and this permission notice shall be included in
12
+// all copies or substantial portions of the Software.
13
+//
14
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20
+// THE SOFTWARE.
21
+
22
+#import <Foundation/Foundation.h>
23
+
24
+#if !TARGET_OS_WATCH
25
+#import <SystemConfiguration/SystemConfiguration.h>
26
+
27
+typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) {
28
+    AFNetworkReachabilityStatusUnknown          = -1,
29
+    AFNetworkReachabilityStatusNotReachable     = 0,
30
+    AFNetworkReachabilityStatusReachableViaWWAN = 1,
31
+    AFNetworkReachabilityStatusReachableViaWiFi = 2,
32
+};
33
+
34
+NS_ASSUME_NONNULL_BEGIN
35
+
36
+/**
37
+ `AFNetworkReachabilityManager` monitors the reachability of domains, and addresses for both WWAN and WiFi network interfaces.
38
+
39
+ Reachability can be used to determine background information about why a network operation failed, or to trigger a network operation retrying when a connection is established. It should not be used to prevent a user from initiating a network request, as it's possible that an initial request may be required to establish reachability.
40
+
41
+ See Apple's Reachability Sample Code ( https://developer.apple.com/library/ios/samplecode/reachability/ )
42
+
43
+ @warning Instances of `AFNetworkReachabilityManager` must be started with `-startMonitoring` before reachability status can be determined.
44
+ */
45
+@interface AFNetworkReachabilityManager : NSObject
46
+
47
+/**
48
+ The current network reachability status.
49
+ */
50
+@property (readonly, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus;
51
+
52
+/**
53
+ Whether or not the network is currently reachable.
54
+ */
55
+@property (readonly, nonatomic, assign, getter = isReachable) BOOL reachable;
56
+
57
+/**
58
+ Whether or not the network is currently reachable via WWAN.
59
+ */
60
+@property (readonly, nonatomic, assign, getter = isReachableViaWWAN) BOOL reachableViaWWAN;
61
+
62
+/**
63
+ Whether or not the network is currently reachable via WiFi.
64
+ */
65
+@property (readonly, nonatomic, assign, getter = isReachableViaWiFi) BOOL reachableViaWiFi;
66
+
67
+///---------------------
68
+/// @name Initialization
69
+///---------------------
70
+
71
+/**
72
+ Returns the shared network reachability manager.
73
+ */
74
++ (instancetype)sharedManager;
75
+
76
+/**
77
+ Creates and returns a network reachability manager with the default socket address.
78
+ 
79
+ @return An initialized network reachability manager, actively monitoring the default socket address.
80
+ */
81
++ (instancetype)manager;
82
+
83
+/**
84
+ Creates and returns a network reachability manager for the specified domain.
85
+
86
+ @param domain The domain used to evaluate network reachability.
87
+
88
+ @return An initialized network reachability manager, actively monitoring the specified domain.
89
+ */
90
++ (instancetype)managerForDomain:(NSString *)domain;
91
+
92
+/**
93
+ Creates and returns a network reachability manager for the socket address.
94
+
95
+ @param address The socket address (`sockaddr_in6`) used to evaluate network reachability.
96
+
97
+ @return An initialized network reachability manager, actively monitoring the specified socket address.
98
+ */
99
++ (instancetype)managerForAddress:(const void *)address;
100
+
101
+/**
102
+ Initializes an instance of a network reachability manager from the specified reachability object.
103
+
104
+ @param reachability The reachability object to monitor.
105
+
106
+ @return An initialized network reachability manager, actively monitoring the specified reachability.
107
+ */
108
+- (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability NS_DESIGNATED_INITIALIZER;
109
+
110
+///--------------------------------------------------
111
+/// @name Starting & Stopping Reachability Monitoring
112
+///--------------------------------------------------
113
+
114
+/**
115
+ Starts monitoring for changes in network reachability status.
116
+ */
117
+- (void)startMonitoring;
118
+
119
+/**
120
+ Stops monitoring for changes in network reachability status.
121
+ */
122
+- (void)stopMonitoring;
123
+
124
+///-------------------------------------------------
125
+/// @name Getting Localized Reachability Description
126
+///-------------------------------------------------
127
+
128
+/**
129
+ Returns a localized string representation of the current network reachability status.
130
+ */
131
+- (NSString *)localizedNetworkReachabilityStatusString;
132
+
133
+///---------------------------------------------------
134
+/// @name Setting Network Reachability Change Callback
135
+///---------------------------------------------------
136
+
137
+/**
138
+ Sets a callback to be executed when the network availability of the `baseURL` host changes.
139
+
140
+ @param block A block object to be executed when the network availability of the `baseURL` host changes.. This block has no return value and takes a single argument which represents the various reachability states from the device to the `baseURL`.
141
+ */
142
+- (void)setReachabilityStatusChangeBlock:(nullable void (^)(AFNetworkReachabilityStatus status))block;
143
+
144
+@end
145
+
146
+///----------------
147
+/// @name Constants
148
+///----------------
149
+
150
+/**
151
+ ## Network Reachability
152
+
153
+ The following constants are provided by `AFNetworkReachabilityManager` as possible network reachability statuses.
154
+
155
+ enum {
156
+ AFNetworkReachabilityStatusUnknown,
157
+ AFNetworkReachabilityStatusNotReachable,
158
+ AFNetworkReachabilityStatusReachableViaWWAN,
159
+ AFNetworkReachabilityStatusReachableViaWiFi,
160
+ }
161
+
162
+ `AFNetworkReachabilityStatusUnknown`
163
+ The `baseURL` host reachability is not known.
164
+
165
+ `AFNetworkReachabilityStatusNotReachable`
166
+ The `baseURL` host cannot be reached.
167
+
168
+ `AFNetworkReachabilityStatusReachableViaWWAN`
169
+ The `baseURL` host can be reached via a cellular connection, such as EDGE or GPRS.
170
+
171
+ `AFNetworkReachabilityStatusReachableViaWiFi`
172
+ The `baseURL` host can be reached via a Wi-Fi connection.
173
+
174
+ ### Keys for Notification UserInfo Dictionary
175
+
176
+ Strings that are used as keys in a `userInfo` dictionary in a network reachability status change notification.
177
+
178
+ `AFNetworkingReachabilityNotificationStatusItem`
179
+ A key in the userInfo dictionary in a `AFNetworkingReachabilityDidChangeNotification` notification.
180
+ The corresponding value is an `NSNumber` object representing the `AFNetworkReachabilityStatus` value for the current reachability status.
181
+ */
182
+
183
+///--------------------
184
+/// @name Notifications
185
+///--------------------
186
+
187
+/**
188
+ Posted when network reachability changes.
189
+ This notification assigns no notification object. The `userInfo` dictionary contains an `NSNumber` object under the `AFNetworkingReachabilityNotificationStatusItem` key, representing the `AFNetworkReachabilityStatus` value for the current network reachability.
190
+
191
+ @warning In order for network reachability to be monitored, include the `SystemConfiguration` framework in the active target's "Link Binary With Library" build phase, and add `#import <SystemConfiguration/SystemConfiguration.h>` to the header prefix of the project (`Prefix.pch`).
192
+ */
193
+FOUNDATION_EXPORT NSString * const AFNetworkingReachabilityDidChangeNotification;
194
+FOUNDATION_EXPORT NSString * const AFNetworkingReachabilityNotificationStatusItem;
195
+
196
+///--------------------
197
+/// @name Functions
198
+///--------------------
199
+
200
+/**
201
+ Returns a localized string representation of an `AFNetworkReachabilityStatus` value.
202
+ */
203
+FOUNDATION_EXPORT NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status);
204
+
205
+NS_ASSUME_NONNULL_END
206
+#endif

+ 263
- 0
node_modules/cordova-plugin-advanced-http/src/ios/AFNetworking/AFNetworkReachabilityManager.m Visa fil

@@ -0,0 +1,263 @@
1
+// AFNetworkReachabilityManager.m
2
+// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3
+//
4
+// Permission is hereby granted, free of charge, to any person obtaining a copy
5
+// of this software and associated documentation files (the "Software"), to deal
6
+// in the Software without restriction, including without limitation the rights
7
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+// copies of the Software, and to permit persons to whom the Software is
9
+// furnished to do so, subject to the following conditions:
10
+//
11
+// The above copyright notice and this permission notice shall be included in
12
+// all copies or substantial portions of the Software.
13
+//
14
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20
+// THE SOFTWARE.
21
+
22
+#import "AFNetworkReachabilityManager.h"
23
+#if !TARGET_OS_WATCH
24
+
25
+#import <netinet/in.h>
26
+#import <netinet6/in6.h>
27
+#import <arpa/inet.h>
28
+#import <ifaddrs.h>
29
+#import <netdb.h>
30
+
31
+NSString * const AFNetworkingReachabilityDidChangeNotification = @"com.alamofire.networking.reachability.change";
32
+NSString * const AFNetworkingReachabilityNotificationStatusItem = @"AFNetworkingReachabilityNotificationStatusItem";
33
+
34
+typedef void (^AFNetworkReachabilityStatusBlock)(AFNetworkReachabilityStatus status);
35
+
36
+NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status) {
37
+    switch (status) {
38
+        case AFNetworkReachabilityStatusNotReachable:
39
+            return NSLocalizedStringFromTable(@"Not Reachable", @"AFNetworking", nil);
40
+        case AFNetworkReachabilityStatusReachableViaWWAN:
41
+            return NSLocalizedStringFromTable(@"Reachable via WWAN", @"AFNetworking", nil);
42
+        case AFNetworkReachabilityStatusReachableViaWiFi:
43
+            return NSLocalizedStringFromTable(@"Reachable via WiFi", @"AFNetworking", nil);
44
+        case AFNetworkReachabilityStatusUnknown:
45
+        default:
46
+            return NSLocalizedStringFromTable(@"Unknown", @"AFNetworking", nil);
47
+    }
48
+}
49
+
50
+static AFNetworkReachabilityStatus AFNetworkReachabilityStatusForFlags(SCNetworkReachabilityFlags flags) {
51
+    BOOL isReachable = ((flags & kSCNetworkReachabilityFlagsReachable) != 0);
52
+    BOOL needsConnection = ((flags & kSCNetworkReachabilityFlagsConnectionRequired) != 0);
53
+    BOOL canConnectionAutomatically = (((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) || ((flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0));
54
+    BOOL canConnectWithoutUserInteraction = (canConnectionAutomatically && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0);
55
+    BOOL isNetworkReachable = (isReachable && (!needsConnection || canConnectWithoutUserInteraction));
56
+
57
+    AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusUnknown;
58
+    if (isNetworkReachable == NO) {
59
+        status = AFNetworkReachabilityStatusNotReachable;
60
+    }
61
+#if	TARGET_OS_IPHONE
62
+    else if ((flags & kSCNetworkReachabilityFlagsIsWWAN) != 0) {
63
+        status = AFNetworkReachabilityStatusReachableViaWWAN;
64
+    }
65
+#endif
66
+    else {
67
+        status = AFNetworkReachabilityStatusReachableViaWiFi;
68
+    }
69
+
70
+    return status;
71
+}
72
+
73
+/**
74
+ * Queue a status change notification for the main thread.
75
+ *
76
+ * This is done to ensure that the notifications are received in the same order
77
+ * as they are sent. If notifications are sent directly, it is possible that
78
+ * a queued notification (for an earlier status condition) is processed after
79
+ * the later update, resulting in the listener being left in the wrong state.
80
+ */
81
+static void AFPostReachabilityStatusChange(SCNetworkReachabilityFlags flags, AFNetworkReachabilityStatusBlock block) {
82
+    AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusForFlags(flags);
83
+    dispatch_async(dispatch_get_main_queue(), ^{
84
+        if (block) {
85
+            block(status);
86
+        }
87
+        NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
88
+        NSDictionary *userInfo = @{ AFNetworkingReachabilityNotificationStatusItem: @(status) };
89
+        [notificationCenter postNotificationName:AFNetworkingReachabilityDidChangeNotification object:nil userInfo:userInfo];
90
+    });
91
+}
92
+
93
+static void AFNetworkReachabilityCallback(SCNetworkReachabilityRef __unused target, SCNetworkReachabilityFlags flags, void *info) {
94
+    AFPostReachabilityStatusChange(flags, (__bridge AFNetworkReachabilityStatusBlock)info);
95
+}
96
+
97
+
98
+static const void * AFNetworkReachabilityRetainCallback(const void *info) {
99
+    return Block_copy(info);
100
+}
101
+
102
+static void AFNetworkReachabilityReleaseCallback(const void *info) {
103
+    if (info) {
104
+        Block_release(info);
105
+    }
106
+}
107
+
108
+@interface AFNetworkReachabilityManager ()
109
+@property (readonly, nonatomic, assign) SCNetworkReachabilityRef networkReachability;
110
+@property (readwrite, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus;
111
+@property (readwrite, nonatomic, copy) AFNetworkReachabilityStatusBlock networkReachabilityStatusBlock;
112
+@end
113
+
114
+@implementation AFNetworkReachabilityManager
115
+
116
++ (instancetype)sharedManager {
117
+    static AFNetworkReachabilityManager *_sharedManager = nil;
118
+    static dispatch_once_t onceToken;
119
+    dispatch_once(&onceToken, ^{
120
+        _sharedManager = [self manager];
121
+    });
122
+
123
+    return _sharedManager;
124
+}
125
+
126
++ (instancetype)managerForDomain:(NSString *)domain {
127
+    SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [domain UTF8String]);
128
+
129
+    AFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability];
130
+    
131
+    CFRelease(reachability);
132
+
133
+    return manager;
134
+}
135
+
136
++ (instancetype)managerForAddress:(const void *)address {
137
+    SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr *)address);
138
+    AFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability];
139
+
140
+    CFRelease(reachability);
141
+    
142
+    return manager;
143
+}
144
+
145
++ (instancetype)manager
146
+{
147
+#if (defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 90000) || (defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101100)
148
+    struct sockaddr_in6 address;
149
+    bzero(&address, sizeof(address));
150
+    address.sin6_len = sizeof(address);
151
+    address.sin6_family = AF_INET6;
152
+#else
153
+    struct sockaddr_in address;
154
+    bzero(&address, sizeof(address));
155
+    address.sin_len = sizeof(address);
156
+    address.sin_family = AF_INET;
157
+#endif
158
+    return [self managerForAddress:&address];
159
+}
160
+
161
+- (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability {
162
+    self = [super init];
163
+    if (!self) {
164
+        return nil;
165
+    }
166
+
167
+    _networkReachability = CFRetain(reachability);
168
+    self.networkReachabilityStatus = AFNetworkReachabilityStatusUnknown;
169
+
170
+    return self;
171
+}
172
+
173
+- (instancetype)init NS_UNAVAILABLE
174
+{
175
+    return nil;
176
+}
177
+
178
+- (void)dealloc {
179
+    [self stopMonitoring];
180
+    
181
+    if (_networkReachability != NULL) {
182
+        CFRelease(_networkReachability);
183
+    }
184
+}
185
+
186
+#pragma mark -
187
+
188
+- (BOOL)isReachable {
189
+    return [self isReachableViaWWAN] || [self isReachableViaWiFi];
190
+}
191
+
192
+- (BOOL)isReachableViaWWAN {
193
+    return self.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWWAN;
194
+}
195
+
196
+- (BOOL)isReachableViaWiFi {
197
+    return self.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWiFi;
198
+}
199
+
200
+#pragma mark -
201
+
202
+- (void)startMonitoring {
203
+    [self stopMonitoring];
204
+
205
+    if (!self.networkReachability) {
206
+        return;
207
+    }
208
+
209
+    __weak __typeof(self)weakSelf = self;
210
+    AFNetworkReachabilityStatusBlock callback = ^(AFNetworkReachabilityStatus status) {
211
+        __strong __typeof(weakSelf)strongSelf = weakSelf;
212
+
213
+        strongSelf.networkReachabilityStatus = status;
214
+        if (strongSelf.networkReachabilityStatusBlock) {
215
+            strongSelf.networkReachabilityStatusBlock(status);
216
+        }
217
+
218
+    };
219
+
220
+    SCNetworkReachabilityContext context = {0, (__bridge void *)callback, AFNetworkReachabilityRetainCallback, AFNetworkReachabilityReleaseCallback, NULL};
221
+    SCNetworkReachabilitySetCallback(self.networkReachability, AFNetworkReachabilityCallback, &context);
222
+    SCNetworkReachabilityScheduleWithRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes);
223
+
224
+    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0),^{
225
+        SCNetworkReachabilityFlags flags;
226
+        if (SCNetworkReachabilityGetFlags(self.networkReachability, &flags)) {
227
+            AFPostReachabilityStatusChange(flags, callback);
228
+        }
229
+    });
230
+}
231
+
232
+- (void)stopMonitoring {
233
+    if (!self.networkReachability) {
234
+        return;
235
+    }
236
+
237
+    SCNetworkReachabilityUnscheduleFromRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes);
238
+}
239
+
240
+#pragma mark -
241
+
242
+- (NSString *)localizedNetworkReachabilityStatusString {
243
+    return AFStringFromNetworkReachabilityStatus(self.networkReachabilityStatus);
244
+}
245
+
246
+#pragma mark -
247
+
248
+- (void)setReachabilityStatusChangeBlock:(void (^)(AFNetworkReachabilityStatus status))block {
249
+    self.networkReachabilityStatusBlock = block;
250
+}
251
+
252
+#pragma mark - NSKeyValueObserving
253
+
254
++ (NSSet *)keyPathsForValuesAffectingValueForKey:(NSString *)key {
255
+    if ([key isEqualToString:@"reachable"] || [key isEqualToString:@"reachableViaWWAN"] || [key isEqualToString:@"reachableViaWiFi"]) {
256
+        return [NSSet setWithObject:@"networkReachabilityStatus"];
257
+    }
258
+
259
+    return [super keyPathsForValuesAffectingValueForKey:key];
260
+}
261
+
262
+@end
263
+#endif

+ 41
- 0
node_modules/cordova-plugin-advanced-http/src/ios/AFNetworking/AFNetworking.h Visa fil

@@ -0,0 +1,41 @@
1
+// AFNetworking.h
2
+//
3
+// Copyright (c) 2013 AFNetworking (http://afnetworking.com/)
4
+// 
5
+// Permission is hereby granted, free of charge, to any person obtaining a copy
6
+// of this software and associated documentation files (the "Software"), to deal
7
+// in the Software without restriction, including without limitation the rights
8
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+// copies of the Software, and to permit persons to whom the Software is
10
+// furnished to do so, subject to the following conditions:
11
+// 
12
+// The above copyright notice and this permission notice shall be included in
13
+// all copies or substantial portions of the Software.
14
+// 
15
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+// THE SOFTWARE.
22
+
23
+#import <Foundation/Foundation.h>
24
+#import <Availability.h>
25
+#import <TargetConditionals.h>
26
+
27
+#ifndef _AFNETWORKING_
28
+    #define _AFNETWORKING_
29
+
30
+    #import "AFURLRequestSerialization.h"
31
+    #import "AFURLResponseSerialization.h"
32
+    #import "AFSecurityPolicy.h"
33
+
34
+#if !TARGET_OS_WATCH
35
+    #import "AFNetworkReachabilityManager.h"
36
+#endif
37
+
38
+    #import "AFURLSessionManager.h"
39
+    #import "AFHTTPSessionManager.h"
40
+
41
+#endif /* _AFNETWORKING_ */

+ 154
- 0
node_modules/cordova-plugin-advanced-http/src/ios/AFNetworking/AFSecurityPolicy.h Visa fil

@@ -0,0 +1,154 @@
1
+// AFSecurityPolicy.h
2
+// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3
+//
4
+// Permission is hereby granted, free of charge, to any person obtaining a copy
5
+// of this software and associated documentation files (the "Software"), to deal
6
+// in the Software without restriction, including without limitation the rights
7
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+// copies of the Software, and to permit persons to whom the Software is
9
+// furnished to do so, subject to the following conditions:
10
+//
11
+// The above copyright notice and this permission notice shall be included in
12
+// all copies or substantial portions of the Software.
13
+//
14
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20
+// THE SOFTWARE.
21
+
22
+#import <Foundation/Foundation.h>
23
+#import <Security/Security.h>
24
+
25
+typedef NS_ENUM(NSUInteger, AFSSLPinningMode) {
26
+    AFSSLPinningModeNone,
27
+    AFSSLPinningModePublicKey,
28
+    AFSSLPinningModeCertificate,
29
+};
30
+
31
+/**
32
+ `AFSecurityPolicy` evaluates server trust against pinned X.509 certificates and public keys over secure connections.
33
+
34
+ Adding pinned SSL certificates to your app helps prevent man-in-the-middle attacks and other vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged to route all communication over an HTTPS connection with SSL pinning configured and enabled.
35
+ */
36
+
37
+NS_ASSUME_NONNULL_BEGIN
38
+
39
+@interface AFSecurityPolicy : NSObject <NSSecureCoding, NSCopying>
40
+
41
+/**
42
+ The criteria by which server trust should be evaluated against the pinned SSL certificates. Defaults to `AFSSLPinningModeNone`.
43
+ */
44
+@property (readonly, nonatomic, assign) AFSSLPinningMode SSLPinningMode;
45
+
46
+/**
47
+ The certificates used to evaluate server trust according to the SSL pinning mode. 
48
+
49
+  By default, this property is set to any (`.cer`) certificates included in the target compiling AFNetworking. Note that if you are using AFNetworking as embedded framework, no certificates will be pinned by default. Use `certificatesInBundle` to load certificates from your target, and then create a new policy by calling `policyWithPinningMode:withPinnedCertificates`.
50
+ 
51
+ Note that if pinning is enabled, `evaluateServerTrust:forDomain:` will return true if any pinned certificate matches.
52
+ */
53
+@property (nonatomic, strong, nullable) NSSet <NSData *> *pinnedCertificates;
54
+
55
+/**
56
+ Whether or not to trust servers with an invalid or expired SSL certificates. Defaults to `NO`.
57
+ */
58
+@property (nonatomic, assign) BOOL allowInvalidCertificates;
59
+
60
+/**
61
+ Whether or not to validate the domain name in the certificate's CN field. Defaults to `YES`.
62
+ */
63
+@property (nonatomic, assign) BOOL validatesDomainName;
64
+
65
+///-----------------------------------------
66
+/// @name Getting Certificates from the Bundle
67
+///-----------------------------------------
68
+
69
+/**
70
+ Returns any certificates included in the bundle. If you are using AFNetworking as an embedded framework, you must use this method to find the certificates you have included in your app bundle, and use them when creating your security policy by calling `policyWithPinningMode:withPinnedCertificates`.
71
+
72
+ @return The certificates included in the given bundle.
73
+ */
74
++ (NSSet <NSData *> *)certificatesInBundle:(NSBundle *)bundle;
75
+
76
+///-----------------------------------------
77
+/// @name Getting Specific Security Policies
78
+///-----------------------------------------
79
+
80
+/**
81
+ Returns the shared default security policy, which does not allow invalid certificates, validates domain name, and does not validate against pinned certificates or public keys.
82
+
83
+ @return The default security policy.
84
+ */
85
++ (instancetype)defaultPolicy;
86
+
87
+///---------------------
88
+/// @name Initialization
89
+///---------------------
90
+
91
+/**
92
+ Creates and returns a security policy with the specified pinning mode.
93
+
94
+ @param pinningMode The SSL pinning mode.
95
+
96
+ @return A new security policy.
97
+ */
98
++ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode;
99
+
100
+/**
101
+ Creates and returns a security policy with the specified pinning mode.
102
+
103
+ @param pinningMode The SSL pinning mode.
104
+ @param pinnedCertificates The certificates to pin against.
105
+
106
+ @return A new security policy.
107
+ */
108
++ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode withPinnedCertificates:(NSSet <NSData *> *)pinnedCertificates;
109
+
110
+///------------------------------
111
+/// @name Evaluating Server Trust
112
+///------------------------------
113
+
114
+/**
115
+ Whether or not the specified server trust should be accepted, based on the security policy.
116
+
117
+ This method should be used when responding to an authentication challenge from a server.
118
+
119
+ @param serverTrust The X.509 certificate trust of the server.
120
+ @param domain The domain of serverTrust. If `nil`, the domain will not be validated.
121
+
122
+ @return Whether or not to trust the server.
123
+ */
124
+- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust
125
+                  forDomain:(nullable NSString *)domain;
126
+
127
+@end
128
+
129
+NS_ASSUME_NONNULL_END
130
+
131
+///----------------
132
+/// @name Constants
133
+///----------------
134
+
135
+/**
136
+ ## SSL Pinning Modes
137
+
138
+ The following constants are provided by `AFSSLPinningMode` as possible SSL pinning modes.
139
+
140
+ enum {
141
+ AFSSLPinningModeNone,
142
+ AFSSLPinningModePublicKey,
143
+ AFSSLPinningModeCertificate,
144
+ }
145
+
146
+ `AFSSLPinningModeNone`
147
+ Do not used pinned certificates to validate servers.
148
+
149
+ `AFSSLPinningModePublicKey`
150
+ Validate host certificates against public keys of pinned certificates.
151
+
152
+ `AFSSLPinningModeCertificate`
153
+ Validate host certificates against pinned certificates.
154
+*/

+ 353
- 0
node_modules/cordova-plugin-advanced-http/src/ios/AFNetworking/AFSecurityPolicy.m Visa fil

@@ -0,0 +1,353 @@
1
+// AFSecurityPolicy.m
2
+// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3
+//
4
+// Permission is hereby granted, free of charge, to any person obtaining a copy
5
+// of this software and associated documentation files (the "Software"), to deal
6
+// in the Software without restriction, including without limitation the rights
7
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+// copies of the Software, and to permit persons to whom the Software is
9
+// furnished to do so, subject to the following conditions:
10
+//
11
+// The above copyright notice and this permission notice shall be included in
12
+// all copies or substantial portions of the Software.
13
+//
14
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20
+// THE SOFTWARE.
21
+
22
+#import "AFSecurityPolicy.h"
23
+
24
+#import <AssertMacros.h>
25
+
26
+#if !TARGET_OS_IOS && !TARGET_OS_WATCH && !TARGET_OS_TV
27
+static NSData * AFSecKeyGetData(SecKeyRef key) {
28
+    CFDataRef data = NULL;
29
+
30
+    __Require_noErr_Quiet(SecItemExport(key, kSecFormatUnknown, kSecItemPemArmour, NULL, &data), _out);
31
+
32
+    return (__bridge_transfer NSData *)data;
33
+
34
+_out:
35
+    if (data) {
36
+        CFRelease(data);
37
+    }
38
+
39
+    return nil;
40
+}
41
+#endif
42
+
43
+static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) {
44
+#if TARGET_OS_IOS || TARGET_OS_WATCH || TARGET_OS_TV
45
+    return [(__bridge id)key1 isEqual:(__bridge id)key2];
46
+#else
47
+    return [AFSecKeyGetData(key1) isEqual:AFSecKeyGetData(key2)];
48
+#endif
49
+}
50
+
51
+static id AFPublicKeyForCertificate(NSData *certificate) {
52
+    id allowedPublicKey = nil;
53
+    SecCertificateRef allowedCertificate;
54
+    SecCertificateRef allowedCertificates[1];
55
+    CFArrayRef tempCertificates = nil;
56
+    SecPolicyRef policy = nil;
57
+    SecTrustRef allowedTrust = nil;
58
+    SecTrustResultType result;
59
+
60
+    allowedCertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificate);
61
+    __Require_Quiet(allowedCertificate != NULL, _out);
62
+
63
+    allowedCertificates[0] = allowedCertificate;
64
+    tempCertificates = CFArrayCreate(NULL, (const void **)allowedCertificates, 1, NULL);
65
+
66
+    policy = SecPolicyCreateBasicX509();
67
+    __Require_noErr_Quiet(SecTrustCreateWithCertificates(tempCertificates, policy, &allowedTrust), _out);
68
+    __Require_noErr_Quiet(SecTrustEvaluate(allowedTrust, &result), _out);
69
+
70
+    allowedPublicKey = (__bridge_transfer id)SecTrustCopyPublicKey(allowedTrust);
71
+
72
+_out:
73
+    if (allowedTrust) {
74
+        CFRelease(allowedTrust);
75
+    }
76
+
77
+    if (policy) {
78
+        CFRelease(policy);
79
+    }
80
+
81
+    if (tempCertificates) {
82
+        CFRelease(tempCertificates);
83
+    }
84
+
85
+    if (allowedCertificate) {
86
+        CFRelease(allowedCertificate);
87
+    }
88
+
89
+    return allowedPublicKey;
90
+}
91
+
92
+static BOOL AFServerTrustIsValid(SecTrustRef serverTrust) {
93
+    BOOL isValid = NO;
94
+    SecTrustResultType result;
95
+    __Require_noErr_Quiet(SecTrustEvaluate(serverTrust, &result), _out);
96
+
97
+    isValid = (result == kSecTrustResultUnspecified || result == kSecTrustResultProceed);
98
+
99
+_out:
100
+    return isValid;
101
+}
102
+
103
+static NSArray * AFCertificateTrustChainForServerTrust(SecTrustRef serverTrust) {
104
+    CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust);
105
+    NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:(NSUInteger)certificateCount];
106
+
107
+    for (CFIndex i = 0; i < certificateCount; i++) {
108
+        SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i);
109
+        [trustChain addObject:(__bridge_transfer NSData *)SecCertificateCopyData(certificate)];
110
+    }
111
+
112
+    return [NSArray arrayWithArray:trustChain];
113
+}
114
+
115
+static NSArray * AFPublicKeyTrustChainForServerTrust(SecTrustRef serverTrust) {
116
+    SecPolicyRef policy = SecPolicyCreateBasicX509();
117
+    CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust);
118
+    NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:(NSUInteger)certificateCount];
119
+    for (CFIndex i = 0; i < certificateCount; i++) {
120
+        SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i);
121
+
122
+        SecCertificateRef someCertificates[] = {certificate};
123
+        CFArrayRef certificates = CFArrayCreate(NULL, (const void **)someCertificates, 1, NULL);
124
+
125
+        SecTrustRef trust;
126
+        __Require_noErr_Quiet(SecTrustCreateWithCertificates(certificates, policy, &trust), _out);
127
+
128
+        SecTrustResultType result;
129
+        __Require_noErr_Quiet(SecTrustEvaluate(trust, &result), _out);
130
+
131
+        [trustChain addObject:(__bridge_transfer id)SecTrustCopyPublicKey(trust)];
132
+
133
+    _out:
134
+        if (trust) {
135
+            CFRelease(trust);
136
+        }
137
+
138
+        if (certificates) {
139
+            CFRelease(certificates);
140
+        }
141
+
142
+        continue;
143
+    }
144
+    CFRelease(policy);
145
+
146
+    return [NSArray arrayWithArray:trustChain];
147
+}
148
+
149
+#pragma mark -
150
+
151
+@interface AFSecurityPolicy()
152
+@property (readwrite, nonatomic, assign) AFSSLPinningMode SSLPinningMode;
153
+@property (readwrite, nonatomic, strong) NSSet *pinnedPublicKeys;
154
+@end
155
+
156
+@implementation AFSecurityPolicy
157
+
158
++ (NSSet *)certificatesInBundle:(NSBundle *)bundle {
159
+    NSArray *paths = [bundle pathsForResourcesOfType:@"cer" inDirectory:@"www/certificates"];
160
+    NSMutableSet *certificates = [NSMutableSet setWithCapacity:[paths count]];
161
+
162
+    for (NSString *path in paths) {
163
+        NSData *certificateData = [NSData dataWithContentsOfFile:path];
164
+        [certificates addObject:certificateData];
165
+    }
166
+
167
+    return [NSSet setWithSet:certificates];
168
+}
169
+
170
++ (NSSet *)defaultPinnedCertificates {
171
+    static NSSet *_defaultPinnedCertificates = nil;
172
+    static dispatch_once_t onceToken;
173
+    dispatch_once(&onceToken, ^{
174
+        NSBundle *bundle = [NSBundle bundleForClass:[self class]];
175
+        _defaultPinnedCertificates = [self certificatesInBundle:bundle];
176
+    });
177
+
178
+    return _defaultPinnedCertificates;
179
+}
180
+
181
++ (instancetype)defaultPolicy {
182
+    AFSecurityPolicy *securityPolicy = [[self alloc] init];
183
+    securityPolicy.SSLPinningMode = AFSSLPinningModeNone;
184
+
185
+    return securityPolicy;
186
+}
187
+
188
++ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode {
189
+    return [self policyWithPinningMode:pinningMode withPinnedCertificates:[self defaultPinnedCertificates]];
190
+}
191
+
192
++ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode withPinnedCertificates:(NSSet *)pinnedCertificates {
193
+    AFSecurityPolicy *securityPolicy = [[self alloc] init];
194
+    securityPolicy.SSLPinningMode = pinningMode;
195
+
196
+    [securityPolicy setPinnedCertificates:pinnedCertificates];
197
+
198
+    return securityPolicy;
199
+}
200
+
201
+- (instancetype)init {
202
+    self = [super init];
203
+    if (!self) {
204
+        return nil;
205
+    }
206
+
207
+    self.validatesDomainName = YES;
208
+
209
+    return self;
210
+}
211
+
212
+- (void)setPinnedCertificates:(NSSet *)pinnedCertificates {
213
+    _pinnedCertificates = pinnedCertificates;
214
+
215
+    if (self.pinnedCertificates) {
216
+        NSMutableSet *mutablePinnedPublicKeys = [NSMutableSet setWithCapacity:[self.pinnedCertificates count]];
217
+        for (NSData *certificate in self.pinnedCertificates) {
218
+            id publicKey = AFPublicKeyForCertificate(certificate);
219
+            if (!publicKey) {
220
+                continue;
221
+            }
222
+            [mutablePinnedPublicKeys addObject:publicKey];
223
+        }
224
+        self.pinnedPublicKeys = [NSSet setWithSet:mutablePinnedPublicKeys];
225
+    } else {
226
+        self.pinnedPublicKeys = nil;
227
+    }
228
+}
229
+
230
+#pragma mark -
231
+
232
+- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust
233
+                  forDomain:(NSString *)domain
234
+{
235
+    if (domain && self.allowInvalidCertificates && self.validatesDomainName && (self.SSLPinningMode == AFSSLPinningModeNone || [self.pinnedCertificates count] == 0)) {
236
+        // https://developer.apple.com/library/mac/documentation/NetworkingInternet/Conceptual/NetworkingTopics/Articles/OverridingSSLChainValidationCorrectly.html
237
+        //  According to the docs, you should only trust your provided certs for evaluation.
238
+        //  Pinned certificates are added to the trust. Without pinned certificates,
239
+        //  there is nothing to evaluate against.
240
+        //
241
+        //  From Apple Docs:
242
+        //          "Do not implicitly trust self-signed certificates as anchors (kSecTrustOptionImplicitAnchors).
243
+        //           Instead, add your own (self-signed) CA certificate to the list of trusted anchors."
244
+        NSLog(@"In order to validate a domain name for self signed certificates, you MUST use pinning.");
245
+        return NO;
246
+    }
247
+
248
+    NSMutableArray *policies = [NSMutableArray array];
249
+    if (self.validatesDomainName) {
250
+        [policies addObject:(__bridge_transfer id)SecPolicyCreateSSL(true, (__bridge CFStringRef)domain)];
251
+    } else {
252
+        [policies addObject:(__bridge_transfer id)SecPolicyCreateBasicX509()];
253
+    }
254
+
255
+    SecTrustSetPolicies(serverTrust, (__bridge CFArrayRef)policies);
256
+
257
+    if (self.SSLPinningMode == AFSSLPinningModeNone) {
258
+        return self.allowInvalidCertificates || AFServerTrustIsValid(serverTrust);
259
+    } else if (!AFServerTrustIsValid(serverTrust) && !self.allowInvalidCertificates) {
260
+        return NO;
261
+    }
262
+
263
+    switch (self.SSLPinningMode) {
264
+        case AFSSLPinningModeNone:
265
+        default:
266
+            return NO;
267
+        case AFSSLPinningModeCertificate: {
268
+            NSMutableArray *pinnedCertificates = [NSMutableArray array];
269
+            for (NSData *certificateData in self.pinnedCertificates) {
270
+                [pinnedCertificates addObject:(__bridge_transfer id)SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificateData)];
271
+            }
272
+            SecTrustSetAnchorCertificates(serverTrust, (__bridge CFArrayRef)pinnedCertificates);
273
+
274
+            if (!AFServerTrustIsValid(serverTrust)) {
275
+                return NO;
276
+            }
277
+
278
+            // obtain the chain after being validated, which *should* contain the pinned certificate in the last position (if it's the Root CA)
279
+            NSArray *serverCertificates = AFCertificateTrustChainForServerTrust(serverTrust);
280
+
281
+            for (NSData *trustChainCertificate in [serverCertificates reverseObjectEnumerator]) {
282
+                if ([self.pinnedCertificates containsObject:trustChainCertificate]) {
283
+                    return YES;
284
+                }
285
+            }
286
+
287
+            return NO;
288
+        }
289
+        case AFSSLPinningModePublicKey: {
290
+            NSUInteger trustedPublicKeyCount = 0;
291
+            NSArray *publicKeys = AFPublicKeyTrustChainForServerTrust(serverTrust);
292
+
293
+            for (id trustChainPublicKey in publicKeys) {
294
+                for (id pinnedPublicKey in self.pinnedPublicKeys) {
295
+                    if (AFSecKeyIsEqualToKey((__bridge SecKeyRef)trustChainPublicKey, (__bridge SecKeyRef)pinnedPublicKey)) {
296
+                        trustedPublicKeyCount += 1;
297
+                    }
298
+                }
299
+            }
300
+            return trustedPublicKeyCount > 0;
301
+        }
302
+    }
303
+
304
+    return NO;
305
+}
306
+
307
+#pragma mark - NSKeyValueObserving
308
+
309
++ (NSSet *)keyPathsForValuesAffectingPinnedPublicKeys {
310
+    return [NSSet setWithObject:@"pinnedCertificates"];
311
+}
312
+
313
+#pragma mark - NSSecureCoding
314
+
315
++ (BOOL)supportsSecureCoding {
316
+    return YES;
317
+}
318
+
319
+- (instancetype)initWithCoder:(NSCoder *)decoder {
320
+
321
+    self = [self init];
322
+    if (!self) {
323
+        return nil;
324
+    }
325
+
326
+    self.SSLPinningMode = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(SSLPinningMode))] unsignedIntegerValue];
327
+    self.allowInvalidCertificates = [decoder decodeBoolForKey:NSStringFromSelector(@selector(allowInvalidCertificates))];
328
+    self.validatesDomainName = [decoder decodeBoolForKey:NSStringFromSelector(@selector(validatesDomainName))];
329
+    self.pinnedCertificates = [decoder decodeObjectOfClass:[NSArray class] forKey:NSStringFromSelector(@selector(pinnedCertificates))];
330
+
331
+    return self;
332
+}
333
+
334
+- (void)encodeWithCoder:(NSCoder *)coder {
335
+    [coder encodeObject:[NSNumber numberWithUnsignedInteger:self.SSLPinningMode] forKey:NSStringFromSelector(@selector(SSLPinningMode))];
336
+    [coder encodeBool:self.allowInvalidCertificates forKey:NSStringFromSelector(@selector(allowInvalidCertificates))];
337
+    [coder encodeBool:self.validatesDomainName forKey:NSStringFromSelector(@selector(validatesDomainName))];
338
+    [coder encodeObject:self.pinnedCertificates forKey:NSStringFromSelector(@selector(pinnedCertificates))];
339
+}
340
+
341
+#pragma mark - NSCopying
342
+
343
+- (instancetype)copyWithZone:(NSZone *)zone {
344
+    AFSecurityPolicy *securityPolicy = [[[self class] allocWithZone:zone] init];
345
+    securityPolicy.SSLPinningMode = self.SSLPinningMode;
346
+    securityPolicy.allowInvalidCertificates = self.allowInvalidCertificates;
347
+    securityPolicy.validatesDomainName = self.validatesDomainName;
348
+    securityPolicy.pinnedCertificates = [self.pinnedCertificates copyWithZone:zone];
349
+
350
+    return securityPolicy;
351
+}
352
+
353
+@end

+ 479
- 0
node_modules/cordova-plugin-advanced-http/src/ios/AFNetworking/AFURLRequestSerialization.h Visa fil

@@ -0,0 +1,479 @@
1
+// AFURLRequestSerialization.h
2
+// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3
+//
4
+// Permission is hereby granted, free of charge, to any person obtaining a copy
5
+// of this software and associated documentation files (the "Software"), to deal
6
+// in the Software without restriction, including without limitation the rights
7
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+// copies of the Software, and to permit persons to whom the Software is
9
+// furnished to do so, subject to the following conditions:
10
+//
11
+// The above copyright notice and this permission notice shall be included in
12
+// all copies or substantial portions of the Software.
13
+//
14
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20
+// THE SOFTWARE.
21
+
22
+#import <Foundation/Foundation.h>
23
+#import <TargetConditionals.h>
24
+
25
+#if TARGET_OS_IOS || TARGET_OS_TV
26
+#import <UIKit/UIKit.h>
27
+#elif TARGET_OS_WATCH
28
+#import <WatchKit/WatchKit.h>
29
+#endif
30
+
31
+NS_ASSUME_NONNULL_BEGIN
32
+
33
+/**
34
+ Returns a percent-escaped string following RFC 3986 for a query string key or value.
35
+ RFC 3986 states that the following characters are "reserved" characters.
36
+ - General Delimiters: ":", "#", "[", "]", "@", "?", "/"
37
+ - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
38
+
39
+ In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow
40
+ query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/"
41
+ should be percent-escaped in the query string.
42
+ 
43
+ @param string The string to be percent-escaped.
44
+ 
45
+ @return The percent-escaped string.
46
+ */
47
+FOUNDATION_EXPORT NSString * AFPercentEscapedStringFromString(NSString *string);
48
+
49
+/**
50
+ A helper method to generate encoded url query parameters for appending to the end of a URL.
51
+
52
+ @param parameters A dictionary of key/values to be encoded.
53
+
54
+ @return A url encoded query string
55
+ */
56
+FOUNDATION_EXPORT NSString * AFQueryStringFromParameters(NSDictionary *parameters);
57
+
58
+/**
59
+ The `AFURLRequestSerialization` protocol is adopted by an object that encodes parameters for a specified HTTP requests. Request serializers may encode parameters as query strings, HTTP bodies, setting the appropriate HTTP header fields as necessary.
60
+
61
+ For example, a JSON request serializer may set the HTTP body of the request to a JSON representation, and set the `Content-Type` HTTP header field value to `application/json`.
62
+ */
63
+@protocol AFURLRequestSerialization <NSObject, NSSecureCoding, NSCopying>
64
+
65
+/**
66
+ Returns a request with the specified parameters encoded into a copy of the original request.
67
+
68
+ @param request The original request.
69
+ @param parameters The parameters to be encoded.
70
+ @param error The error that occurred while attempting to encode the request parameters.
71
+
72
+ @return A serialized request.
73
+ */
74
+- (nullable NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
75
+                               withParameters:(nullable id)parameters
76
+                                        error:(NSError * _Nullable __autoreleasing *)error NS_SWIFT_NOTHROW;
77
+
78
+@end
79
+
80
+#pragma mark -
81
+
82
+/**
83
+
84
+ */
85
+typedef NS_ENUM(NSUInteger, AFHTTPRequestQueryStringSerializationStyle) {
86
+    AFHTTPRequestQueryStringDefaultStyle = 0,
87
+};
88
+
89
+@protocol AFMultipartFormData;
90
+
91
+/**
92
+ `AFHTTPRequestSerializer` conforms to the `AFURLRequestSerialization` & `AFURLResponseSerialization` protocols, offering a concrete base implementation of query string / URL form-encoded parameter serialization and default request headers, as well as response status code and content type validation.
93
+
94
+ Any request or response serializer dealing with HTTP is encouraged to subclass `AFHTTPRequestSerializer` in order to ensure consistent default behavior.
95
+ */
96
+@interface AFHTTPRequestSerializer : NSObject <AFURLRequestSerialization>
97
+
98
+/**
99
+ The string encoding used to serialize parameters. `NSUTF8StringEncoding` by default.
100
+ */
101
+@property (nonatomic, assign) NSStringEncoding stringEncoding;
102
+
103
+/**
104
+ Whether created requests can use the device’s cellular radio (if present). `YES` by default.
105
+
106
+ @see NSMutableURLRequest -setAllowsCellularAccess:
107
+ */
108
+@property (nonatomic, assign) BOOL allowsCellularAccess;
109
+
110
+/**
111
+ The cache policy of created requests. `NSURLRequestUseProtocolCachePolicy` by default.
112
+
113
+ @see NSMutableURLRequest -setCachePolicy:
114
+ */
115
+@property (nonatomic, assign) NSURLRequestCachePolicy cachePolicy;
116
+
117
+/**
118
+ Whether created requests should use the default cookie handling. `YES` by default.
119
+
120
+ @see NSMutableURLRequest -setHTTPShouldHandleCookies:
121
+ */
122
+@property (nonatomic, assign) BOOL HTTPShouldHandleCookies;
123
+
124
+/**
125
+ Whether created requests can continue transmitting data before receiving a response from an earlier transmission. `NO` by default
126
+
127
+ @see NSMutableURLRequest -setHTTPShouldUsePipelining:
128
+ */
129
+@property (nonatomic, assign) BOOL HTTPShouldUsePipelining;
130
+
131
+/**
132
+ The network service type for created requests. `NSURLNetworkServiceTypeDefault` by default.
133
+
134
+ @see NSMutableURLRequest -setNetworkServiceType:
135
+ */
136
+@property (nonatomic, assign) NSURLRequestNetworkServiceType networkServiceType;
137
+
138
+/**
139
+ The timeout interval, in seconds, for created requests. The default timeout interval is 60 seconds.
140
+
141
+ @see NSMutableURLRequest -setTimeoutInterval:
142
+ */
143
+@property (nonatomic, assign) NSTimeInterval timeoutInterval;
144
+
145
+///---------------------------------------
146
+/// @name Configuring HTTP Request Headers
147
+///---------------------------------------
148
+
149
+/**
150
+ Default HTTP header field values to be applied to serialized requests. By default, these include the following:
151
+
152
+ - `Accept-Language` with the contents of `NSLocale +preferredLanguages`
153
+ - `User-Agent` with the contents of various bundle identifiers and OS designations
154
+
155
+ @discussion To add or remove default request headers, use `setValue:forHTTPHeaderField:`.
156
+ */
157
+@property (readonly, nonatomic, strong) NSDictionary <NSString *, NSString *> *HTTPRequestHeaders;
158
+
159
+/**
160
+ Creates and returns a serializer with default configuration.
161
+ */
162
++ (instancetype)serializer;
163
+
164
+/**
165
+ Sets the value for the HTTP headers set in request objects made by the HTTP client. If `nil`, removes the existing value for that header.
166
+
167
+ @param field The HTTP header to set a default value for
168
+ @param value The value set as default for the specified header, or `nil`
169
+ */
170
+- (void)setValue:(nullable NSString *)value
171
+forHTTPHeaderField:(NSString *)field;
172
+
173
+/**
174
+ Returns the value for the HTTP headers set in the request serializer.
175
+
176
+ @param field The HTTP header to retrieve the default value for
177
+
178
+ @return The value set as default for the specified header, or `nil`
179
+ */
180
+- (nullable NSString *)valueForHTTPHeaderField:(NSString *)field;
181
+
182
+/**
183
+ Sets the "Authorization" HTTP header set in request objects made by the HTTP client to a basic authentication value with Base64-encoded username and password. This overwrites any existing value for this header.
184
+
185
+ @param username The HTTP basic auth username
186
+ @param password The HTTP basic auth password
187
+ */
188
+- (void)setAuthorizationHeaderFieldWithUsername:(NSString *)username
189
+                                       password:(NSString *)password;
190
+
191
+/**
192
+ Clears any existing value for the "Authorization" HTTP header.
193
+ */
194
+- (void)clearAuthorizationHeader;
195
+
196
+///-------------------------------------------------------
197
+/// @name Configuring Query String Parameter Serialization
198
+///-------------------------------------------------------
199
+
200
+/**
201
+ HTTP methods for which serialized requests will encode parameters as a query string. `GET`, `HEAD`, and `DELETE` by default.
202
+ */
203
+@property (nonatomic, strong) NSSet <NSString *> *HTTPMethodsEncodingParametersInURI;
204
+
205
+/**
206
+ Set the method of query string serialization according to one of the pre-defined styles.
207
+
208
+ @param style The serialization style.
209
+
210
+ @see AFHTTPRequestQueryStringSerializationStyle
211
+ */
212
+- (void)setQueryStringSerializationWithStyle:(AFHTTPRequestQueryStringSerializationStyle)style;
213
+
214
+/**
215
+ Set the a custom method of query string serialization according to the specified block.
216
+
217
+ @param block A block that defines a process of encoding parameters into a query string. This block returns the query string and takes three arguments: the request, the parameters to encode, and the error that occurred when attempting to encode parameters for the given request.
218
+ */
219
+- (void)setQueryStringSerializationWithBlock:(nullable NSString * (^)(NSURLRequest *request, id parameters, NSError * __autoreleasing *error))block;
220
+
221
+///-------------------------------
222
+/// @name Creating Request Objects
223
+///-------------------------------
224
+
225
+/**
226
+ Creates an `NSMutableURLRequest` object with the specified HTTP method and URL string.
227
+
228
+ If the HTTP method is `GET`, `HEAD`, or `DELETE`, the parameters will be used to construct a url-encoded query string that is appended to the request's URL. Otherwise, the parameters will be encoded according to the value of the `parameterEncoding` property, and set as the request body.
229
+
230
+ @param method The HTTP method for the request, such as `GET`, `POST`, `PUT`, or `DELETE`. This parameter must not be `nil`.
231
+ @param URLString The URL string used to create the request URL.
232
+ @param parameters The parameters to be either set as a query string for `GET` requests, or the request HTTP body.
233
+ @param error The error that occurred while constructing the request.
234
+
235
+ @return An `NSMutableURLRequest` object.
236
+ */
237
+- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
238
+                                 URLString:(NSString *)URLString
239
+                                parameters:(nullable id)parameters
240
+                                     error:(NSError * _Nullable __autoreleasing *)error;
241
+
242
+/**
243
+ Creates an `NSMutableURLRequest` object with the specified HTTP method and URLString, and constructs a `multipart/form-data` HTTP body, using the specified parameters and multipart form data block. See http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.2
244
+
245
+ Multipart form requests are automatically streamed, reading files directly from disk along with in-memory data in a single HTTP body. The resulting `NSMutableURLRequest` object has an `HTTPBodyStream` property, so refrain from setting `HTTPBodyStream` or `HTTPBody` on this request object, as it will clear out the multipart form body stream.
246
+
247
+ @param method The HTTP method for the request. This parameter must not be `GET` or `HEAD`, or `nil`.
248
+ @param URLString The URL string used to create the request URL.
249
+ @param parameters The parameters to be encoded and set in the request HTTP body.
250
+ @param block A block that takes a single argument and appends data to the HTTP body. The block argument is an object adopting the `AFMultipartFormData` protocol.
251
+ @param error The error that occurred while constructing the request.
252
+
253
+ @return An `NSMutableURLRequest` object
254
+ */
255
+- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method
256
+                                              URLString:(NSString *)URLString
257
+                                             parameters:(nullable NSDictionary <NSString *, id> *)parameters
258
+                              constructingBodyWithBlock:(nullable void (^)(id <AFMultipartFormData> formData))block
259
+                                                  error:(NSError * _Nullable __autoreleasing *)error;
260
+
261
+/**
262
+ Creates an `NSMutableURLRequest` by removing the `HTTPBodyStream` from a request, and asynchronously writing its contents into the specified file, invoking the completion handler when finished.
263
+
264
+ @param request The multipart form request. The `HTTPBodyStream` property of `request` must not be `nil`.
265
+ @param fileURL The file URL to write multipart form contents to.
266
+ @param handler A handler block to execute.
267
+
268
+ @discussion There is a bug in `NSURLSessionTask` that causes requests to not send a `Content-Length` header when streaming contents from an HTTP body, which is notably problematic when interacting with the Amazon S3 webservice. As a workaround, this method takes a request constructed with `multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:error:`, or any other request with an `HTTPBodyStream`, writes the contents to the specified file and returns a copy of the original request with the `HTTPBodyStream` property set to `nil`. From here, the file can either be passed to `AFURLSessionManager -uploadTaskWithRequest:fromFile:progress:completionHandler:`, or have its contents read into an `NSData` that's assigned to the `HTTPBody` property of the request.
269
+
270
+ @see https://github.com/AFNetworking/AFNetworking/issues/1398
271
+ */
272
+- (NSMutableURLRequest *)requestWithMultipartFormRequest:(NSURLRequest *)request
273
+                             writingStreamContentsToFile:(NSURL *)fileURL
274
+                                       completionHandler:(nullable void (^)(NSError * _Nullable error))handler;
275
+
276
+@end
277
+
278
+#pragma mark -
279
+
280
+/**
281
+ The `AFMultipartFormData` protocol defines the methods supported by the parameter in the block argument of `AFHTTPRequestSerializer -multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:`.
282
+ */
283
+@protocol AFMultipartFormData
284
+
285
+/**
286
+ Appends the HTTP header `Content-Disposition: file; filename=#{generated filename}; name=#{name}"` and `Content-Type: #{generated mimeType}`, followed by the encoded file data and the multipart form boundary.
287
+
288
+ The filename and MIME type for this data in the form will be automatically generated, using the last path component of the `fileURL` and system associated MIME type for the `fileURL` extension, respectively.
289
+
290
+ @param fileURL The URL corresponding to the file whose content will be appended to the form. This parameter must not be `nil`.
291
+ @param name The name to be associated with the specified data. This parameter must not be `nil`.
292
+ @param error If an error occurs, upon return contains an `NSError` object that describes the problem.
293
+
294
+ @return `YES` if the file data was successfully appended, otherwise `NO`.
295
+ */
296
+- (BOOL)appendPartWithFileURL:(NSURL *)fileURL
297
+                         name:(NSString *)name
298
+                        error:(NSError * _Nullable __autoreleasing *)error;
299
+
300
+/**
301
+ Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the encoded file data and the multipart form boundary.
302
+
303
+ @param fileURL The URL corresponding to the file whose content will be appended to the form. This parameter must not be `nil`.
304
+ @param name The name to be associated with the specified data. This parameter must not be `nil`.
305
+ @param fileName The file name to be used in the `Content-Disposition` header. This parameter must not be `nil`.
306
+ @param mimeType The declared MIME type of the file data. This parameter must not be `nil`.
307
+ @param error If an error occurs, upon return contains an `NSError` object that describes the problem.
308
+
309
+ @return `YES` if the file data was successfully appended otherwise `NO`.
310
+ */
311
+- (BOOL)appendPartWithFileURL:(NSURL *)fileURL
312
+                         name:(NSString *)name
313
+                     fileName:(NSString *)fileName
314
+                     mimeType:(NSString *)mimeType
315
+                        error:(NSError * _Nullable __autoreleasing *)error;
316
+
317
+/**
318
+ Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the data from the input stream and the multipart form boundary.
319
+
320
+ @param inputStream The input stream to be appended to the form data
321
+ @param name The name to be associated with the specified input stream. This parameter must not be `nil`.
322
+ @param fileName The filename to be associated with the specified input stream. This parameter must not be `nil`.
323
+ @param length The length of the specified input stream in bytes.
324
+ @param mimeType The MIME type of the specified data. (For example, the MIME type for a JPEG image is image/jpeg.) For a list of valid MIME types, see http://www.iana.org/assignments/media-types/. This parameter must not be `nil`.
325
+ */
326
+- (void)appendPartWithInputStream:(nullable NSInputStream *)inputStream
327
+                             name:(NSString *)name
328
+                         fileName:(NSString *)fileName
329
+                           length:(int64_t)length
330
+                         mimeType:(NSString *)mimeType;
331
+
332
+/**
333
+ Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the encoded file data and the multipart form boundary.
334
+
335
+ @param data The data to be encoded and appended to the form data.
336
+ @param name The name to be associated with the specified data. This parameter must not be `nil`.
337
+ @param fileName The filename to be associated with the specified data. This parameter must not be `nil`.
338
+ @param mimeType The MIME type of the specified data. (For example, the MIME type for a JPEG image is image/jpeg.) For a list of valid MIME types, see http://www.iana.org/assignments/media-types/. This parameter must not be `nil`.
339
+ */
340
+- (void)appendPartWithFileData:(NSData *)data
341
+                          name:(NSString *)name
342
+                      fileName:(NSString *)fileName
343
+                      mimeType:(NSString *)mimeType;
344
+
345
+/**
346
+ Appends the HTTP headers `Content-Disposition: form-data; name=#{name}"`, followed by the encoded data and the multipart form boundary.
347
+
348
+ @param data The data to be encoded and appended to the form data.
349
+ @param name The name to be associated with the specified data. This parameter must not be `nil`.
350
+ */
351
+
352
+- (void)appendPartWithFormData:(NSData *)data
353
+                          name:(NSString *)name;
354
+
355
+
356
+/**
357
+ Appends HTTP headers, followed by the encoded data and the multipart form boundary.
358
+
359
+ @param headers The HTTP headers to be appended to the form data.
360
+ @param body The data to be encoded and appended to the form data. This parameter must not be `nil`.
361
+ */
362
+- (void)appendPartWithHeaders:(nullable NSDictionary <NSString *, NSString *> *)headers
363
+                         body:(NSData *)body;
364
+
365
+/**
366
+ Throttles request bandwidth by limiting the packet size and adding a delay for each chunk read from the upload stream.
367
+
368
+ When uploading over a 3G or EDGE connection, requests may fail with "request body stream exhausted". Setting a maximum packet size and delay according to the recommended values (`kAFUploadStream3GSuggestedPacketSize` and `kAFUploadStream3GSuggestedDelay`) lowers the risk of the input stream exceeding its allocated bandwidth. Unfortunately, there is no definite way to distinguish between a 3G, EDGE, or LTE connection over `NSURLConnection`. As such, it is not recommended that you throttle bandwidth based solely on network reachability. Instead, you should consider checking for the "request body stream exhausted" in a failure block, and then retrying the request with throttled bandwidth.
369
+
370
+ @param numberOfBytes Maximum packet size, in number of bytes. The default packet size for an input stream is 16kb.
371
+ @param delay Duration of delay each time a packet is read. By default, no delay is set.
372
+ */
373
+- (void)throttleBandwidthWithPacketSize:(NSUInteger)numberOfBytes
374
+                                  delay:(NSTimeInterval)delay;
375
+
376
+@end
377
+
378
+#pragma mark -
379
+
380
+/**
381
+ `AFJSONRequestSerializer` is a subclass of `AFHTTPRequestSerializer` that encodes parameters as JSON using `NSJSONSerialization`, setting the `Content-Type` of the encoded request to `application/json`.
382
+ */
383
+@interface AFJSONRequestSerializer : AFHTTPRequestSerializer
384
+
385
+/**
386
+ Options for writing the request JSON data from Foundation objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONWritingOptions". `0` by default.
387
+ */
388
+@property (nonatomic, assign) NSJSONWritingOptions writingOptions;
389
+
390
+/**
391
+ Creates and returns a JSON serializer with specified reading and writing options.
392
+
393
+ @param writingOptions The specified JSON writing options.
394
+ */
395
++ (instancetype)serializerWithWritingOptions:(NSJSONWritingOptions)writingOptions;
396
+
397
+@end
398
+
399
+#pragma mark -
400
+
401
+/**
402
+ `AFPropertyListRequestSerializer` is a subclass of `AFHTTPRequestSerializer` that encodes parameters as JSON using `NSPropertyListSerializer`, setting the `Content-Type` of the encoded request to `application/x-plist`.
403
+ */
404
+@interface AFPropertyListRequestSerializer : AFHTTPRequestSerializer
405
+
406
+/**
407
+ The property list format. Possible values are described in "NSPropertyListFormat".
408
+ */
409
+@property (nonatomic, assign) NSPropertyListFormat format;
410
+
411
+/**
412
+ @warning The `writeOptions` property is currently unused.
413
+ */
414
+@property (nonatomic, assign) NSPropertyListWriteOptions writeOptions;
415
+
416
+/**
417
+ Creates and returns a property list serializer with a specified format, read options, and write options.
418
+
419
+ @param format The property list format.
420
+ @param writeOptions The property list write options.
421
+
422
+ @warning The `writeOptions` property is currently unused.
423
+ */
424
++ (instancetype)serializerWithFormat:(NSPropertyListFormat)format
425
+                        writeOptions:(NSPropertyListWriteOptions)writeOptions;
426
+
427
+@end
428
+
429
+#pragma mark -
430
+
431
+///----------------
432
+/// @name Constants
433
+///----------------
434
+
435
+/**
436
+ ## Error Domains
437
+
438
+ The following error domain is predefined.
439
+
440
+ - `NSString * const AFURLRequestSerializationErrorDomain`
441
+
442
+ ### Constants
443
+
444
+ `AFURLRequestSerializationErrorDomain`
445
+ AFURLRequestSerializer errors. Error codes for `AFURLRequestSerializationErrorDomain` correspond to codes in `NSURLErrorDomain`.
446
+ */
447
+FOUNDATION_EXPORT NSString * const AFURLRequestSerializationErrorDomain;
448
+
449
+/**
450
+ ## User info dictionary keys
451
+
452
+ These keys may exist in the user info dictionary, in addition to those defined for NSError.
453
+
454
+ - `NSString * const AFNetworkingOperationFailingURLRequestErrorKey`
455
+
456
+ ### Constants
457
+
458
+ `AFNetworkingOperationFailingURLRequestErrorKey`
459
+ The corresponding value is an `NSURLRequest` containing the request of the operation associated with an error. This key is only present in the `AFURLRequestSerializationErrorDomain`.
460
+ */
461
+FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLRequestErrorKey;
462
+
463
+/**
464
+ ## Throttling Bandwidth for HTTP Request Input Streams
465
+
466
+ @see -throttleBandwidthWithPacketSize:delay:
467
+
468
+ ### Constants
469
+
470
+ `kAFUploadStream3GSuggestedPacketSize`
471
+ Maximum packet size, in number of bytes. Equal to 16kb.
472
+
473
+ `kAFUploadStream3GSuggestedDelay`
474
+ Duration of delay each time a packet is read. Equal to 0.2 seconds.
475
+ */
476
+FOUNDATION_EXPORT NSUInteger const kAFUploadStream3GSuggestedPacketSize;
477
+FOUNDATION_EXPORT NSTimeInterval const kAFUploadStream3GSuggestedDelay;
478
+
479
+NS_ASSUME_NONNULL_END

+ 1355
- 0
node_modules/cordova-plugin-advanced-http/src/ios/AFNetworking/AFURLRequestSerialization.m
Filskillnaden har hållits tillbaka eftersom den är för stor
Visa fil


+ 318
- 0
node_modules/cordova-plugin-advanced-http/src/ios/AFNetworking/AFURLResponseSerialization.h Visa fil

@@ -0,0 +1,318 @@
1
+// AFURLResponseSerialization.h
2
+// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3
+//
4
+// Permission is hereby granted, free of charge, to any person obtaining a copy
5
+// of this software and associated documentation files (the "Software"), to deal
6
+// in the Software without restriction, including without limitation the rights
7
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+// copies of the Software, and to permit persons to whom the Software is
9
+// furnished to do so, subject to the following conditions:
10
+//
11
+// The above copyright notice and this permission notice shall be included in
12
+// all copies or substantial portions of the Software.
13
+//
14
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20
+// THE SOFTWARE.
21
+
22
+#import <Foundation/Foundation.h>
23
+#import <CoreGraphics/CoreGraphics.h>
24
+
25
+NS_ASSUME_NONNULL_BEGIN
26
+
27
+/**
28
+ The `AFURLResponseSerialization` protocol is adopted by an object that decodes data into a more useful object representation, according to details in the server response. Response serializers may additionally perform validation on the incoming response and data.
29
+
30
+ For example, a JSON response serializer may check for an acceptable status code (`2XX` range) and content type (`application/json`), decoding a valid JSON response into an object.
31
+ */
32
+@protocol AFURLResponseSerialization <NSObject, NSSecureCoding, NSCopying>
33
+
34
+/**
35
+ The response object decoded from the data associated with a specified response.
36
+
37
+ @param response The response to be processed.
38
+ @param data The response data to be decoded.
39
+ @param error The error that occurred while attempting to decode the response data.
40
+
41
+ @return The object decoded from the specified response data.
42
+ */
43
+- (nullable id)responseObjectForResponse:(nullable NSURLResponse *)response
44
+                           data:(nullable NSData *)data
45
+                          error:(NSError * _Nullable __autoreleasing *)error NS_SWIFT_NOTHROW;
46
+
47
+@end
48
+
49
+#pragma mark -
50
+
51
+/**
52
+ `AFHTTPResponseSerializer` conforms to the `AFURLRequestSerialization` & `AFURLResponseSerialization` protocols, offering a concrete base implementation of query string / URL form-encoded parameter serialization and default request headers, as well as response status code and content type validation.
53
+
54
+ Any request or response serializer dealing with HTTP is encouraged to subclass `AFHTTPResponseSerializer` in order to ensure consistent default behavior.
55
+ */
56
+@interface AFHTTPResponseSerializer : NSObject <AFURLResponseSerialization>
57
+
58
+- (instancetype)init;
59
+
60
+/**
61
+ The string encoding used to serialize data received from the server, when no string encoding is specified by the response. `NSUTF8StringEncoding` by default.
62
+ */
63
+@property (nonatomic, assign) NSStringEncoding stringEncoding;
64
+
65
+/**
66
+ Creates and returns a serializer with default configuration.
67
+ */
68
++ (instancetype)serializer;
69
+
70
+///-----------------------------------------
71
+/// @name Configuring Response Serialization
72
+///-----------------------------------------
73
+
74
+/**
75
+ The acceptable HTTP status codes for responses. When non-`nil`, responses with status codes not contained by the set will result in an error during validation.
76
+
77
+ See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
78
+ */
79
+@property (nonatomic, copy, nullable) NSIndexSet *acceptableStatusCodes;
80
+
81
+/**
82
+ The acceptable MIME types for responses. When non-`nil`, responses with a `Content-Type` with MIME types that do not intersect with the set will result in an error during validation.
83
+ */
84
+@property (nonatomic, copy, nullable) NSSet <NSString *> *acceptableContentTypes;
85
+
86
+/**
87
+ Validates the specified response and data.
88
+
89
+ In its base implementation, this method checks for an acceptable status code and content type. Subclasses may wish to add other domain-specific checks.
90
+
91
+ @param response The response to be validated.
92
+ @param data The data associated with the response.
93
+ @param error The error that occurred while attempting to validate the response.
94
+
95
+ @return `YES` if the response is valid, otherwise `NO`.
96
+ */
97
+- (BOOL)validateResponse:(nullable NSHTTPURLResponse *)response
98
+                    data:(nullable NSData *)data
99
+                   error:(NSError * _Nullable __autoreleasing *)error;
100
+
101
+@end
102
+
103
+#pragma mark -
104
+
105
+
106
+/**
107
+ `AFJSONResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes JSON responses.
108
+
109
+ By default, `AFJSONResponseSerializer` accepts the following MIME types, which includes the official standard, `application/json`, as well as other commonly-used types:
110
+
111
+ - `application/json`
112
+ - `text/json`
113
+ - `text/javascript`
114
+ */
115
+@interface AFJSONResponseSerializer : AFHTTPResponseSerializer
116
+
117
+- (instancetype)init;
118
+
119
+/**
120
+ Options for reading the response JSON data and creating the Foundation objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONReadingOptions". `0` by default.
121
+ */
122
+@property (nonatomic, assign) NSJSONReadingOptions readingOptions;
123
+
124
+/**
125
+ Whether to remove keys with `NSNull` values from response JSON. Defaults to `NO`.
126
+ */
127
+@property (nonatomic, assign) BOOL removesKeysWithNullValues;
128
+
129
+/**
130
+ Creates and returns a JSON serializer with specified reading and writing options.
131
+
132
+ @param readingOptions The specified JSON reading options.
133
+ */
134
++ (instancetype)serializerWithReadingOptions:(NSJSONReadingOptions)readingOptions;
135
+
136
+@end
137
+
138
+#pragma mark -
139
+
140
+/**
141
+ `AFXMLParserResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLParser` objects.
142
+
143
+ By default, `AFXMLParserResponseSerializer` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types:
144
+
145
+ - `application/xml`
146
+ - `text/xml`
147
+ */
148
+@interface AFXMLParserResponseSerializer : AFHTTPResponseSerializer
149
+
150
+@end
151
+
152
+#pragma mark -
153
+
154
+#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED
155
+
156
+/**
157
+ `AFXMLDocumentResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLDocument` objects.
158
+
159
+ By default, `AFXMLDocumentResponseSerializer` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types:
160
+
161
+ - `application/xml`
162
+ - `text/xml`
163
+ */
164
+@interface AFXMLDocumentResponseSerializer : AFHTTPResponseSerializer
165
+
166
+- (instancetype)init;
167
+
168
+/**
169
+ Input and output options specifically intended for `NSXMLDocument` objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONReadingOptions". `0` by default.
170
+ */
171
+@property (nonatomic, assign) NSUInteger options;
172
+
173
+/**
174
+ Creates and returns an XML document serializer with the specified options.
175
+
176
+ @param mask The XML document options.
177
+ */
178
++ (instancetype)serializerWithXMLDocumentOptions:(NSUInteger)mask;
179
+
180
+@end
181
+
182
+#endif
183
+
184
+#pragma mark -
185
+
186
+/**
187
+ `AFPropertyListResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLDocument` objects.
188
+
189
+ By default, `AFPropertyListResponseSerializer` accepts the following MIME types:
190
+
191
+ - `application/x-plist`
192
+ */
193
+@interface AFPropertyListResponseSerializer : AFHTTPResponseSerializer
194
+
195
+- (instancetype)init;
196
+
197
+/**
198
+ The property list format. Possible values are described in "NSPropertyListFormat".
199
+ */
200
+@property (nonatomic, assign) NSPropertyListFormat format;
201
+
202
+/**
203
+ The property list reading options. Possible values are described in "NSPropertyListMutabilityOptions."
204
+ */
205
+@property (nonatomic, assign) NSPropertyListReadOptions readOptions;
206
+
207
+/**
208
+ Creates and returns a property list serializer with a specified format, read options, and write options.
209
+
210
+ @param format The property list format.
211
+ @param readOptions The property list reading options.
212
+ */
213
++ (instancetype)serializerWithFormat:(NSPropertyListFormat)format
214
+                         readOptions:(NSPropertyListReadOptions)readOptions;
215
+
216
+@end
217
+
218
+#pragma mark -
219
+
220
+/**
221
+ `AFImageResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes image responses.
222
+
223
+ By default, `AFImageResponseSerializer` accepts the following MIME types, which correspond to the image formats supported by UIImage or NSImage:
224
+
225
+ - `image/tiff`
226
+ - `image/jpeg`
227
+ - `image/gif`
228
+ - `image/png`
229
+ - `image/ico`
230
+ - `image/x-icon`
231
+ - `image/bmp`
232
+ - `image/x-bmp`
233
+ - `image/x-xbitmap`
234
+ - `image/x-win-bitmap`
235
+ */
236
+@interface AFImageResponseSerializer : AFHTTPResponseSerializer
237
+
238
+#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
239
+/**
240
+ The scale factor used when interpreting the image data to construct `responseImage`. Specifying a scale factor of 1.0 results in an image whose size matches the pixel-based dimensions of the image. Applying a different scale factor changes the size of the image as reported by the size property. This is set to the value of scale of the main screen by default, which automatically scales images for retina displays, for instance.
241
+ */
242
+@property (nonatomic, assign) CGFloat imageScale;
243
+
244
+/**
245
+ Whether to automatically inflate response image data for compressed formats (such as PNG or JPEG). Enabling this can significantly improve drawing performance on iOS when used with `setCompletionBlockWithSuccess:failure:`, as it allows a bitmap representation to be constructed in the background rather than on the main thread. `YES` by default.
246
+ */
247
+@property (nonatomic, assign) BOOL automaticallyInflatesResponseImage;
248
+#endif
249
+
250
+@end
251
+
252
+#pragma mark -
253
+
254
+/**
255
+ `AFCompoundSerializer` is a subclass of `AFHTTPResponseSerializer` that delegates the response serialization to the first `AFHTTPResponseSerializer` object that returns an object for `responseObjectForResponse:data:error:`, falling back on the default behavior of `AFHTTPResponseSerializer`. This is useful for supporting multiple potential types and structures of server responses with a single serializer.
256
+ */
257
+@interface AFCompoundResponseSerializer : AFHTTPResponseSerializer
258
+
259
+/**
260
+ The component response serializers.
261
+ */
262
+@property (readonly, nonatomic, copy) NSArray <id<AFURLResponseSerialization>> *responseSerializers;
263
+
264
+/**
265
+ Creates and returns a compound serializer comprised of the specified response serializers.
266
+
267
+ @warning Each response serializer specified must be a subclass of `AFHTTPResponseSerializer`, and response to `-validateResponse:data:error:`.
268
+ */
269
++ (instancetype)compoundSerializerWithResponseSerializers:(NSArray <id<AFURLResponseSerialization>> *)responseSerializers;
270
+
271
+@end
272
+
273
+///----------------
274
+/// @name Constants
275
+///----------------
276
+
277
+/**
278
+ ## Error Domains
279
+
280
+ The following error domain is predefined.
281
+
282
+ - `NSString * const AFURLResponseSerializationErrorDomain`
283
+
284
+ ### Constants
285
+
286
+ `AFURLResponseSerializationErrorDomain`
287
+ AFURLResponseSerializer errors. Error codes for `AFURLResponseSerializationErrorDomain` correspond to codes in `NSURLErrorDomain`.
288
+ */
289
+FOUNDATION_EXPORT NSString * const AFURLResponseSerializationErrorDomain;
290
+
291
+/**
292
+ ## User info dictionary keys
293
+
294
+ These keys may exist in the user info dictionary, in addition to those defined for NSError.
295
+
296
+ - `NSString * const AFNetworkingOperationFailingURLResponseErrorKey`
297
+ - `NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey`
298
+
299
+ ### Constants
300
+
301
+ `AFNetworkingOperationFailingURLResponseErrorKey`
302
+ The corresponding value is an `NSURLResponse` containing the response of the operation associated with an error. This key is only present in the `AFURLResponseSerializationErrorDomain`.
303
+
304
+ `AFNetworkingOperationFailingURLResponseDataErrorKey`
305
+ The corresponding value is an `NSData` containing the original data of the operation associated with an error. This key is only present in the `AFURLResponseSerializationErrorDomain`.
306
+ */
307
+FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLResponseErrorKey;
308
+
309
+FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey;
310
+
311
+/**
312
+`AFNetworkingOperationFailingURLResponseBodyErrorKey`
313
+The corresponding value is an `NSString` containing the decoded error message.
314
+ */
315
+
316
+FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLResponseBodyErrorKey;
317
+
318
+NS_ASSUME_NONNULL_END

+ 806
- 0
node_modules/cordova-plugin-advanced-http/src/ios/AFNetworking/AFURLResponseSerialization.m Visa fil

@@ -0,0 +1,806 @@
1
+// AFURLResponseSerialization.m
2
+// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3
+//
4
+// Permission is hereby granted, free of charge, to any person obtaining a copy
5
+// of this software and associated documentation files (the "Software"), to deal
6
+// in the Software without restriction, including without limitation the rights
7
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+// copies of the Software, and to permit persons to whom the Software is
9
+// furnished to do so, subject to the following conditions:
10
+//
11
+// The above copyright notice and this permission notice shall be included in
12
+// all copies or substantial portions of the Software.
13
+//
14
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20
+// THE SOFTWARE.
21
+
22
+#import "AFURLResponseSerialization.h"
23
+
24
+#import <TargetConditionals.h>
25
+
26
+#if TARGET_OS_IOS
27
+#import <UIKit/UIKit.h>
28
+#elif TARGET_OS_WATCH
29
+#import <WatchKit/WatchKit.h>
30
+#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
31
+#import <Cocoa/Cocoa.h>
32
+#endif
33
+
34
+NSString * const AFURLResponseSerializationErrorDomain = @"com.alamofire.error.serialization.response";
35
+NSString * const AFNetworkingOperationFailingURLResponseErrorKey = @"com.alamofire.serialization.response.error.response";
36
+NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey = @"com.alamofire.serialization.response.error.data";
37
+NSString * const AFNetworkingOperationFailingURLResponseBodyErrorKey = @"com.alamofire.serialization.response.error.body";
38
+
39
+static NSError * AFErrorWithUnderlyingError(NSError *error, NSError *underlyingError) {
40
+    if (!error) {
41
+        return underlyingError;
42
+    }
43
+
44
+    if (!underlyingError || error.userInfo[NSUnderlyingErrorKey]) {
45
+        return error;
46
+    }
47
+
48
+    NSMutableDictionary *mutableUserInfo = [error.userInfo mutableCopy];
49
+    mutableUserInfo[NSUnderlyingErrorKey] = underlyingError;
50
+
51
+    return [[NSError alloc] initWithDomain:error.domain code:error.code userInfo:mutableUserInfo];
52
+}
53
+
54
+static BOOL AFErrorOrUnderlyingErrorHasCodeInDomain(NSError *error, NSInteger code, NSString *domain) {
55
+    if ([error.domain isEqualToString:domain] && error.code == code) {
56
+        return YES;
57
+    } else if (error.userInfo[NSUnderlyingErrorKey]) {
58
+        return AFErrorOrUnderlyingErrorHasCodeInDomain(error.userInfo[NSUnderlyingErrorKey], code, domain);
59
+    }
60
+
61
+    return NO;
62
+}
63
+
64
+static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingOptions readingOptions) {
65
+    if ([JSONObject isKindOfClass:[NSArray class]]) {
66
+        NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:[(NSArray *)JSONObject count]];
67
+        for (id value in (NSArray *)JSONObject) {
68
+            [mutableArray addObject:AFJSONObjectByRemovingKeysWithNullValues(value, readingOptions)];
69
+        }
70
+
71
+        return (readingOptions & NSJSONReadingMutableContainers) ? mutableArray : [NSArray arrayWithArray:mutableArray];
72
+    } else if ([JSONObject isKindOfClass:[NSDictionary class]]) {
73
+        NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithDictionary:JSONObject];
74
+        for (id <NSCopying> key in [(NSDictionary *)JSONObject allKeys]) {
75
+            id value = (NSDictionary *)JSONObject[key];
76
+            if (!value || [value isEqual:[NSNull null]]) {
77
+                [mutableDictionary removeObjectForKey:key];
78
+            } else if ([value isKindOfClass:[NSArray class]] || [value isKindOfClass:[NSDictionary class]]) {
79
+                mutableDictionary[key] = AFJSONObjectByRemovingKeysWithNullValues(value, readingOptions);
80
+            }
81
+        }
82
+
83
+        return (readingOptions & NSJSONReadingMutableContainers) ? mutableDictionary : [NSDictionary dictionaryWithDictionary:mutableDictionary];
84
+    }
85
+
86
+    return JSONObject;
87
+}
88
+
89
+@implementation AFHTTPResponseSerializer
90
+
91
++ (instancetype)serializer {
92
+    return [[self alloc] init];
93
+}
94
+
95
+- (instancetype)init {
96
+    self = [super init];
97
+    if (!self) {
98
+        return nil;
99
+    }
100
+
101
+    self.stringEncoding = NSUTF8StringEncoding;
102
+
103
+    self.acceptableStatusCodes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)];
104
+    self.acceptableContentTypes = nil;
105
+
106
+    return self;
107
+}
108
+
109
+#pragma mark -
110
+
111
+- (BOOL)validateResponse:(NSHTTPURLResponse *)response
112
+                    data:(NSData *)data
113
+                   error:(NSError * __autoreleasing *)error
114
+{
115
+    BOOL responseIsValid = YES;
116
+    NSError *validationError = nil;
117
+
118
+    if (response && [response isKindOfClass:[NSHTTPURLResponse class]]) {
119
+        if (self.acceptableContentTypes && ![self.acceptableContentTypes containsObject:[response MIMEType]] &&
120
+            !([response MIMEType] == nil && [data length] == 0)) {
121
+
122
+            if ([data length] > 0 && [response URL]) {
123
+                NSMutableDictionary *mutableUserInfo = [@{
124
+                                                          NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Request failed: unacceptable content-type: %@", @"AFNetworking", nil), [response MIMEType]],
125
+                                                          NSURLErrorFailingURLErrorKey:[response URL],
126
+                                                          AFNetworkingOperationFailingURLResponseErrorKey: response,
127
+                                                        } mutableCopy];
128
+                if (data) {
129
+                    mutableUserInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] = data;
130
+                }
131
+
132
+                validationError = AFErrorWithUnderlyingError([NSError errorWithDomain:AFURLResponseSerializationErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:mutableUserInfo], validationError);
133
+            }
134
+
135
+            responseIsValid = NO;
136
+        }
137
+
138
+        if (self.acceptableStatusCodes && ![self.acceptableStatusCodes containsIndex:(NSUInteger)response.statusCode] && [response URL]) {
139
+            NSMutableDictionary *mutableUserInfo = [@{
140
+                                               NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Request failed: %@ (%ld)", @"AFNetworking", nil), [NSHTTPURLResponse localizedStringForStatusCode:response.statusCode], (long)response.statusCode],
141
+                                               NSURLErrorFailingURLErrorKey:[response URL],
142
+                                               AFNetworkingOperationFailingURLResponseErrorKey: response,
143
+                                       } mutableCopy];
144
+
145
+            if (data) {
146
+                mutableUserInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] = data;
147
+            }
148
+
149
+            validationError = AFErrorWithUnderlyingError([NSError errorWithDomain:AFURLResponseSerializationErrorDomain code:NSURLErrorBadServerResponse userInfo:mutableUserInfo], validationError);
150
+
151
+            responseIsValid = NO;
152
+        }
153
+    }
154
+
155
+    if (error && !responseIsValid) {
156
+        *error = validationError;
157
+    }
158
+
159
+    return responseIsValid;
160
+}
161
+
162
+#pragma mark - AFURLResponseSerialization
163
+
164
+- (id)responseObjectForResponse:(NSURLResponse *)response
165
+                           data:(NSData *)data
166
+                          error:(NSError *__autoreleasing *)error
167
+{
168
+    [self validateResponse:(NSHTTPURLResponse *)response data:data error:error];
169
+
170
+    return data;
171
+}
172
+
173
+#pragma mark - NSSecureCoding
174
+
175
++ (BOOL)supportsSecureCoding {
176
+    return YES;
177
+}
178
+
179
+- (instancetype)initWithCoder:(NSCoder *)decoder {
180
+    self = [self init];
181
+    if (!self) {
182
+        return nil;
183
+    }
184
+
185
+    self.acceptableStatusCodes = [decoder decodeObjectOfClass:[NSIndexSet class] forKey:NSStringFromSelector(@selector(acceptableStatusCodes))];
186
+    self.acceptableContentTypes = [decoder decodeObjectOfClass:[NSIndexSet class] forKey:NSStringFromSelector(@selector(acceptableContentTypes))];
187
+
188
+    return self;
189
+}
190
+
191
+- (void)encodeWithCoder:(NSCoder *)coder {
192
+    [coder encodeObject:self.acceptableStatusCodes forKey:NSStringFromSelector(@selector(acceptableStatusCodes))];
193
+    [coder encodeObject:self.acceptableContentTypes forKey:NSStringFromSelector(@selector(acceptableContentTypes))];
194
+}
195
+
196
+#pragma mark - NSCopying
197
+
198
+- (instancetype)copyWithZone:(NSZone *)zone {
199
+    AFHTTPResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
200
+    serializer.acceptableStatusCodes = [self.acceptableStatusCodes copyWithZone:zone];
201
+    serializer.acceptableContentTypes = [self.acceptableContentTypes copyWithZone:zone];
202
+
203
+    return serializer;
204
+}
205
+
206
+@end
207
+
208
+#pragma mark -
209
+
210
+@implementation AFJSONResponseSerializer
211
+
212
++ (instancetype)serializer {
213
+    return [self serializerWithReadingOptions:(NSJSONReadingOptions)0];
214
+}
215
+
216
++ (instancetype)serializerWithReadingOptions:(NSJSONReadingOptions)readingOptions {
217
+    AFJSONResponseSerializer *serializer = [[self alloc] init];
218
+    serializer.readingOptions = readingOptions;
219
+
220
+    return serializer;
221
+}
222
+
223
+- (instancetype)init {
224
+    self = [super init];
225
+    if (!self) {
226
+        return nil;
227
+    }
228
+
229
+    self.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", nil];
230
+
231
+    return self;
232
+}
233
+
234
+#pragma mark - AFURLResponseSerialization
235
+
236
+- (id)responseObjectForResponse:(NSURLResponse *)response
237
+                           data:(NSData *)data
238
+                          error:(NSError *__autoreleasing *)error
239
+{
240
+    if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
241
+        if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {
242
+            return nil;
243
+        }
244
+    }
245
+
246
+    id responseObject = nil;
247
+    NSError *serializationError = nil;
248
+    // Workaround for behavior of Rails to return a single space for `head :ok` (a workaround for a bug in Safari), which is not interpreted as valid input by NSJSONSerialization.
249
+    // See https://github.com/rails/rails/issues/1742
250
+    BOOL isSpace = [data isEqualToData:[NSData dataWithBytes:" " length:1]];
251
+    if (data.length > 0 && !isSpace) {
252
+        responseObject = [NSJSONSerialization JSONObjectWithData:data options:self.readingOptions error:&serializationError];
253
+    } else {
254
+        return nil;
255
+    }
256
+
257
+    if (self.removesKeysWithNullValues && responseObject) {
258
+        responseObject = AFJSONObjectByRemovingKeysWithNullValues(responseObject, self.readingOptions);
259
+    }
260
+
261
+    if (error) {
262
+        *error = AFErrorWithUnderlyingError(serializationError, *error);
263
+    }
264
+
265
+    return responseObject;
266
+}
267
+
268
+#pragma mark - NSSecureCoding
269
+
270
+- (instancetype)initWithCoder:(NSCoder *)decoder {
271
+    self = [super initWithCoder:decoder];
272
+    if (!self) {
273
+        return nil;
274
+    }
275
+
276
+    self.readingOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(readingOptions))] unsignedIntegerValue];
277
+    self.removesKeysWithNullValues = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(removesKeysWithNullValues))] boolValue];
278
+
279
+    return self;
280
+}
281
+
282
+- (void)encodeWithCoder:(NSCoder *)coder {
283
+    [super encodeWithCoder:coder];
284
+
285
+    [coder encodeObject:@(self.readingOptions) forKey:NSStringFromSelector(@selector(readingOptions))];
286
+    [coder encodeObject:@(self.removesKeysWithNullValues) forKey:NSStringFromSelector(@selector(removesKeysWithNullValues))];
287
+}
288
+
289
+#pragma mark - NSCopying
290
+
291
+- (instancetype)copyWithZone:(NSZone *)zone {
292
+    AFJSONResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
293
+    serializer.readingOptions = self.readingOptions;
294
+    serializer.removesKeysWithNullValues = self.removesKeysWithNullValues;
295
+
296
+    return serializer;
297
+}
298
+
299
+@end
300
+
301
+#pragma mark -
302
+
303
+@implementation AFXMLParserResponseSerializer
304
+
305
++ (instancetype)serializer {
306
+    AFXMLParserResponseSerializer *serializer = [[self alloc] init];
307
+
308
+    return serializer;
309
+}
310
+
311
+- (instancetype)init {
312
+    self = [super init];
313
+    if (!self) {
314
+        return nil;
315
+    }
316
+
317
+    self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/xml", @"text/xml", nil];
318
+
319
+    return self;
320
+}
321
+
322
+#pragma mark - AFURLResponseSerialization
323
+
324
+- (id)responseObjectForResponse:(NSHTTPURLResponse *)response
325
+                           data:(NSData *)data
326
+                          error:(NSError *__autoreleasing *)error
327
+{
328
+    if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
329
+        if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {
330
+            return nil;
331
+        }
332
+    }
333
+
334
+    return [[NSXMLParser alloc] initWithData:data];
335
+}
336
+
337
+@end
338
+
339
+#pragma mark -
340
+
341
+#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED
342
+
343
+@implementation AFXMLDocumentResponseSerializer
344
+
345
++ (instancetype)serializer {
346
+    return [self serializerWithXMLDocumentOptions:0];
347
+}
348
+
349
++ (instancetype)serializerWithXMLDocumentOptions:(NSUInteger)mask {
350
+    AFXMLDocumentResponseSerializer *serializer = [[self alloc] init];
351
+    serializer.options = mask;
352
+
353
+    return serializer;
354
+}
355
+
356
+- (instancetype)init {
357
+    self = [super init];
358
+    if (!self) {
359
+        return nil;
360
+    }
361
+
362
+    self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/xml", @"text/xml", nil];
363
+
364
+    return self;
365
+}
366
+
367
+#pragma mark - AFURLResponseSerialization
368
+
369
+- (id)responseObjectForResponse:(NSURLResponse *)response
370
+                           data:(NSData *)data
371
+                          error:(NSError *__autoreleasing *)error
372
+{
373
+    if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
374
+        if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {
375
+            return nil;
376
+        }
377
+    }
378
+
379
+    NSError *serializationError = nil;
380
+    NSXMLDocument *document = [[NSXMLDocument alloc] initWithData:data options:self.options error:&serializationError];
381
+
382
+    if (error) {
383
+        *error = AFErrorWithUnderlyingError(serializationError, *error);
384
+    }
385
+
386
+    return document;
387
+}
388
+
389
+#pragma mark - NSSecureCoding
390
+
391
+- (instancetype)initWithCoder:(NSCoder *)decoder {
392
+    self = [super initWithCoder:decoder];
393
+    if (!self) {
394
+        return nil;
395
+    }
396
+
397
+    self.options = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(options))] unsignedIntegerValue];
398
+
399
+    return self;
400
+}
401
+
402
+- (void)encodeWithCoder:(NSCoder *)coder {
403
+    [super encodeWithCoder:coder];
404
+
405
+    [coder encodeObject:@(self.options) forKey:NSStringFromSelector(@selector(options))];
406
+}
407
+
408
+#pragma mark - NSCopying
409
+
410
+- (instancetype)copyWithZone:(NSZone *)zone {
411
+    AFXMLDocumentResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
412
+    serializer.options = self.options;
413
+
414
+    return serializer;
415
+}
416
+
417
+@end
418
+
419
+#endif
420
+
421
+#pragma mark -
422
+
423
+@implementation AFPropertyListResponseSerializer
424
+
425
++ (instancetype)serializer {
426
+    return [self serializerWithFormat:NSPropertyListXMLFormat_v1_0 readOptions:0];
427
+}
428
+
429
++ (instancetype)serializerWithFormat:(NSPropertyListFormat)format
430
+                         readOptions:(NSPropertyListReadOptions)readOptions
431
+{
432
+    AFPropertyListResponseSerializer *serializer = [[self alloc] init];
433
+    serializer.format = format;
434
+    serializer.readOptions = readOptions;
435
+
436
+    return serializer;
437
+}
438
+
439
+- (instancetype)init {
440
+    self = [super init];
441
+    if (!self) {
442
+        return nil;
443
+    }
444
+
445
+    self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/x-plist", nil];
446
+
447
+    return self;
448
+}
449
+
450
+#pragma mark - AFURLResponseSerialization
451
+
452
+- (id)responseObjectForResponse:(NSURLResponse *)response
453
+                           data:(NSData *)data
454
+                          error:(NSError *__autoreleasing *)error
455
+{
456
+    if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
457
+        if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {
458
+            return nil;
459
+        }
460
+    }
461
+
462
+    id responseObject;
463
+    NSError *serializationError = nil;
464
+
465
+    if (data) {
466
+        responseObject = [NSPropertyListSerialization propertyListWithData:data options:self.readOptions format:NULL error:&serializationError];
467
+    }
468
+
469
+    if (error) {
470
+        *error = AFErrorWithUnderlyingError(serializationError, *error);
471
+    }
472
+
473
+    return responseObject;
474
+}
475
+
476
+#pragma mark - NSSecureCoding
477
+
478
+- (instancetype)initWithCoder:(NSCoder *)decoder {
479
+    self = [super initWithCoder:decoder];
480
+    if (!self) {
481
+        return nil;
482
+    }
483
+
484
+    self.format = (NSPropertyListFormat)[[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(format))] unsignedIntegerValue];
485
+    self.readOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(readOptions))] unsignedIntegerValue];
486
+
487
+    return self;
488
+}
489
+
490
+- (void)encodeWithCoder:(NSCoder *)coder {
491
+    [super encodeWithCoder:coder];
492
+
493
+    [coder encodeObject:@(self.format) forKey:NSStringFromSelector(@selector(format))];
494
+    [coder encodeObject:@(self.readOptions) forKey:NSStringFromSelector(@selector(readOptions))];
495
+}
496
+
497
+#pragma mark - NSCopying
498
+
499
+- (instancetype)copyWithZone:(NSZone *)zone {
500
+    AFPropertyListResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
501
+    serializer.format = self.format;
502
+    serializer.readOptions = self.readOptions;
503
+
504
+    return serializer;
505
+}
506
+
507
+@end
508
+
509
+#pragma mark -
510
+
511
+#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
512
+#import <CoreGraphics/CoreGraphics.h>
513
+#import <UIKit/UIKit.h>
514
+
515
+@interface UIImage (AFNetworkingSafeImageLoading)
516
++ (UIImage *)af_safeImageWithData:(NSData *)data;
517
+@end
518
+
519
+static NSLock* imageLock = nil;
520
+
521
+@implementation UIImage (AFNetworkingSafeImageLoading)
522
+
523
++ (UIImage *)af_safeImageWithData:(NSData *)data {
524
+    UIImage* image = nil;
525
+    static dispatch_once_t onceToken;
526
+    dispatch_once(&onceToken, ^{
527
+        imageLock = [[NSLock alloc] init];
528
+    });
529
+
530
+    [imageLock lock];
531
+    image = [UIImage imageWithData:data];
532
+    [imageLock unlock];
533
+    return image;
534
+}
535
+
536
+@end
537
+
538
+static UIImage * AFImageWithDataAtScale(NSData *data, CGFloat scale) {
539
+    UIImage *image = [UIImage af_safeImageWithData:data];
540
+    if (image.images) {
541
+        return image;
542
+    }
543
+
544
+    return [[UIImage alloc] initWithCGImage:[image CGImage] scale:scale orientation:image.imageOrientation];
545
+}
546
+
547
+static UIImage * AFInflatedImageFromResponseWithDataAtScale(NSHTTPURLResponse *response, NSData *data, CGFloat scale) {
548
+    if (!data || [data length] == 0) {
549
+        return nil;
550
+    }
551
+
552
+    CGImageRef imageRef = NULL;
553
+    CGDataProviderRef dataProvider = CGDataProviderCreateWithCFData((__bridge CFDataRef)data);
554
+
555
+    if ([response.MIMEType isEqualToString:@"image/png"]) {
556
+        imageRef = CGImageCreateWithPNGDataProvider(dataProvider,  NULL, true, kCGRenderingIntentDefault);
557
+    } else if ([response.MIMEType isEqualToString:@"image/jpeg"]) {
558
+        imageRef = CGImageCreateWithJPEGDataProvider(dataProvider, NULL, true, kCGRenderingIntentDefault);
559
+
560
+        if (imageRef) {
561
+            CGColorSpaceRef imageColorSpace = CGImageGetColorSpace(imageRef);
562
+            CGColorSpaceModel imageColorSpaceModel = CGColorSpaceGetModel(imageColorSpace);
563
+
564
+            // CGImageCreateWithJPEGDataProvider does not properly handle CMKY, so fall back to AFImageWithDataAtScale
565
+            if (imageColorSpaceModel == kCGColorSpaceModelCMYK) {
566
+                CGImageRelease(imageRef);
567
+                imageRef = NULL;
568
+            }
569
+        }
570
+    }
571
+
572
+    CGDataProviderRelease(dataProvider);
573
+
574
+    UIImage *image = AFImageWithDataAtScale(data, scale);
575
+    if (!imageRef) {
576
+        if (image.images || !image) {
577
+            return image;
578
+        }
579
+
580
+        imageRef = CGImageCreateCopy([image CGImage]);
581
+        if (!imageRef) {
582
+            return nil;
583
+        }
584
+    }
585
+
586
+    size_t width = CGImageGetWidth(imageRef);
587
+    size_t height = CGImageGetHeight(imageRef);
588
+    size_t bitsPerComponent = CGImageGetBitsPerComponent(imageRef);
589
+
590
+    if (width * height > 1024 * 1024 || bitsPerComponent > 8) {
591
+        CGImageRelease(imageRef);
592
+
593
+        return image;
594
+    }
595
+
596
+    // CGImageGetBytesPerRow() calculates incorrectly in iOS 5.0, so defer to CGBitmapContextCreate
597
+    size_t bytesPerRow = 0;
598
+    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
599
+    CGColorSpaceModel colorSpaceModel = CGColorSpaceGetModel(colorSpace);
600
+    CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef);
601
+
602
+    if (colorSpaceModel == kCGColorSpaceModelRGB) {
603
+        uint32_t alpha = (bitmapInfo & kCGBitmapAlphaInfoMask);
604
+#pragma clang diagnostic push
605
+#pragma clang diagnostic ignored "-Wassign-enum"
606
+        if (alpha == kCGImageAlphaNone) {
607
+            bitmapInfo &= ~kCGBitmapAlphaInfoMask;
608
+            bitmapInfo |= kCGImageAlphaNoneSkipFirst;
609
+        } else if (!(alpha == kCGImageAlphaNoneSkipFirst || alpha == kCGImageAlphaNoneSkipLast)) {
610
+            bitmapInfo &= ~kCGBitmapAlphaInfoMask;
611
+            bitmapInfo |= kCGImageAlphaPremultipliedFirst;
612
+        }
613
+#pragma clang diagnostic pop
614
+    }
615
+
616
+    CGContextRef context = CGBitmapContextCreate(NULL, width, height, bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo);
617
+
618
+    CGColorSpaceRelease(colorSpace);
619
+
620
+    if (!context) {
621
+        CGImageRelease(imageRef);
622
+
623
+        return image;
624
+    }
625
+
626
+    CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, width, height), imageRef);
627
+    CGImageRef inflatedImageRef = CGBitmapContextCreateImage(context);
628
+
629
+    CGContextRelease(context);
630
+
631
+    UIImage *inflatedImage = [[UIImage alloc] initWithCGImage:inflatedImageRef scale:scale orientation:image.imageOrientation];
632
+
633
+    CGImageRelease(inflatedImageRef);
634
+    CGImageRelease(imageRef);
635
+
636
+    return inflatedImage;
637
+}
638
+#endif
639
+
640
+
641
+@implementation AFImageResponseSerializer
642
+
643
+- (instancetype)init {
644
+    self = [super init];
645
+    if (!self) {
646
+        return nil;
647
+    }
648
+
649
+    self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"image/tiff", @"image/jpeg", @"image/gif", @"image/png", @"image/ico", @"image/x-icon", @"image/bmp", @"image/x-bmp", @"image/x-xbitmap", @"image/x-win-bitmap", nil];
650
+
651
+#if TARGET_OS_IOS || TARGET_OS_TV
652
+    self.imageScale = [[UIScreen mainScreen] scale];
653
+    self.automaticallyInflatesResponseImage = YES;
654
+#elif TARGET_OS_WATCH
655
+    self.imageScale = [[WKInterfaceDevice currentDevice] screenScale];
656
+    self.automaticallyInflatesResponseImage = YES;
657
+#endif
658
+
659
+    return self;
660
+}
661
+
662
+#pragma mark - AFURLResponseSerializer
663
+
664
+- (id)responseObjectForResponse:(NSURLResponse *)response
665
+                           data:(NSData *)data
666
+                          error:(NSError *__autoreleasing *)error
667
+{
668
+    if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
669
+        if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {
670
+            return nil;
671
+        }
672
+    }
673
+
674
+#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
675
+    if (self.automaticallyInflatesResponseImage) {
676
+        return AFInflatedImageFromResponseWithDataAtScale((NSHTTPURLResponse *)response, data, self.imageScale);
677
+    } else {
678
+        return AFImageWithDataAtScale(data, self.imageScale);
679
+    }
680
+#else
681
+    // Ensure that the image is set to it's correct pixel width and height
682
+    NSBitmapImageRep *bitimage = [[NSBitmapImageRep alloc] initWithData:data];
683
+    NSImage *image = [[NSImage alloc] initWithSize:NSMakeSize([bitimage pixelsWide], [bitimage pixelsHigh])];
684
+    [image addRepresentation:bitimage];
685
+
686
+    return image;
687
+#endif
688
+
689
+    return nil;
690
+}
691
+
692
+#pragma mark - NSSecureCoding
693
+
694
+- (instancetype)initWithCoder:(NSCoder *)decoder {
695
+    self = [super initWithCoder:decoder];
696
+    if (!self) {
697
+        return nil;
698
+    }
699
+
700
+#if TARGET_OS_IOS  || TARGET_OS_TV || TARGET_OS_WATCH
701
+    NSNumber *imageScale = [decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(imageScale))];
702
+#if CGFLOAT_IS_DOUBLE
703
+    self.imageScale = [imageScale doubleValue];
704
+#else
705
+    self.imageScale = [imageScale floatValue];
706
+#endif
707
+
708
+    self.automaticallyInflatesResponseImage = [decoder decodeBoolForKey:NSStringFromSelector(@selector(automaticallyInflatesResponseImage))];
709
+#endif
710
+
711
+    return self;
712
+}
713
+
714
+- (void)encodeWithCoder:(NSCoder *)coder {
715
+    [super encodeWithCoder:coder];
716
+
717
+#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
718
+    [coder encodeObject:@(self.imageScale) forKey:NSStringFromSelector(@selector(imageScale))];
719
+    [coder encodeBool:self.automaticallyInflatesResponseImage forKey:NSStringFromSelector(@selector(automaticallyInflatesResponseImage))];
720
+#endif
721
+}
722
+
723
+#pragma mark - NSCopying
724
+
725
+- (instancetype)copyWithZone:(NSZone *)zone {
726
+    AFImageResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
727
+
728
+#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
729
+    serializer.imageScale = self.imageScale;
730
+    serializer.automaticallyInflatesResponseImage = self.automaticallyInflatesResponseImage;
731
+#endif
732
+
733
+    return serializer;
734
+}
735
+
736
+@end
737
+
738
+#pragma mark -
739
+
740
+@interface AFCompoundResponseSerializer ()
741
+@property (readwrite, nonatomic, copy) NSArray *responseSerializers;
742
+@end
743
+
744
+@implementation AFCompoundResponseSerializer
745
+
746
++ (instancetype)compoundSerializerWithResponseSerializers:(NSArray *)responseSerializers {
747
+    AFCompoundResponseSerializer *serializer = [[self alloc] init];
748
+    serializer.responseSerializers = responseSerializers;
749
+
750
+    return serializer;
751
+}
752
+
753
+#pragma mark - AFURLResponseSerialization
754
+
755
+- (id)responseObjectForResponse:(NSURLResponse *)response
756
+                           data:(NSData *)data
757
+                          error:(NSError *__autoreleasing *)error
758
+{
759
+    for (id <AFURLResponseSerialization> serializer in self.responseSerializers) {
760
+        if (![serializer isKindOfClass:[AFHTTPResponseSerializer class]]) {
761
+            continue;
762
+        }
763
+
764
+        NSError *serializerError = nil;
765
+        id responseObject = [serializer responseObjectForResponse:response data:data error:&serializerError];
766
+        if (responseObject) {
767
+            if (error) {
768
+                *error = AFErrorWithUnderlyingError(serializerError, *error);
769
+            }
770
+
771
+            return responseObject;
772
+        }
773
+    }
774
+
775
+    return [super responseObjectForResponse:response data:data error:error];
776
+}
777
+
778
+#pragma mark - NSSecureCoding
779
+
780
+- (instancetype)initWithCoder:(NSCoder *)decoder {
781
+    self = [super initWithCoder:decoder];
782
+    if (!self) {
783
+        return nil;
784
+    }
785
+
786
+    self.responseSerializers = [decoder decodeObjectOfClass:[NSArray class] forKey:NSStringFromSelector(@selector(responseSerializers))];
787
+
788
+    return self;
789
+}
790
+
791
+- (void)encodeWithCoder:(NSCoder *)coder {
792
+    [super encodeWithCoder:coder];
793
+
794
+    [coder encodeObject:self.responseSerializers forKey:NSStringFromSelector(@selector(responseSerializers))];
795
+}
796
+
797
+#pragma mark - NSCopying
798
+
799
+- (instancetype)copyWithZone:(NSZone *)zone {
800
+    AFCompoundResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
801
+    serializer.responseSerializers = self.responseSerializers;
802
+
803
+    return serializer;
804
+}
805
+
806
+@end

+ 500
- 0
node_modules/cordova-plugin-advanced-http/src/ios/AFNetworking/AFURLSessionManager.h Visa fil

@@ -0,0 +1,500 @@
1
+// AFURLSessionManager.h
2
+// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3
+//
4
+// Permission is hereby granted, free of charge, to any person obtaining a copy
5
+// of this software and associated documentation files (the "Software"), to deal
6
+// in the Software without restriction, including without limitation the rights
7
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+// copies of the Software, and to permit persons to whom the Software is
9
+// furnished to do so, subject to the following conditions:
10
+//
11
+// The above copyright notice and this permission notice shall be included in
12
+// all copies or substantial portions of the Software.
13
+//
14
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20
+// THE SOFTWARE.
21
+
22
+
23
+#import <Foundation/Foundation.h>
24
+
25
+#import "AFURLResponseSerialization.h"
26
+#import "AFURLRequestSerialization.h"
27
+#import "AFSecurityPolicy.h"
28
+#if !TARGET_OS_WATCH
29
+#import "AFNetworkReachabilityManager.h"
30
+#endif
31
+
32
+/**
33
+ `AFURLSessionManager` creates and manages an `NSURLSession` object based on a specified `NSURLSessionConfiguration` object, which conforms to `<NSURLSessionTaskDelegate>`, `<NSURLSessionDataDelegate>`, `<NSURLSessionDownloadDelegate>`, and `<NSURLSessionDelegate>`.
34
+
35
+ ## Subclassing Notes
36
+
37
+ This is the base class for `AFHTTPSessionManager`, which adds functionality specific to making HTTP requests. If you are looking to extend `AFURLSessionManager` specifically for HTTP, consider subclassing `AFHTTPSessionManager` instead.
38
+
39
+ ## NSURLSession & NSURLSessionTask Delegate Methods
40
+
41
+ `AFURLSessionManager` implements the following delegate methods:
42
+
43
+ ### `NSURLSessionDelegate`
44
+
45
+ - `URLSession:didBecomeInvalidWithError:`
46
+ - `URLSession:didReceiveChallenge:completionHandler:`
47
+ - `URLSessionDidFinishEventsForBackgroundURLSession:`
48
+
49
+ ### `NSURLSessionTaskDelegate`
50
+
51
+ - `URLSession:willPerformHTTPRedirection:newRequest:completionHandler:`
52
+ - `URLSession:task:didReceiveChallenge:completionHandler:`
53
+ - `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`
54
+ - `URLSession:task:needNewBodyStream:`
55
+ - `URLSession:task:didCompleteWithError:`
56
+
57
+ ### `NSURLSessionDataDelegate`
58
+
59
+ - `URLSession:dataTask:didReceiveResponse:completionHandler:`
60
+ - `URLSession:dataTask:didBecomeDownloadTask:`
61
+ - `URLSession:dataTask:didReceiveData:`
62
+ - `URLSession:dataTask:willCacheResponse:completionHandler:`
63
+
64
+ ### `NSURLSessionDownloadDelegate`
65
+
66
+ - `URLSession:downloadTask:didFinishDownloadingToURL:`
67
+ - `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesWritten:totalBytesExpectedToWrite:`
68
+ - `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:`
69
+
70
+ If any of these methods are overridden in a subclass, they _must_ call the `super` implementation first.
71
+
72
+ ## Network Reachability Monitoring
73
+
74
+ Network reachability status and change monitoring is available through the `reachabilityManager` property. Applications may choose to monitor network reachability conditions in order to prevent or suspend any outbound requests. See `AFNetworkReachabilityManager` for more details.
75
+
76
+ ## NSCoding Caveats
77
+
78
+ - Encoded managers do not include any block properties. Be sure to set delegate callback blocks when using `-initWithCoder:` or `NSKeyedUnarchiver`.
79
+
80
+ ## NSCopying Caveats
81
+
82
+ - `-copy` and `-copyWithZone:` return a new manager with a new `NSURLSession` created from the configuration of the original.
83
+ - Operation copies do not include any delegate callback blocks, as they often strongly captures a reference to `self`, which would otherwise have the unintuitive side-effect of pointing to the _original_ session manager when copied.
84
+
85
+ @warning Managers for background sessions must be owned for the duration of their use. This can be accomplished by creating an application-wide or shared singleton instance.
86
+ */
87
+
88
+NS_ASSUME_NONNULL_BEGIN
89
+
90
+@interface AFURLSessionManager : NSObject <NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate, NSSecureCoding, NSCopying>
91
+
92
+/**
93
+ The managed session.
94
+ */
95
+@property (readonly, nonatomic, strong) NSURLSession *session;
96
+
97
+/**
98
+ The operation queue on which delegate callbacks are run.
99
+ */
100
+@property (readonly, nonatomic, strong) NSOperationQueue *operationQueue;
101
+
102
+/**
103
+ Responses sent from the server in data tasks created with `dataTaskWithRequest:success:failure:` and run using the `GET` / `POST` / et al. convenience methods are automatically validated and serialized by the response serializer. By default, this property is set to an instance of `AFJSONResponseSerializer`.
104
+
105
+ @warning `responseSerializer` must not be `nil`.
106
+ */
107
+@property (nonatomic, strong) id <AFURLResponseSerialization> responseSerializer;
108
+
109
+///-------------------------------
110
+/// @name Managing Security Policy
111
+///-------------------------------
112
+
113
+/**
114
+ The security policy used by created session to evaluate server trust for secure connections. `AFURLSessionManager` uses the `defaultPolicy` unless otherwise specified.
115
+ */
116
+@property (nonatomic, strong) AFSecurityPolicy *securityPolicy;
117
+
118
+#if !TARGET_OS_WATCH
119
+///--------------------------------------
120
+/// @name Monitoring Network Reachability
121
+///--------------------------------------
122
+
123
+/**
124
+ The network reachability manager. `AFURLSessionManager` uses the `sharedManager` by default.
125
+ */
126
+@property (readwrite, nonatomic, strong) AFNetworkReachabilityManager *reachabilityManager;
127
+#endif
128
+
129
+///----------------------------
130
+/// @name Getting Session Tasks
131
+///----------------------------
132
+
133
+/**
134
+ The data, upload, and download tasks currently run by the managed session.
135
+ */
136
+@property (readonly, nonatomic, strong) NSArray <NSURLSessionTask *> *tasks;
137
+
138
+/**
139
+ The data tasks currently run by the managed session.
140
+ */
141
+@property (readonly, nonatomic, strong) NSArray <NSURLSessionDataTask *> *dataTasks;
142
+
143
+/**
144
+ The upload tasks currently run by the managed session.
145
+ */
146
+@property (readonly, nonatomic, strong) NSArray <NSURLSessionUploadTask *> *uploadTasks;
147
+
148
+/**
149
+ The download tasks currently run by the managed session.
150
+ */
151
+@property (readonly, nonatomic, strong) NSArray <NSURLSessionDownloadTask *> *downloadTasks;
152
+
153
+///-------------------------------
154
+/// @name Managing Callback Queues
155
+///-------------------------------
156
+
157
+/**
158
+ The dispatch queue for `completionBlock`. If `NULL` (default), the main queue is used.
159
+ */
160
+@property (nonatomic, strong, nullable) dispatch_queue_t completionQueue;
161
+
162
+/**
163
+ The dispatch group for `completionBlock`. If `NULL` (default), a private dispatch group is used.
164
+ */
165
+@property (nonatomic, strong, nullable) dispatch_group_t completionGroup;
166
+
167
+///---------------------------------
168
+/// @name Working Around System Bugs
169
+///---------------------------------
170
+
171
+/**
172
+ Whether to attempt to retry creation of upload tasks for background sessions when initial call returns `nil`. `NO` by default.
173
+
174
+ @bug As of iOS 7.0, there is a bug where upload tasks created for background tasks are sometimes `nil`. As a workaround, if this property is `YES`, AFNetworking will follow Apple's recommendation to try creating the task again.
175
+
176
+ @see https://github.com/AFNetworking/AFNetworking/issues/1675
177
+ */
178
+@property (nonatomic, assign) BOOL attemptsToRecreateUploadTasksForBackgroundSessions;
179
+
180
+///---------------------
181
+/// @name Initialization
182
+///---------------------
183
+
184
+/**
185
+ Creates and returns a manager for a session created with the specified configuration. This is the designated initializer.
186
+
187
+ @param configuration The configuration used to create the managed session.
188
+
189
+ @return A manager for a newly-created session.
190
+ */
191
+- (instancetype)initWithSessionConfiguration:(nullable NSURLSessionConfiguration *)configuration NS_DESIGNATED_INITIALIZER;
192
+
193
+/**
194
+ Invalidates the managed session, optionally canceling pending tasks.
195
+
196
+ @param cancelPendingTasks Whether or not to cancel pending tasks.
197
+ */
198
+- (void)invalidateSessionCancelingTasks:(BOOL)cancelPendingTasks;
199
+
200
+///-------------------------
201
+/// @name Running Data Tasks
202
+///-------------------------
203
+
204
+/**
205
+ Creates an `NSURLSessionDataTask` with the specified request.
206
+
207
+ @param request The HTTP request for the request.
208
+ @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any.
209
+ */
210
+- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request
211
+                            completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject,  NSError * _Nullable error))completionHandler;
212
+
213
+/**
214
+ Creates an `NSURLSessionDataTask` with the specified request.
215
+
216
+ @param request The HTTP request for the request.
217
+ @param uploadProgressBlock A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue.
218
+ @param downloadProgressBlock A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue.
219
+ @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any.
220
+ */
221
+- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request
222
+                               uploadProgress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock
223
+                             downloadProgress:(nullable void (^)(NSProgress *downloadProgress))downloadProgressBlock
224
+                            completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject,  NSError * _Nullable error))completionHandler;
225
+
226
+///---------------------------
227
+/// @name Running Upload Tasks
228
+///---------------------------
229
+
230
+/**
231
+ Creates an `NSURLSessionUploadTask` with the specified request for a local file.
232
+
233
+ @param request The HTTP request for the request.
234
+ @param fileURL A URL to the local file to be uploaded.
235
+ @param uploadProgressBlock A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue.
236
+ @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any.
237
+
238
+ @see `attemptsToRecreateUploadTasksForBackgroundSessions`
239
+ */
240
+- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request
241
+                                         fromFile:(NSURL *)fileURL
242
+                                         progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock
243
+                                completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError  * _Nullable error))completionHandler;
244
+
245
+/**
246
+ Creates an `NSURLSessionUploadTask` with the specified request for an HTTP body.
247
+
248
+ @param request The HTTP request for the request.
249
+ @param bodyData A data object containing the HTTP body to be uploaded.
250
+ @param uploadProgressBlock A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue.
251
+ @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any.
252
+ */
253
+- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request
254
+                                         fromData:(nullable NSData *)bodyData
255
+                                         progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock
256
+                                completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler;
257
+
258
+/**
259
+ Creates an `NSURLSessionUploadTask` with the specified streaming request.
260
+
261
+ @param request The HTTP request for the request.
262
+ @param uploadProgressBlock A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue.
263
+ @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any.
264
+ */
265
+- (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)request
266
+                                                 progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock
267
+                                        completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler;
268
+
269
+///-----------------------------
270
+/// @name Running Download Tasks
271
+///-----------------------------
272
+
273
+/**
274
+ Creates an `NSURLSessionDownloadTask` with the specified request.
275
+
276
+ @param request The HTTP request for the request.
277
+ @param downloadProgressBlock A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue.
278
+ @param destination A block object to be executed in order to determine the destination of the downloaded file. This block takes two arguments, the target path & the server response, and returns the desired file URL of the resulting download. The temporary file used during the download will be automatically deleted after being moved to the returned URL.
279
+ @param completionHandler A block to be executed when a task finishes. This block has no return value and takes three arguments: the server response, the path of the downloaded file, and the error describing the network or parsing error that occurred, if any.
280
+
281
+ @warning If using a background `NSURLSessionConfiguration` on iOS, these blocks will be lost when the app is terminated. Background sessions may prefer to use `-setDownloadTaskDidFinishDownloadingBlock:` to specify the URL for saving the downloaded file, rather than the destination block of this method.
282
+ */
283
+- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request
284
+                                             progress:(nullable void (^)(NSProgress *downloadProgress))downloadProgressBlock
285
+                                          destination:(nullable NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
286
+                                    completionHandler:(nullable void (^)(NSURLResponse *response, NSURL * _Nullable filePath, NSError * _Nullable error))completionHandler;
287
+
288
+/**
289
+ Creates an `NSURLSessionDownloadTask` with the specified resume data.
290
+
291
+ @param resumeData The data used to resume downloading.
292
+ @param downloadProgressBlock A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue.
293
+ @param destination A block object to be executed in order to determine the destination of the downloaded file. This block takes two arguments, the target path & the server response, and returns the desired file URL of the resulting download. The temporary file used during the download will be automatically deleted after being moved to the returned URL.
294
+ @param completionHandler A block to be executed when a task finishes. This block has no return value and takes three arguments: the server response, the path of the downloaded file, and the error describing the network or parsing error that occurred, if any.
295
+ */
296
+- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData
297
+                                                progress:(nullable void (^)(NSProgress *downloadProgress))downloadProgressBlock
298
+                                             destination:(nullable NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
299
+                                       completionHandler:(nullable void (^)(NSURLResponse *response, NSURL * _Nullable filePath, NSError * _Nullable error))completionHandler;
300
+
301
+///---------------------------------
302
+/// @name Getting Progress for Tasks
303
+///---------------------------------
304
+
305
+/**
306
+ Returns the upload progress of the specified task.
307
+
308
+ @param task The session task. Must not be `nil`.
309
+
310
+ @return An `NSProgress` object reporting the upload progress of a task, or `nil` if the progress is unavailable.
311
+ */
312
+- (nullable NSProgress *)uploadProgressForTask:(NSURLSessionTask *)task;
313
+
314
+/**
315
+ Returns the download progress of the specified task.
316
+
317
+ @param task The session task. Must not be `nil`.
318
+
319
+ @return An `NSProgress` object reporting the download progress of a task, or `nil` if the progress is unavailable.
320
+ */
321
+- (nullable NSProgress *)downloadProgressForTask:(NSURLSessionTask *)task;
322
+
323
+///-----------------------------------------
324
+/// @name Setting Session Delegate Callbacks
325
+///-----------------------------------------
326
+
327
+/**
328
+ Sets a block to be executed when the managed session becomes invalid, as handled by the `NSURLSessionDelegate` method `URLSession:didBecomeInvalidWithError:`.
329
+
330
+ @param block A block object to be executed when the managed session becomes invalid. The block has no return value, and takes two arguments: the session, and the error related to the cause of invalidation.
331
+ */
332
+- (void)setSessionDidBecomeInvalidBlock:(nullable void (^)(NSURLSession *session, NSError *error))block;
333
+
334
+/**
335
+ Sets a block to be executed when a connection level authentication challenge has occurred, as handled by the `NSURLSessionDelegate` method `URLSession:didReceiveChallenge:completionHandler:`.
336
+
337
+ @param block A block object to be executed when a connection level authentication challenge has occurred. The block returns the disposition of the authentication challenge, and takes three arguments: the session, the authentication challenge, and a pointer to the credential that should be used to resolve the challenge.
338
+ */
339
+- (void)setSessionDidReceiveAuthenticationChallengeBlock:(nullable NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * _Nullable __autoreleasing * _Nullable credential))block;
340
+
341
+///--------------------------------------
342
+/// @name Setting Task Delegate Callbacks
343
+///--------------------------------------
344
+
345
+/**
346
+ Sets a block to be executed when a task requires a new request body stream to send to the remote server, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:needNewBodyStream:`.
347
+
348
+ @param block A block object to be executed when a task requires a new request body stream.
349
+ */
350
+- (void)setTaskNeedNewBodyStreamBlock:(nullable NSInputStream * (^)(NSURLSession *session, NSURLSessionTask *task))block;
351
+
352
+/**
353
+ Sets a block to be executed when an HTTP request is attempting to perform a redirection to a different URL, as handled by the `NSURLSessionTaskDelegate` method `URLSession:willPerformHTTPRedirection:newRequest:completionHandler:`.
354
+
355
+ @param block A block object to be executed when an HTTP request is attempting to perform a redirection to a different URL. The block returns the request to be made for the redirection, and takes four arguments: the session, the task, the redirection response, and the request corresponding to the redirection response.
356
+ */
357
+- (void)setTaskWillPerformHTTPRedirectionBlock:(nullable NSURLRequest * (^)(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request))block;
358
+
359
+/**
360
+ Sets a block to be executed when a session task has received a request specific authentication challenge, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didReceiveChallenge:completionHandler:`.
361
+
362
+ @param block A block object to be executed when a session task has received a request specific authentication challenge. The block returns the disposition of the authentication challenge, and takes four arguments: the session, the task, the authentication challenge, and a pointer to the credential that should be used to resolve the challenge.
363
+ */
364
+- (void)setTaskDidReceiveAuthenticationChallengeBlock:(nullable NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential * _Nullable __autoreleasing * _Nullable credential))block;
365
+
366
+/**
367
+ Sets a block to be executed periodically to track upload progress, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`.
368
+
369
+ @param block A block object to be called when an undetermined number of bytes have been uploaded to the server. This block has no return value and takes five arguments: the session, the task, the number of bytes written since the last time the upload progress block was called, the total bytes written, and the total bytes expected to be written during the request, as initially determined by the length of the HTTP body. This block may be called multiple times, and will execute on the main thread.
370
+ */
371
+- (void)setTaskDidSendBodyDataBlock:(nullable void (^)(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend))block;
372
+
373
+/**
374
+ Sets a block to be executed as the last message related to a specific task, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didCompleteWithError:`.
375
+
376
+ @param block A block object to be executed when a session task is completed. The block has no return value, and takes three arguments: the session, the task, and any error that occurred in the process of executing the task.
377
+ */
378
+- (void)setTaskDidCompleteBlock:(nullable void (^)(NSURLSession *session, NSURLSessionTask *task, NSError * _Nullable error))block;
379
+
380
+///-------------------------------------------
381
+/// @name Setting Data Task Delegate Callbacks
382
+///-------------------------------------------
383
+
384
+/**
385
+ Sets a block to be executed when a data task has received a response, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didReceiveResponse:completionHandler:`.
386
+
387
+ @param block A block object to be executed when a data task has received a response. The block returns the disposition of the session response, and takes three arguments: the session, the data task, and the received response.
388
+ */
389
+- (void)setDataTaskDidReceiveResponseBlock:(nullable NSURLSessionResponseDisposition (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response))block;
390
+
391
+/**
392
+ Sets a block to be executed when a data task has become a download task, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didBecomeDownloadTask:`.
393
+
394
+ @param block A block object to be executed when a data task has become a download task. The block has no return value, and takes three arguments: the session, the data task, and the download task it has become.
395
+ */
396
+- (void)setDataTaskDidBecomeDownloadTaskBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask))block;
397
+
398
+/**
399
+ Sets a block to be executed when a data task receives data, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didReceiveData:`.
400
+
401
+ @param block A block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes three arguments: the session, the data task, and the data received. This block may be called multiple times, and will execute on the session manager operation queue.
402
+ */
403
+- (void)setDataTaskDidReceiveDataBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data))block;
404
+
405
+/**
406
+ Sets a block to be executed to determine the caching behavior of a data task, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:willCacheResponse:completionHandler:`.
407
+
408
+ @param block A block object to be executed to determine the caching behavior of a data task. The block returns the response to cache, and takes three arguments: the session, the data task, and the proposed cached URL response.
409
+ */
410
+- (void)setDataTaskWillCacheResponseBlock:(nullable NSCachedURLResponse * (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSCachedURLResponse *proposedResponse))block;
411
+
412
+/**
413
+ Sets a block to be executed once all messages enqueued for a session have been delivered, as handled by the `NSURLSessionDataDelegate` method `URLSessionDidFinishEventsForBackgroundURLSession:`.
414
+
415
+ @param block A block object to be executed once all messages enqueued for a session have been delivered. The block has no return value and takes a single argument: the session.
416
+ */
417
+- (void)setDidFinishEventsForBackgroundURLSessionBlock:(nullable void (^)(NSURLSession *session))block;
418
+
419
+///-----------------------------------------------
420
+/// @name Setting Download Task Delegate Callbacks
421
+///-----------------------------------------------
422
+
423
+/**
424
+ Sets a block to be executed when a download task has completed a download, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didFinishDownloadingToURL:`.
425
+
426
+ @param block A block object to be executed when a download task has completed. The block returns the URL the download should be moved to, and takes three arguments: the session, the download task, and the temporary location of the downloaded file. If the file manager encounters an error while attempting to move the temporary file to the destination, an `AFURLSessionDownloadTaskDidFailToMoveFileNotification` will be posted, with the download task as its object, and the user info of the error.
427
+ */
428
+- (void)setDownloadTaskDidFinishDownloadingBlock:(nullable NSURL * _Nullable  (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location))block;
429
+
430
+/**
431
+ Sets a block to be executed periodically to track download progress, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesWritten:totalBytesExpectedToWrite:`.
432
+
433
+ @param block A block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes five arguments: the session, the download task, the number of bytes read since the last time the download progress block was called, the total bytes read, and the total bytes expected to be read during the request, as initially determined by the expected content size of the `NSHTTPURLResponse` object. This block may be called multiple times, and will execute on the session manager operation queue.
434
+ */
435
+- (void)setDownloadTaskDidWriteDataBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite))block;
436
+
437
+/**
438
+ Sets a block to be executed when a download task has been resumed, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:`.
439
+
440
+ @param block A block object to be executed when a download task has been resumed. The block has no return value and takes four arguments: the session, the download task, the file offset of the resumed download, and the total number of bytes expected to be downloaded.
441
+ */
442
+- (void)setDownloadTaskDidResumeBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes))block;
443
+
444
+@end
445
+
446
+///--------------------
447
+/// @name Notifications
448
+///--------------------
449
+
450
+/**
451
+ Posted when a task resumes.
452
+ */
453
+FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidResumeNotification;
454
+
455
+/**
456
+ Posted when a task finishes executing. Includes a userInfo dictionary with additional information about the task.
457
+ */
458
+FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteNotification;
459
+
460
+/**
461
+ Posted when a task suspends its execution.
462
+ */
463
+FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidSuspendNotification;
464
+
465
+/**
466
+ Posted when a session is invalidated.
467
+ */
468
+FOUNDATION_EXPORT NSString * const AFURLSessionDidInvalidateNotification;
469
+
470
+/**
471
+ Posted when a session download task encountered an error when moving the temporary download file to a specified destination.
472
+ */
473
+FOUNDATION_EXPORT NSString * const AFURLSessionDownloadTaskDidFailToMoveFileNotification;
474
+
475
+/**
476
+ The raw response data of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if response data exists for the task.
477
+ */
478
+FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteResponseDataKey;
479
+
480
+/**
481
+ The serialized response object of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if the response was serialized.
482
+ */
483
+FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteSerializedResponseKey;
484
+
485
+/**
486
+ The response serializer used to serialize the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if the task has an associated response serializer.
487
+ */
488
+FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteResponseSerializerKey;
489
+
490
+/**
491
+ The file path associated with the download task. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if an the response data has been stored directly to disk.
492
+ */
493
+FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteAssetPathKey;
494
+
495
+/**
496
+ Any error associated with the task, or the serialization of the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if an error exists.
497
+ */
498
+FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteErrorKey;
499
+
500
+NS_ASSUME_NONNULL_END

+ 1239
- 0
node_modules/cordova-plugin-advanced-http/src/ios/AFNetworking/AFURLSessionManager.m
Filskillnaden har hållits tillbaka eftersom den är för stor
Visa fil


+ 8
- 0
node_modules/cordova-plugin-advanced-http/src/ios/BinaryRequestSerializer.h Visa fil

@@ -0,0 +1,8 @@
1
+#import <Foundation/Foundation.h>
2
+#import "AFURLRequestSerialization.h"
3
+
4
+@interface BinaryRequestSerializer : AFHTTPRequestSerializer
5
+
6
++ (instancetype)serializer;
7
+
8
+@end

+ 53
- 0
node_modules/cordova-plugin-advanced-http/src/ios/BinaryRequestSerializer.m Visa fil

@@ -0,0 +1,53 @@
1
+#import "BinaryRequestSerializer.h"
2
+
3
+@implementation BinaryRequestSerializer
4
+
5
++ (instancetype)serializer
6
+{
7
+    BinaryRequestSerializer *serializer = [[self alloc] init];
8
+    return serializer;
9
+}
10
+
11
+#pragma mark - AFURLRequestSerialization
12
+
13
+- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
14
+                               withParameters:(id)parameters
15
+                                        error:(NSError *__autoreleasing *)error
16
+{
17
+    NSParameterAssert(request);
18
+
19
+    if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) {
20
+        return [super requestBySerializingRequest:request withParameters:parameters error:error];
21
+    }
22
+
23
+    NSMutableURLRequest *mutableRequest = [request mutableCopy];
24
+
25
+    [self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) {
26
+        if (![request valueForHTTPHeaderField:field]) {
27
+            [mutableRequest setValue:value forHTTPHeaderField:field];
28
+        }
29
+    }];
30
+
31
+    if (parameters) {
32
+        if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) {
33
+            [mutableRequest setValue:@"application/octet-stream" forHTTPHeaderField:@"Content-Type"];
34
+        }
35
+
36
+        [mutableRequest setHTTPBody: parameters];
37
+    }
38
+
39
+    return mutableRequest;
40
+}
41
+
42
+#pragma mark - NSSecureCoding
43
+
44
+- (instancetype)initWithCoder:(NSCoder *)decoder {
45
+    self = [super initWithCoder:decoder];
46
+    if (!self) {
47
+        return nil;
48
+    }
49
+
50
+    return self;
51
+}
52
+
53
+@end

+ 8
- 0
node_modules/cordova-plugin-advanced-http/src/ios/BinaryResponseSerializer.h Visa fil

@@ -0,0 +1,8 @@
1
+#import <Foundation/Foundation.h>
2
+#import "AFURLResponseSerialization.h"
3
+
4
+@interface BinaryResponseSerializer : AFHTTPResponseSerializer
5
+
6
++ (instancetype)serializer;
7
+
8
+@end

+ 126
- 0
node_modules/cordova-plugin-advanced-http/src/ios/BinaryResponseSerializer.m Visa fil

@@ -0,0 +1,126 @@
1
+#import "BinaryResponseSerializer.h"
2
+
3
+static NSError * AFErrorWithUnderlyingError(NSError *error, NSError *underlyingError) {
4
+  if (!error) {
5
+    return underlyingError;
6
+  }
7
+
8
+  if (!underlyingError || error.userInfo[NSUnderlyingErrorKey]) {
9
+    return error;
10
+  }
11
+
12
+  NSMutableDictionary *mutableUserInfo = [error.userInfo mutableCopy];
13
+  mutableUserInfo[NSUnderlyingErrorKey] = underlyingError;
14
+
15
+  return [[NSError alloc] initWithDomain:error.domain code:error.code userInfo:mutableUserInfo];
16
+}
17
+
18
+static BOOL AFErrorOrUnderlyingErrorHasCodeInDomain(NSError *error, NSInteger code, NSString *domain) {
19
+  if ([error.domain isEqualToString:domain] && error.code == code) {
20
+    return YES;
21
+  } else if (error.userInfo[NSUnderlyingErrorKey]) {
22
+    return AFErrorOrUnderlyingErrorHasCodeInDomain(error.userInfo[NSUnderlyingErrorKey], code, domain);
23
+  }
24
+
25
+  return NO;
26
+}
27
+
28
+@implementation BinaryResponseSerializer
29
+
30
++ (instancetype)serializer {
31
+  BinaryResponseSerializer *serializer = [[self alloc] init];
32
+  return serializer;
33
+}
34
+
35
+- (instancetype)init {
36
+  self = [super init];
37
+
38
+  if (!self) {
39
+    return nil;
40
+  }
41
+
42
+  self.acceptableContentTypes = nil;
43
+
44
+  return self;
45
+}
46
+
47
+- (NSString*)decodeResponseData:(NSData*)rawResponseData withEncoding:(CFStringEncoding)cfEncoding {
48
+  NSStringEncoding nsEncoding;
49
+  NSString* decoded = nil;
50
+
51
+  if (cfEncoding != kCFStringEncodingInvalidId) {
52
+    nsEncoding = CFStringConvertEncodingToNSStringEncoding(cfEncoding);
53
+  }
54
+
55
+  NSStringEncoding supportedEncodings[6] = {
56
+    NSUTF8StringEncoding, NSWindowsCP1252StringEncoding, NSISOLatin1StringEncoding,
57
+    NSISOLatin2StringEncoding, NSASCIIStringEncoding, NSUnicodeStringEncoding
58
+  };
59
+
60
+  for (int i = 0; i < sizeof(supportedEncodings) / sizeof(NSStringEncoding) && !decoded; ++i) {
61
+    if (cfEncoding == kCFStringEncodingInvalidId || nsEncoding == supportedEncodings[i]) {
62
+      decoded = [[NSString alloc] initWithData:rawResponseData encoding:supportedEncodings[i]];
63
+    }
64
+  }
65
+
66
+  return decoded;
67
+}
68
+
69
+- (CFStringEncoding) getEncoding:(NSURLResponse *)response {
70
+  CFStringEncoding encoding = kCFStringEncodingInvalidId;
71
+
72
+  if (response.textEncodingName) {
73
+    encoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)response.textEncodingName);
74
+  }
75
+
76
+  return encoding;
77
+}
78
+
79
+#pragma mark -
80
+
81
+- (BOOL)validateResponse:(NSHTTPURLResponse *)response
82
+                    data:(NSData *)data
83
+                   error:(NSError * __autoreleasing *)error
84
+{
85
+  if (response && [response isKindOfClass:[NSHTTPURLResponse class]]) {
86
+    if (self.acceptableStatusCodes && ![self.acceptableStatusCodes containsIndex:(NSUInteger)response.statusCode] && [response URL]) {
87
+      NSMutableDictionary *mutableUserInfo = [@{
88
+        NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Request failed: %@ (%ld)", @"AFNetworking", nil), [NSHTTPURLResponse localizedStringForStatusCode:response.statusCode], (long)response.statusCode],
89
+        NSURLErrorFailingURLErrorKey: [response URL],
90
+        AFNetworkingOperationFailingURLResponseErrorKey: response,
91
+      } mutableCopy];
92
+
93
+      if (data) {
94
+        mutableUserInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] = data;
95
+
96
+        // trying to decode error message in body
97
+        mutableUserInfo[AFNetworkingOperationFailingURLResponseBodyErrorKey] = [self decodeResponseData:data withEncoding:[self getEncoding:response]];
98
+      }
99
+
100
+      if (error) {
101
+        *error = [NSError errorWithDomain:AFURLResponseSerializationErrorDomain code:NSURLErrorBadServerResponse userInfo:mutableUserInfo];
102
+      }
103
+
104
+      return NO;
105
+    }
106
+  }
107
+
108
+  return YES;
109
+}
110
+
111
+#pragma mark - AFURLResponseSerialization
112
+
113
+- (id)responseObjectForResponse:(NSURLResponse *)response
114
+                           data:(NSData *)data
115
+                          error:(NSError *__autoreleasing *)error
116
+{
117
+  if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
118
+    if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {
119
+      return nil;
120
+    }
121
+  }
122
+
123
+  return [data base64EncodedStringWithOptions:0];
124
+}
125
+
126
+@end

+ 19
- 0
node_modules/cordova-plugin-advanced-http/src/ios/CordovaHttpPlugin.h Visa fil

@@ -0,0 +1,19 @@
1
+#import <Foundation/Foundation.h>
2
+
3
+#import <Cordova/CDVPlugin.h>
4
+
5
+@interface CordovaHttpPlugin : CDVPlugin
6
+
7
+- (void)setServerTrustMode:(CDVInvokedUrlCommand*)command;
8
+- (void)setClientAuthMode:(CDVInvokedUrlCommand*)command;
9
+- (void)post:(CDVInvokedUrlCommand*)command;
10
+- (void)put:(CDVInvokedUrlCommand*)command;
11
+- (void)patch:(CDVInvokedUrlCommand*)command;
12
+- (void)get:(CDVInvokedUrlCommand*)command;
13
+- (void)delete:(CDVInvokedUrlCommand*)command;
14
+- (void)head:(CDVInvokedUrlCommand*)command;
15
+- (void)options:(CDVInvokedUrlCommand*)command;
16
+- (void)uploadFiles:(CDVInvokedUrlCommand*)command;
17
+- (void)downloadFile:(CDVInvokedUrlCommand*)command;
18
+
19
+@end

+ 565
- 0
node_modules/cordova-plugin-advanced-http/src/ios/CordovaHttpPlugin.m Visa fil

@@ -0,0 +1,565 @@
1
+#import "CordovaHttpPlugin.h"
2
+#import "CDVFile.h"
3
+#import "BinaryRequestSerializer.h"
4
+#import "BinaryResponseSerializer.h"
5
+#import "TextResponseSerializer.h"
6
+#import "TextRequestSerializer.h"
7
+#import "AFHTTPSessionManager.h"
8
+#import "SDNetworkActivityIndicator.h"
9
+
10
+@interface CordovaHttpPlugin()
11
+
12
+- (void)setRequestHeaders:(NSDictionary*)headers forManager:(AFHTTPSessionManager*)manager;
13
+- (void)handleSuccess:(NSMutableDictionary*)dictionary withResponse:(NSHTTPURLResponse*)response andData:(id)data;
14
+- (void)handleError:(NSMutableDictionary*)dictionary withResponse:(NSHTTPURLResponse*)response error:(NSError*)error;
15
+- (NSNumber*)getStatusCode:(NSError*) error;
16
+- (NSMutableDictionary*)copyHeaderFields:(NSDictionary*)headerFields;
17
+- (void)setTimeout:(NSTimeInterval)timeout forManager:(AFHTTPSessionManager*)manager;
18
+- (void)setRedirect:(bool)redirect forManager:(AFHTTPSessionManager*)manager;
19
+
20
+@end
21
+
22
+@implementation CordovaHttpPlugin {
23
+    AFSecurityPolicy *securityPolicy;
24
+    NSURLCredential *x509Credential;
25
+}
26
+
27
+- (void)pluginInitialize {
28
+    securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
29
+}
30
+
31
+- (void)setRequestSerializer:(NSString*)serializerName forManager:(AFHTTPSessionManager*)manager {
32
+    if ([serializerName isEqualToString:@"json"]) {
33
+        manager.requestSerializer = [AFJSONRequestSerializer serializer];
34
+    } else if ([serializerName isEqualToString:@"utf8"]) {
35
+        manager.requestSerializer = [TextRequestSerializer serializer];
36
+    } else if ([serializerName isEqualToString:@"raw"]) {
37
+        manager.requestSerializer = [BinaryRequestSerializer serializer];
38
+    } else {
39
+        manager.requestSerializer = [AFHTTPRequestSerializer serializer];
40
+    }
41
+}
42
+
43
+- (void)setupAuthChallengeBlock:(AFHTTPSessionManager*)manager {
44
+    [manager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition(
45
+        NSURLSession * _Nonnull session,
46
+        NSURLAuthenticationChallenge * _Nonnull challenge,
47
+        NSURLCredential * _Nullable __autoreleasing * _Nullable credential
48
+    ) {
49
+        if ([challenge.protectionSpace.authenticationMethod isEqualToString: NSURLAuthenticationMethodServerTrust]) {
50
+            *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
51
+
52
+            if (![self->securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) {
53
+                return NSURLSessionAuthChallengeRejectProtectionSpace;
54
+            }
55
+            
56
+            if (credential) {
57
+                return NSURLSessionAuthChallengeUseCredential;
58
+            }
59
+        }
60
+
61
+        if ([challenge.protectionSpace.authenticationMethod isEqualToString: NSURLAuthenticationMethodClientCertificate] && self->x509Credential) {
62
+            *credential = self->x509Credential;
63
+            return NSURLSessionAuthChallengeUseCredential;
64
+        }
65
+        
66
+        return NSURLSessionAuthChallengePerformDefaultHandling;
67
+    }];
68
+}
69
+
70
+- (void)setRequestHeaders:(NSDictionary*)headers forManager:(AFHTTPSessionManager*)manager {
71
+    [headers enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
72
+        [manager.requestSerializer setValue:obj forHTTPHeaderField:key];
73
+    }];
74
+}
75
+
76
+- (void)setRedirect:(bool)followRedirect forManager:(AFHTTPSessionManager*)manager {
77
+    [manager setTaskWillPerformHTTPRedirectionBlock:^NSURLRequest * _Nonnull(NSURLSession * _Nonnull session,
78
+        NSURLSessionTask * _Nonnull task, NSURLResponse * _Nonnull response, NSURLRequest * _Nonnull request) {
79
+
80
+        if (followRedirect) {
81
+            return request;
82
+        } else {
83
+            return nil;
84
+        }
85
+    }];
86
+}
87
+
88
+- (void)setTimeout:(NSTimeInterval)timeout forManager:(AFHTTPSessionManager*)manager {
89
+    [manager.requestSerializer setTimeoutInterval:timeout];
90
+}
91
+
92
+- (void)setResponseSerializer:(NSString*)responseType forManager:(AFHTTPSessionManager*)manager {
93
+    if ([responseType isEqualToString: @"text"] || [responseType isEqualToString: @"json"]) {
94
+        manager.responseSerializer = [TextResponseSerializer serializer];
95
+    } else {
96
+        manager.responseSerializer = [BinaryResponseSerializer serializer];
97
+    }
98
+}
99
+
100
+
101
+- (void)handleSuccess:(NSMutableDictionary*)dictionary withResponse:(NSHTTPURLResponse*)response andData:(id)data {
102
+    if (response != nil) {
103
+        [dictionary setValue:response.URL.absoluteString forKey:@"url"];
104
+        [dictionary setObject:[NSNumber numberWithInt:(int)response.statusCode] forKey:@"status"];
105
+        [dictionary setObject:[self copyHeaderFields:response.allHeaderFields] forKey:@"headers"];
106
+    }
107
+
108
+    if (data != nil) {
109
+        [dictionary setObject:data forKey:@"data"];
110
+    }
111
+}
112
+
113
+- (void)handleError:(NSMutableDictionary*)dictionary withResponse:(NSHTTPURLResponse*)response error:(NSError*)error {
114
+    if (response != nil) {
115
+        [dictionary setValue:response.URL.absoluteString forKey:@"url"];
116
+        [dictionary setObject:[NSNumber numberWithInt:(int)response.statusCode] forKey:@"status"];
117
+        [dictionary setObject:[self copyHeaderFields:response.allHeaderFields] forKey:@"headers"];
118
+        if (error.userInfo[AFNetworkingOperationFailingURLResponseBodyErrorKey]) {
119
+            [dictionary setObject:error.userInfo[AFNetworkingOperationFailingURLResponseBodyErrorKey] forKey:@"error"];
120
+        }
121
+    } else {
122
+        [dictionary setObject:[self getStatusCode:error] forKey:@"status"];
123
+        [dictionary setObject:[error localizedDescription] forKey:@"error"];
124
+    }
125
+}
126
+
127
+- (void)handleException:(NSException*)exception withCommand:(CDVInvokedUrlCommand*)command {
128
+  CordovaHttpPlugin* __weak weakSelf = self;
129
+
130
+  NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
131
+  [dictionary setValue:exception.userInfo forKey:@"error"];
132
+  [dictionary setObject:[NSNumber numberWithInt:-1] forKey:@"status"];
133
+
134
+  CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:dictionary];
135
+  [weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
136
+}
137
+
138
+- (NSNumber*)getStatusCode:(NSError*) error {
139
+    switch ([error code]) {
140
+        case -1001:
141
+            // timeout
142
+            return [NSNumber numberWithInt:-4];
143
+        case -1002:
144
+            // unsupported URL
145
+            return [NSNumber numberWithInt:-5];
146
+        case -1003:
147
+            // server not found
148
+            return [NSNumber numberWithInt:-3];
149
+        case -1009:
150
+            // no connection
151
+            return [NSNumber numberWithInt:-6];
152
+        case -1200: // secure connection failed
153
+        case -1201: // certificate has bad date
154
+        case -1202: // certificate untrusted
155
+        case -1203: // certificate has unknown root
156
+        case -1204: // certificate is not yet valid
157
+            // configuring SSL failed
158
+            return [NSNumber numberWithInt:-2];
159
+        default:
160
+            return [NSNumber numberWithInt:-1];
161
+    }
162
+}
163
+
164
+- (NSMutableDictionary*)copyHeaderFields:(NSDictionary *)headerFields {
165
+    NSMutableDictionary *headerFieldsCopy = [[NSMutableDictionary alloc] initWithCapacity:headerFields.count];
166
+    NSString *headerKeyCopy;
167
+
168
+    for (NSString *headerKey in headerFields.allKeys) {
169
+        headerKeyCopy = [[headerKey mutableCopy] lowercaseString];
170
+        [headerFieldsCopy setValue:[headerFields objectForKey:headerKey] forKey:headerKeyCopy];
171
+    }
172
+
173
+    return headerFieldsCopy;
174
+}
175
+
176
+- (void)executeRequestWithoutData:(CDVInvokedUrlCommand*)command withMethod:(NSString*) method {
177
+    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
178
+
179
+    NSString *url = [command.arguments objectAtIndex:0];
180
+    NSDictionary *headers = [command.arguments objectAtIndex:1];
181
+    NSTimeInterval timeoutInSeconds = [[command.arguments objectAtIndex:2] doubleValue];
182
+    bool followRedirect = [[command.arguments objectAtIndex:3] boolValue];
183
+    NSString *responseType = [command.arguments objectAtIndex:4];
184
+
185
+    [self setRequestSerializer: @"default" forManager: manager];
186
+    [self setupAuthChallengeBlock: manager];
187
+    [self setRequestHeaders: headers forManager: manager];
188
+    [self setTimeout:timeoutInSeconds forManager:manager];
189
+    [self setRedirect:followRedirect forManager:manager];
190
+    [self setResponseSerializer:responseType forManager:manager];
191
+
192
+    CordovaHttpPlugin* __weak weakSelf = self;
193
+    [[SDNetworkActivityIndicator sharedActivityIndicator] startActivity];
194
+
195
+    @try {
196
+        void (^onSuccess)(NSURLSessionTask *, id) = ^(NSURLSessionTask *task, id responseObject) {
197
+            NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
198
+            
199
+            // no 'body' for HEAD request, omitting 'data'
200
+            if ([method isEqualToString:@"HEAD"]) {
201
+                [self handleSuccess:dictionary withResponse:(NSHTTPURLResponse*)task.response andData:nil];
202
+            } else {
203
+                [self handleSuccess:dictionary withResponse:(NSHTTPURLResponse*)task.response andData:responseObject];
204
+            }
205
+            
206
+            CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:dictionary];
207
+            [weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
208
+            [[SDNetworkActivityIndicator sharedActivityIndicator] stopActivity];
209
+        };
210
+        
211
+        void (^onFailure)(NSURLSessionTask *, NSError *) = ^(NSURLSessionTask *task, NSError *error) {
212
+            NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
213
+            [self handleError:dictionary withResponse:(NSHTTPURLResponse*)task.response error:error];
214
+            
215
+            CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:dictionary];
216
+            [weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
217
+            [[SDNetworkActivityIndicator sharedActivityIndicator] stopActivity];
218
+        };
219
+        
220
+        [manager downloadTaskWithHTTPMethod:method URLString:url parameters:nil progress:nil success:onSuccess failure:onFailure];
221
+    }
222
+    @catch (NSException *exception) {
223
+        [[SDNetworkActivityIndicator sharedActivityIndicator] stopActivity];
224
+        [self handleException:exception withCommand:command];
225
+    }
226
+}
227
+
228
+- (void)executeRequestWithData:(CDVInvokedUrlCommand*)command withMethod:(NSString*)method {
229
+    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
230
+
231
+    NSString *url = [command.arguments objectAtIndex:0];
232
+    NSDictionary *data = [command.arguments objectAtIndex:1];
233
+    NSString *serializerName = [command.arguments objectAtIndex:2];
234
+    NSDictionary *headers = [command.arguments objectAtIndex:3];
235
+    NSTimeInterval timeoutInSeconds = [[command.arguments objectAtIndex:4] doubleValue];
236
+    bool followRedirect = [[command.arguments objectAtIndex:5] boolValue];
237
+    NSString *responseType = [command.arguments objectAtIndex:6];
238
+
239
+    [self setRequestSerializer: serializerName forManager: manager];
240
+    [self setupAuthChallengeBlock: manager];
241
+    [self setRequestHeaders: headers forManager: manager];
242
+    [self setTimeout:timeoutInSeconds forManager:manager];
243
+    [self setRedirect:followRedirect forManager:manager];
244
+    [self setResponseSerializer:responseType forManager:manager];
245
+
246
+    CordovaHttpPlugin* __weak weakSelf = self;
247
+    [[SDNetworkActivityIndicator sharedActivityIndicator] startActivity];
248
+    
249
+    @try {
250
+        void (^constructBody)(id<AFMultipartFormData>) = ^(id<AFMultipartFormData> formData) {
251
+            NSArray *buffers = [data mutableArrayValueForKey:@"buffers"];
252
+            NSArray *fileNames = [data mutableArrayValueForKey:@"fileNames"];
253
+            NSArray *names = [data mutableArrayValueForKey:@"names"];
254
+            NSArray *types = [data mutableArrayValueForKey:@"types"];
255
+            
256
+            NSError *error;
257
+            
258
+            for (int i = 0; i < [buffers count]; ++i) {
259
+                NSData *decodedBuffer = [[NSData alloc] initWithBase64EncodedString:[buffers objectAtIndex:i] options:0];
260
+                NSString *fileName = [fileNames objectAtIndex:i];
261
+                NSString *partName = [names objectAtIndex:i];
262
+                NSString *partType = [types objectAtIndex:i];
263
+                
264
+                if (![fileName isEqual:[NSNull null]]) {
265
+                    [formData appendPartWithFileData:decodedBuffer name:partName fileName:fileName mimeType:partType];
266
+                } else {
267
+                    [formData appendPartWithFormData:decodedBuffer name:[names objectAtIndex:i]];
268
+                }
269
+            }
270
+            
271
+            if (error) {
272
+                NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
273
+                [dictionary setObject:[NSNumber numberWithInt:400] forKey:@"status"];
274
+                [dictionary setObject:@"Could not add part to multipart request body." forKey:@"error"];
275
+                CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:dictionary];
276
+                [weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
277
+                [[SDNetworkActivityIndicator sharedActivityIndicator] stopActivity];
278
+                return;
279
+            }
280
+        };
281
+        
282
+        void (^onSuccess)(NSURLSessionTask *, id) = ^(NSURLSessionTask *task, id responseObject) {
283
+            NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
284
+            [self handleSuccess:dictionary withResponse:(NSHTTPURLResponse*)task.response andData:responseObject];
285
+            
286
+            CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:dictionary];
287
+            [weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
288
+            [[SDNetworkActivityIndicator sharedActivityIndicator] stopActivity];
289
+        };
290
+        
291
+        void (^onFailure)(NSURLSessionTask *, NSError *) = ^(NSURLSessionTask *task, NSError *error) {
292
+            NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
293
+            [self handleError:dictionary withResponse:(NSHTTPURLResponse*)task.response error:error];
294
+            
295
+            CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:dictionary];
296
+            [weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
297
+            [[SDNetworkActivityIndicator sharedActivityIndicator] stopActivity];
298
+        };
299
+        
300
+        if ([serializerName isEqualToString:@"multipart"]) {
301
+            [manager uploadTaskWithHTTPMethod:method URLString:url parameters:nil constructingBodyWithBlock:constructBody progress:nil success:onSuccess failure:onFailure];
302
+        } else {
303
+            [manager uploadTaskWithHTTPMethod:method URLString:url parameters:data progress:nil success:onSuccess failure:onFailure];
304
+        }
305
+    }
306
+    @catch (NSException *exception) {
307
+        [[SDNetworkActivityIndicator sharedActivityIndicator] stopActivity];
308
+        [self handleException:exception withCommand:command];
309
+    }
310
+}
311
+
312
+- (void)setServerTrustMode:(CDVInvokedUrlCommand*)command {
313
+    NSString *certMode = [command.arguments objectAtIndex:0];
314
+
315
+    if ([certMode isEqualToString: @"default"] || [certMode isEqualToString: @"legacy"]) {
316
+        securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
317
+        securityPolicy.allowInvalidCertificates = NO;
318
+        securityPolicy.validatesDomainName = YES;
319
+    } else if ([certMode isEqualToString: @"nocheck"]) {
320
+        securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
321
+        securityPolicy.allowInvalidCertificates = YES;
322
+        securityPolicy.validatesDomainName = NO;
323
+    } else if ([certMode isEqualToString: @"pinned"]) {
324
+        securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
325
+        securityPolicy.allowInvalidCertificates = NO;
326
+        securityPolicy.validatesDomainName = YES;
327
+    }
328
+
329
+    CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
330
+    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
331
+}
332
+
333
+- (void)setClientAuthMode:(CDVInvokedUrlCommand*)command {
334
+    CDVPluginResult* pluginResult;
335
+    NSString *mode = [command.arguments objectAtIndex:0];
336
+    
337
+    if ([mode isEqualToString:@"none"]) {
338
+      x509Credential = nil;
339
+      pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
340
+    }
341
+  
342
+    if ([mode isEqualToString:@"systemstore"]) {
343
+      NSString *alias = [command.arguments objectAtIndex:1];
344
+      
345
+      // TODO
346
+      
347
+      pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"mode 'systemstore' is not supported on iOS"];
348
+    }
349
+  
350
+    if ([mode isEqualToString:@"buffer"]) {
351
+        CFDataRef container = (__bridge CFDataRef) [command.arguments objectAtIndex:2];
352
+        CFStringRef password = (__bridge CFStringRef) [command.arguments objectAtIndex:3];
353
+      
354
+        const void *keys[] = { kSecImportExportPassphrase };
355
+        const void *values[] = { password };
356
+      
357
+        CFDictionaryRef options = CFDictionaryCreate(NULL, keys, values, 1, NULL, NULL);
358
+        CFArrayRef items;
359
+        OSStatus securityError = SecPKCS12Import(container, options, &items);
360
+        CFRelease(options);
361
+
362
+        if (securityError != noErr) {
363
+            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR];
364
+        } else {
365
+            CFDictionaryRef identityDict = CFArrayGetValueAtIndex(items, 0);
366
+            SecIdentityRef identity = (SecIdentityRef)CFDictionaryGetValue(identityDict, kSecImportItemIdentity);
367
+
368
+            self->x509Credential = [NSURLCredential credentialWithIdentity:identity certificates: nil persistence:NSURLCredentialPersistenceForSession];
369
+            CFRelease(items);
370
+          
371
+            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
372
+        }
373
+    }
374
+
375
+    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
376
+}
377
+
378
+- (void)post:(CDVInvokedUrlCommand*)command {
379
+    [self executeRequestWithData: command withMethod:@"POST"];
380
+}
381
+
382
+- (void)put:(CDVInvokedUrlCommand*)command {
383
+    [self executeRequestWithData: command withMethod:@"PUT"];
384
+}
385
+
386
+- (void)patch:(CDVInvokedUrlCommand*)command {
387
+    [self executeRequestWithData: command withMethod:@"PATCH"];
388
+}
389
+
390
+- (void)get:(CDVInvokedUrlCommand*)command {
391
+    [self executeRequestWithoutData: command withMethod:@"GET"];
392
+}
393
+
394
+- (void)delete:(CDVInvokedUrlCommand*)command {
395
+    [self executeRequestWithoutData: command withMethod:@"DELETE"];
396
+}
397
+
398
+- (void)head:(CDVInvokedUrlCommand*)command {
399
+    [self executeRequestWithoutData: command withMethod:@"HEAD"];
400
+}
401
+
402
+- (void)options:(CDVInvokedUrlCommand*)command {
403
+    [self executeRequestWithoutData: command withMethod:@"OPTIONS"];
404
+}
405
+
406
+- (void)uploadFiles:(CDVInvokedUrlCommand*)command {
407
+    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
408
+
409
+    NSString *url = [command.arguments objectAtIndex:0];
410
+    NSDictionary *headers = [command.arguments objectAtIndex:1];
411
+    NSArray *filePaths = [command.arguments objectAtIndex: 2];
412
+    NSArray *names = [command.arguments objectAtIndex: 3];
413
+    NSTimeInterval timeoutInSeconds = [[command.arguments objectAtIndex:4] doubleValue];
414
+    bool followRedirect = [[command.arguments objectAtIndex:5] boolValue];
415
+    NSString *responseType = [command.arguments objectAtIndex:6];
416
+
417
+    [self setRequestHeaders: headers forManager: manager];
418
+    [self setupAuthChallengeBlock: manager];
419
+    [self setTimeout:timeoutInSeconds forManager:manager];
420
+    [self setRedirect:followRedirect forManager:manager];
421
+    [self setResponseSerializer:responseType forManager:manager];
422
+
423
+    CordovaHttpPlugin* __weak weakSelf = self;
424
+    [[SDNetworkActivityIndicator sharedActivityIndicator] startActivity];
425
+
426
+    @try {
427
+        [manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
428
+            NSError *error;
429
+            for (int i = 0; i < [filePaths count]; i++) {
430
+                NSString *filePath = (NSString *) [filePaths objectAtIndex:i];
431
+                NSString *uploadName = (NSString *) [names objectAtIndex:i];
432
+                NSURL *fileURL = [NSURL URLWithString: filePath];
433
+                [formData appendPartWithFileURL:fileURL name:uploadName error:&error];
434
+            }
435
+            if (error) {
436
+                NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
437
+                [dictionary setObject:[NSNumber numberWithInt:500] forKey:@"status"];
438
+                [dictionary setObject:@"Could not add file to post body." forKey:@"error"];
439
+                CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:dictionary];
440
+                [weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
441
+                [[SDNetworkActivityIndicator sharedActivityIndicator] stopActivity];
442
+                return;
443
+            }
444
+        } progress:nil success:^(NSURLSessionTask *task, id responseObject) {
445
+            NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
446
+            [self handleSuccess:dictionary withResponse:(NSHTTPURLResponse*)task.response andData:responseObject];
447
+
448
+            CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:dictionary];
449
+            [weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
450
+            [[SDNetworkActivityIndicator sharedActivityIndicator] stopActivity];
451
+        } failure:^(NSURLSessionTask *task, NSError *error) {
452
+            NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
453
+            [self handleError:dictionary withResponse:(NSHTTPURLResponse*)task.response error:error];
454
+
455
+            CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:dictionary];
456
+            [weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
457
+            [[SDNetworkActivityIndicator sharedActivityIndicator] stopActivity];
458
+        }];
459
+    }
460
+    @catch (NSException *exception) {
461
+        [[SDNetworkActivityIndicator sharedActivityIndicator] stopActivity];
462
+        [self handleException:exception withCommand:command];
463
+    }
464
+}
465
+
466
+- (void)downloadFile:(CDVInvokedUrlCommand*)command {
467
+    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
468
+    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
469
+
470
+    NSString *url = [command.arguments objectAtIndex:0];
471
+    NSDictionary *headers = [command.arguments objectAtIndex:1];
472
+    NSString *filePath = [command.arguments objectAtIndex: 2];
473
+    NSTimeInterval timeoutInSeconds = [[command.arguments objectAtIndex:3] doubleValue];
474
+    bool followRedirect = [[command.arguments objectAtIndex:4] boolValue];
475
+
476
+    [self setRequestHeaders: headers forManager: manager];
477
+    [self setupAuthChallengeBlock: manager];
478
+    [self setTimeout:timeoutInSeconds forManager:manager];
479
+    [self setRedirect:followRedirect forManager:manager];
480
+
481
+    if ([filePath hasPrefix:@"file://"]) {
482
+        filePath = [filePath substringFromIndex:7];
483
+    }
484
+
485
+    CordovaHttpPlugin* __weak weakSelf = self;
486
+    [[SDNetworkActivityIndicator sharedActivityIndicator] startActivity];
487
+
488
+    @try {
489
+        [manager GET:url parameters:nil progress: nil success:^(NSURLSessionTask *task, id responseObject) {
490
+            /*
491
+             *
492
+             * Licensed to the Apache Software Foundation (ASF) under one
493
+             * or more contributor license agreements.  See the NOTICE file
494
+             * distributed with this work for additional information
495
+             * regarding copyright ownership.  The ASF licenses this file
496
+             * to you under the Apache License, Version 2.0 (the
497
+             * "License"); you may not use this file except in compliance
498
+             * with the License.  You may obtain a copy of the License at
499
+             *
500
+             *   http://www.apache.org/licenses/LICENSE-2.0
501
+             *
502
+             * Unless required by applicable law or agreed to in writing,
503
+             * software distributed under the License is distributed on an
504
+             * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
505
+             * KIND, either express or implied.  See the License for the
506
+             * specific language governing permissions and limitations
507
+             * under the License.
508
+             *
509
+             * Modified by Andrew Stephan for Sync OnSet
510
+             *
511
+             */
512
+            // Download response is okay; begin streaming output to file
513
+            NSString* parentPath = [filePath stringByDeletingLastPathComponent];
514
+
515
+            // create parent directories if needed
516
+            NSError *error;
517
+            if ([[NSFileManager defaultManager] createDirectoryAtPath:parentPath withIntermediateDirectories:YES attributes:nil error:&error] == NO) {
518
+                NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
519
+                [dictionary setObject:[NSNumber numberWithInt:500] forKey:@"status"];
520
+                if (error) {
521
+                    [dictionary setObject:[NSString stringWithFormat:@"Could not create path to save downloaded file: %@", [error localizedDescription]] forKey:@"error"];
522
+                } else {
523
+                    [dictionary setObject:@"Could not create path to save downloaded file" forKey:@"error"];
524
+                }
525
+                CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:dictionary];
526
+                [weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
527
+                [[SDNetworkActivityIndicator sharedActivityIndicator] stopActivity];
528
+                return;
529
+            }
530
+            NSData *data = (NSData *)responseObject;
531
+            if (![data writeToFile:filePath atomically:YES]) {
532
+                NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
533
+                [dictionary setObject:[NSNumber numberWithInt:500] forKey:@"status"];
534
+                [dictionary setObject:@"Could not write the data to the given filePath." forKey:@"error"];
535
+                CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:dictionary];
536
+                [weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
537
+                [[SDNetworkActivityIndicator sharedActivityIndicator] stopActivity];
538
+                return;
539
+            }
540
+
541
+            id filePlugin = [self.commandDelegate getCommandInstance:@"File"];
542
+            NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
543
+            [self handleSuccess:dictionary withResponse:(NSHTTPURLResponse*)task.response andData:nil];
544
+            [dictionary setObject:[filePlugin getDirectoryEntry:filePath isDirectory:NO] forKey:@"file"];
545
+
546
+            CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:dictionary];
547
+            [weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
548
+            [[SDNetworkActivityIndicator sharedActivityIndicator] stopActivity];
549
+        } failure:^(NSURLSessionTask *task, NSError *error) {
550
+            NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
551
+            [self handleError:dictionary withResponse:(NSHTTPURLResponse*)task.response error:error];
552
+            [dictionary setObject:@"There was an error downloading the file" forKey:@"error"];
553
+
554
+            CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:dictionary];
555
+            [weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
556
+            [[SDNetworkActivityIndicator sharedActivityIndicator] stopActivity];
557
+        }];
558
+    }
559
+    @catch (NSException *exception) {
560
+        [[SDNetworkActivityIndicator sharedActivityIndicator] stopActivity];
561
+        [self handleException:exception withCommand:command];
562
+    }
563
+}
564
+
565
+@end

+ 20
- 0
node_modules/cordova-plugin-advanced-http/src/ios/SDNetworkActivityIndicator/LICENSE Visa fil

@@ -0,0 +1,20 @@
1
+Copyright (c) 2010 Olivier Poitrey <rs@dailymotion.com>
2
+ 
3
+Permission is hereby granted, free of charge, to any person obtaining a copy
4
+of this software and associated documentation files (the "Software"), to deal
5
+in the Software without restriction, including without limitation the rights
6
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+copies of the Software, and to permit persons to whom the Software is furnished
8
+to do so, subject to the following conditions:
9
+ 
10
+The above copyright notice and this permission notice shall be included in all
11
+copies or substantial portions of the Software.
12
+ 
13
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19
+THE SOFTWARE.
20
+

+ 52
- 0
node_modules/cordova-plugin-advanced-http/src/ios/SDNetworkActivityIndicator/README.md Visa fil

@@ -0,0 +1,52 @@
1
+# SDNetworkActivityIndicator
2
+
3
+Handle showing / hiding of the iOS network activity indicator to allow multiple concurrent threads to show / hide the indicator such that the indicator remains visible until all the requests have completed and requested the indicator to be hidden.
4
+
5
+## Requirements
6
+
7
+* iOS 5.0 or later.
8
+* ARC memory management.
9
+
10
+## Installation
11
+
12
+The easiest way to install it is by copying the following files to your project:
13
+
14
+* SDNetworkActivityIndicator.h
15
+* SDNetworkActivityIndicator.m
16
+
17
+## Usage
18
+
19
+* When you start a network activity (will show the network activity indicator):
20
+
21
+        [[SDNetworkActivityIndicator sharedActivityIndicator] startActivity];
22
+
23
+* When you finish a network activity (will hide the network activity indicator only if the number of calls to `stopActivity` matches the number of calls to `startActivity`):
24
+
25
+        [[SDNetworkActivityIndicator sharedActivityIndicator] stopActivity];
26
+
27
+* To hide the network activity indicator regardless of whether all activities have finished (without having to call `stopActivity` for each `startActivity` called):
28
+
29
+        [[SDNetworkActivityIndicator sharedActivityIndicator] stopAllActivity];
30
+
31
+
32
+## License
33
+Copyright (c) 2010 Olivier Poitrey <rs@dailymotion.com>
34
+ 
35
+Permission is hereby granted, free of charge, to any person obtaining a copy
36
+of this software and associated documentation files (the "Software"), to deal
37
+in the Software without restriction, including without limitation the rights
38
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
39
+copies of the Software, and to permit persons to whom the Software is furnished
40
+to do so, subject to the following conditions:
41
+ 
42
+The above copyright notice and this permission notice shall be included in all
43
+copies or substantial portions of the Software.
44
+ 
45
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
46
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
47
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
48
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
49
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
50
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
51
+THE SOFTWARE.
52
+

+ 18
- 0
node_modules/cordova-plugin-advanced-http/src/ios/SDNetworkActivityIndicator/SDNetworkActivityIndicator.h Visa fil

@@ -0,0 +1,18 @@
1
+/*
2
+ * This file is part of the SDNetworkActivityIndicator package.
3
+ * (c) Olivier Poitrey <rs@dailymotion.com>
4
+ *
5
+ * For the full copyright and license information, please view the LICENSE
6
+ * file that was distributed with this source code.
7
+ */
8
+
9
+#import <Foundation/Foundation.h>
10
+
11
+@interface SDNetworkActivityIndicator : NSObject
12
+
13
++ (id)sharedActivityIndicator;
14
+- (void)startActivity;
15
+- (void)stopActivity;
16
+- (void)stopAllActivity;
17
+
18
+@end

+ 70
- 0
node_modules/cordova-plugin-advanced-http/src/ios/SDNetworkActivityIndicator/SDNetworkActivityIndicator.m Visa fil

@@ -0,0 +1,70 @@
1
+/*
2
+ * This file is part of the SDNetworkActivityIndicator package.
3
+ * (c) Olivier Poitrey <rs@dailymotion.com>
4
+ *
5
+ * For the full copyright and license information, please view the LICENSE
6
+ * file that was distributed with this source code.
7
+ */
8
+
9
+#import "SDNetworkActivityIndicator.h"
10
+
11
+@interface SDNetworkActivityIndicator()
12
+{
13
+    @private NSUInteger counter;
14
+}
15
+@end
16
+
17
+
18
+@implementation SDNetworkActivityIndicator
19
+
20
++ (instancetype) sharedActivityIndicator
21
+{
22
+    static id _sharedInstance = nil;
23
+    static dispatch_once_t onceToken;
24
+    dispatch_once(&onceToken, ^{
25
+        _sharedInstance = [[self alloc] init];
26
+    });
27
+    
28
+    return _sharedInstance;
29
+}
30
+
31
+- (id)init
32
+{
33
+    if ((self = [super init]))
34
+    {
35
+        counter = 0;
36
+    }
37
+
38
+    return self;
39
+}
40
+
41
+- (void)startActivity
42
+{
43
+    @synchronized(self)
44
+    {
45
+        counter++;
46
+        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
47
+    }
48
+}
49
+
50
+- (void)stopActivity
51
+{
52
+    @synchronized(self)
53
+    {
54
+        if (counter > 0 && --counter == 0)
55
+        {
56
+            [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
57
+        }
58
+    }
59
+}
60
+
61
+- (void)stopAllActivity
62
+{
63
+    @synchronized(self)
64
+    {
65
+        counter = 0;
66
+        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
67
+    }
68
+}
69
+
70
+@end

+ 8
- 0
node_modules/cordova-plugin-advanced-http/src/ios/TextRequestSerializer.h Visa fil

@@ -0,0 +1,8 @@
1
+#import <Foundation/Foundation.h>
2
+#import "AFURLRequestSerialization.h"
3
+
4
+@interface TextRequestSerializer : AFHTTPRequestSerializer
5
+
6
++ (instancetype)serializer;
7
+
8
+@end

+ 53
- 0
node_modules/cordova-plugin-advanced-http/src/ios/TextRequestSerializer.m Visa fil

@@ -0,0 +1,53 @@
1
+#import "TextRequestSerializer.h"
2
+
3
+@implementation TextRequestSerializer
4
+
5
++ (instancetype)serializer
6
+{
7
+    TextRequestSerializer *serializer = [[self alloc] init];
8
+    return serializer;
9
+}
10
+
11
+#pragma mark - AFURLRequestSerialization
12
+
13
+- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
14
+                               withParameters:(id)parameters
15
+                                        error:(NSError *__autoreleasing *)error
16
+{
17
+    NSParameterAssert(request);
18
+
19
+    if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) {
20
+        return [super requestBySerializingRequest:request withParameters:parameters error:error];
21
+    }
22
+
23
+    NSMutableURLRequest *mutableRequest = [request mutableCopy];
24
+
25
+    [self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) {
26
+        if (![request valueForHTTPHeaderField:field]) {
27
+            [mutableRequest setValue:value forHTTPHeaderField:field];
28
+        }
29
+    }];
30
+
31
+    if (parameters) {
32
+        if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) {
33
+            [mutableRequest setValue:@"text/plain; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
34
+        }
35
+
36
+        [mutableRequest setHTTPBody: [[parameters valueForKey:@"text"] dataUsingEncoding:NSUTF8StringEncoding]];
37
+    }
38
+
39
+    return mutableRequest;
40
+}
41
+
42
+#pragma mark - NSSecureCoding
43
+
44
+- (instancetype)initWithCoder:(NSCoder *)decoder {
45
+    self = [super initWithCoder:decoder];
46
+    if (!self) {
47
+        return nil;
48
+    }
49
+
50
+    return self;
51
+}
52
+
53
+@end

+ 8
- 0
node_modules/cordova-plugin-advanced-http/src/ios/TextResponseSerializer.h Visa fil

@@ -0,0 +1,8 @@
1
+#import <Foundation/Foundation.h>
2
+#import "AFURLResponseSerialization.h"
3
+
4
+@interface TextResponseSerializer : AFHTTPResponseSerializer
5
+
6
++ (instancetype)serializer;
7
+
8
+@end

+ 145
- 0
node_modules/cordova-plugin-advanced-http/src/ios/TextResponseSerializer.m Visa fil

@@ -0,0 +1,145 @@
1
+#import "TextResponseSerializer.h"
2
+
3
+static NSError * AFErrorWithUnderlyingError(NSError *error, NSError *underlyingError) {
4
+  if (!error) {
5
+    return underlyingError;
6
+  }
7
+
8
+  if (!underlyingError || error.userInfo[NSUnderlyingErrorKey]) {
9
+    return error;
10
+  }
11
+
12
+  NSMutableDictionary *mutableUserInfo = [error.userInfo mutableCopy];
13
+  mutableUserInfo[NSUnderlyingErrorKey] = underlyingError;
14
+
15
+  return [[NSError alloc] initWithDomain:error.domain code:error.code userInfo:mutableUserInfo];
16
+}
17
+
18
+static BOOL AFErrorOrUnderlyingErrorHasCodeInDomain(NSError *error, NSInteger code, NSString *domain) {
19
+  if ([error.domain isEqualToString:domain] && error.code == code) {
20
+    return YES;
21
+  } else if (error.userInfo[NSUnderlyingErrorKey]) {
22
+    return AFErrorOrUnderlyingErrorHasCodeInDomain(error.userInfo[NSUnderlyingErrorKey], code, domain);
23
+  }
24
+
25
+  return NO;
26
+}
27
+
28
+@implementation TextResponseSerializer
29
+
30
++ (instancetype)serializer {
31
+  TextResponseSerializer *serializer = [[self alloc] init];
32
+  return serializer;
33
+}
34
+
35
+- (instancetype)init {
36
+  self = [super init];
37
+
38
+  if (!self) {
39
+    return nil;
40
+  }
41
+
42
+  self.acceptableContentTypes = nil;
43
+
44
+  return self;
45
+}
46
+
47
+- (NSString*)decodeResponseData:(NSData*)rawResponseData withEncoding:(CFStringEncoding)cfEncoding {
48
+  NSStringEncoding nsEncoding;
49
+  NSString* decoded = nil;
50
+
51
+  if (cfEncoding != kCFStringEncodingInvalidId) {
52
+    nsEncoding = CFStringConvertEncodingToNSStringEncoding(cfEncoding);
53
+  }
54
+
55
+  NSStringEncoding supportedEncodings[6] = {
56
+    NSUTF8StringEncoding, NSWindowsCP1252StringEncoding, NSISOLatin1StringEncoding,
57
+    NSISOLatin2StringEncoding, NSASCIIStringEncoding, NSUnicodeStringEncoding
58
+  };
59
+
60
+  for (int i = 0; i < sizeof(supportedEncodings) / sizeof(NSStringEncoding) && !decoded; ++i) {
61
+    if (cfEncoding == kCFStringEncodingInvalidId || nsEncoding == supportedEncodings[i]) {
62
+      decoded = [[NSString alloc] initWithData:rawResponseData encoding:supportedEncodings[i]];
63
+    }
64
+  }
65
+
66
+  return decoded;
67
+}
68
+
69
+- (CFStringEncoding) getEncoding:(NSURLResponse *)response {
70
+  CFStringEncoding encoding = kCFStringEncodingInvalidId;
71
+
72
+  if (response.textEncodingName) {
73
+    encoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)response.textEncodingName);
74
+  }
75
+
76
+  return encoding;
77
+}
78
+
79
+#pragma mark -
80
+
81
+- (BOOL)validateResponse:(NSHTTPURLResponse *)response
82
+                    data:(NSData *)data
83
+                 decoded:(NSString **)decoded
84
+                   error:(NSError * __autoreleasing *)error
85
+{
86
+  BOOL responseIsValid = YES;
87
+  NSError *validationError = nil;
88
+
89
+  if (response && [response isKindOfClass:[NSHTTPURLResponse class]]) {
90
+    if (data) {
91
+      *decoded = [self decodeResponseData:data withEncoding:[self getEncoding:response]];
92
+    }
93
+
94
+    if (data && !*decoded) {
95
+      NSMutableDictionary *mutableUserInfo = [@{
96
+        NSURLErrorFailingURLErrorKey:[response URL],
97
+        AFNetworkingOperationFailingURLResponseErrorKey: response,
98
+        AFNetworkingOperationFailingURLResponseDataErrorKey: data,
99
+        AFNetworkingOperationFailingURLResponseBodyErrorKey: @"Could not decode response data due to invalid or unknown charset encoding",
100
+      } mutableCopy];
101
+
102
+      validationError = AFErrorWithUnderlyingError([NSError errorWithDomain:AFURLResponseSerializationErrorDomain code:NSURLErrorBadServerResponse userInfo:mutableUserInfo], validationError);
103
+      responseIsValid = NO;
104
+    } else if (self.acceptableStatusCodes && ![self.acceptableStatusCodes containsIndex:(NSUInteger)response.statusCode] && [response URL]) {
105
+      NSMutableDictionary *mutableUserInfo = [@{
106
+        NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Request failed: %@ (%ld)", @"AFNetworking", nil), [NSHTTPURLResponse localizedStringForStatusCode:response.statusCode], (long)response.statusCode],
107
+        NSURLErrorFailingURLErrorKey: [response URL],
108
+        AFNetworkingOperationFailingURLResponseErrorKey: response,
109
+      } mutableCopy];
110
+
111
+      if (data) {
112
+        mutableUserInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] = data;
113
+        mutableUserInfo[AFNetworkingOperationFailingURLResponseBodyErrorKey] = *decoded;
114
+      }
115
+
116
+      validationError = AFErrorWithUnderlyingError([NSError errorWithDomain:AFURLResponseSerializationErrorDomain code:NSURLErrorBadServerResponse userInfo:mutableUserInfo], validationError);
117
+      responseIsValid = NO;
118
+    }
119
+  }
120
+
121
+  if (error && !responseIsValid) {
122
+    *error = validationError;
123
+  }
124
+
125
+  return responseIsValid;
126
+}
127
+
128
+#pragma mark - AFURLResponseSerialization
129
+
130
+- (id)responseObjectForResponse:(NSURLResponse *)response
131
+                           data:(NSData *)data
132
+                          error:(NSError *__autoreleasing *)error
133
+{
134
+  NSString* decoded = nil;
135
+
136
+  if (![self validateResponse:(NSHTTPURLResponse *)response data:data decoded:&decoded error:error]) {
137
+    if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {
138
+      return nil;
139
+    }
140
+  }
141
+
142
+  return decoded;
143
+}
144
+
145
+@end

+ 25
- 0
node_modules/cordova-plugin-advanced-http/www/advanced-http.js Visa fil

@@ -0,0 +1,25 @@
1
+/*
2
+ * A native HTTP Plugin for Cordova / PhoneGap.
3
+ */
4
+
5
+var pluginId = module.id.slice(0, module.id.lastIndexOf('.'));
6
+
7
+var exec = require('cordova/exec');
8
+var base64 = require('cordova/base64');
9
+var messages = require(pluginId + '.messages');
10
+var errorCodes = require(pluginId + '.error-codes');
11
+var globalConfigs = require(pluginId + '.global-configs');
12
+var jsUtil = require(pluginId + '.js-util');
13
+var ToughCookie = require(pluginId + '.tough-cookie');
14
+var lodash = require(pluginId + '.lodash');
15
+var WebStorageCookieStore = require(pluginId + '.local-storage-store')(ToughCookie, lodash);
16
+var cookieHandler = require(pluginId + '.cookie-handler')(window.localStorage, ToughCookie, WebStorageCookieStore);
17
+var dependencyValidator = require(pluginId + '.dependency-validator')(window, window.console, messages);
18
+var ponyfills = require(pluginId + '.ponyfills')(window);
19
+var helpers = require(pluginId + '.helpers')(window, jsUtil, cookieHandler, messages, base64, errorCodes, dependencyValidator, ponyfills);
20
+var urlUtil = require(pluginId + '.url-util')(jsUtil);
21
+var publicInterface = require(pluginId + '.public-interface')(exec, cookieHandler, urlUtil, helpers, globalConfigs, errorCodes, ponyfills);
22
+
23
+dependencyValidator.logWarnings();
24
+
25
+module.exports = publicInterface;

+ 70
- 0
node_modules/cordova-plugin-advanced-http/www/cookie-handler.js Visa fil

@@ -0,0 +1,70 @@
1
+module.exports = function init(storage, ToughCookie, WebStorageCookieStore) {
2
+  var storeKey = '__advancedHttpCookieStore__';
3
+
4
+  var store = new WebStorageCookieStore(storage, storeKey);
5
+  var cookieJar = new ToughCookie.CookieJar(store);
6
+
7
+  return {
8
+    setCookieFromString: setCookieFromString,
9
+    setCookie: setCookie,
10
+    getCookieString: getCookieString,
11
+    clearCookies: clearCookies,
12
+    removeCookies: removeCookies
13
+  };
14
+
15
+  function splitCookieString(cookieStr) {
16
+    var cookieParts = cookieStr.split(',');
17
+    var splitCookies = [];
18
+    var processedCookie = null;
19
+
20
+    for (var i = 0; i < cookieParts.length; ++i) {
21
+      if (cookieParts[i].substr(-11, 8).toLowerCase() === 'expires=') {
22
+        processedCookie = cookieParts[i] + ',' + cookieParts[i + 1];
23
+        i++;
24
+      } else {
25
+        processedCookie = cookieParts[i];
26
+      }
27
+
28
+      processedCookie = processedCookie.trim();
29
+      splitCookies.push(processedCookie);
30
+    }
31
+
32
+    return splitCookies;
33
+  }
34
+
35
+  function setCookieFromString(url, cookieStr) {
36
+    if (!cookieStr) return;
37
+
38
+    var cookies = splitCookieString(cookieStr);
39
+
40
+    for (var i = 0; i < cookies.length; ++i) {
41
+      cookieJar.setCookieSync(cookies[i], url, { ignoreError: true });
42
+    }
43
+  }
44
+
45
+  function setCookie(url, cookie, options) {
46
+    options = options || {};
47
+    options.ignoreError = false;
48
+    cookieJar.setCookieSync(cookie, url, options);
49
+  }
50
+
51
+  function getCookieString(url) {
52
+    return cookieJar.getCookieStringSync(url);
53
+  }
54
+
55
+  function clearCookies() {
56
+    window.localStorage.removeItem(storeKey);
57
+  }
58
+
59
+  function removeCookies(url, cb) {
60
+    cookieJar.getCookies(url, function (error, cookies) {
61
+      if (!cookies || cookies.length === 0) {
62
+        return cb(null, []);
63
+      }
64
+
65
+      var domain = cookies[0].domain;
66
+
67
+      cookieJar.store.removeCookies(domain, null, cb);
68
+    });
69
+  }
70
+};

+ 43
- 0
node_modules/cordova-plugin-advanced-http/www/dependency-validator.js Visa fil

@@ -0,0 +1,43 @@
1
+module.exports = function init(global, console, messages) {
2
+  var interface = {
3
+    checkBlobApi: checkBlobApi,
4
+    checkFileReaderApi: checkFileReaderApi,
5
+    checkFormDataInstance: checkFormDataInstance,
6
+    checkTextEncoderApi: checkTextEncoderApi,
7
+    logWarnings: logWarnings,
8
+  };
9
+
10
+  return interface;
11
+
12
+  function logWarnings() {
13
+    if (!global.FormData) {
14
+      console.warn(messages.MISSING_FORMDATA_API);
15
+    } else if (!global.FormData.prototype || !global.FormData.prototype.entries) {
16
+      console.warn(messages.MISSING_FORMDATA_ENTRIES_API);
17
+    }
18
+  }
19
+
20
+  function checkBlobApi() {
21
+    if (!global.Blob || !global.Blob.prototype) {
22
+      throw new Error(messages.MISSING_BLOB_API);
23
+    }
24
+  }
25
+
26
+  function checkFileReaderApi() {
27
+    if (!global.FileReader || !global.FileReader.prototype) {
28
+      throw new Error(messages.MISSING_FILE_READER_API);
29
+    }
30
+  }
31
+
32
+  function checkFormDataInstance(instance) {
33
+    if (!instance || !instance.entries) {
34
+      throw new Error(messages.MISSING_FORMDATA_ENTRIES_API);
35
+    }
36
+  }
37
+
38
+  function checkTextEncoderApi() {
39
+    if (!global.TextEncoder || !global.TextEncoder.prototype) {
40
+      throw new Error(messages.MISSING_TEXT_ENCODER_API);
41
+    }
42
+  }
43
+};

+ 9
- 0
node_modules/cordova-plugin-advanced-http/www/error-codes.js Visa fil

@@ -0,0 +1,9 @@
1
+module.exports = {
2
+  GENERIC: -1,
3
+  SSL_EXCEPTION: -2,
4
+  SERVER_NOT_FOUND: -3,
5
+  TIMEOUT: -4,
6
+  UNSUPPORTED_URL: -5,
7
+  NOT_CONNECTED: -6,
8
+  POST_PROCESSING_FAILED: -7,
9
+};

+ 8
- 0
node_modules/cordova-plugin-advanced-http/www/global-configs.js Visa fil

@@ -0,0 +1,8 @@
1
+var globalConfigs = {
2
+  headers: {},
3
+  serializer: 'urlencoded',
4
+  followRedirect: true,
5
+  timeout: 60.0,
6
+};
7
+
8
+module.exports = globalConfigs;

+ 503
- 0
node_modules/cordova-plugin-advanced-http/www/helpers.js Visa fil

@@ -0,0 +1,503 @@
1
+module.exports = function init(global, jsUtil, cookieHandler, messages, base64, errorCodes, dependencyValidator, ponyfills) {
2
+  var validSerializers = ['urlencoded', 'json', 'utf8', 'raw', 'multipart'];
3
+  var validCertModes = ['default', 'nocheck', 'pinned', 'legacy'];
4
+  var validClientAuthModes = ['none', 'systemstore', 'buffer'];
5
+  var validHttpMethods = ['get', 'put', 'post', 'patch', 'head', 'delete', 'options', 'upload', 'download'];
6
+  var validResponseTypes = ['text', 'json', 'arraybuffer', 'blob'];
7
+
8
+  var interface = {
9
+    b64EncodeUnicode: b64EncodeUnicode,
10
+    checkClientAuthMode: checkClientAuthMode,
11
+    checkClientAuthOptions: checkClientAuthOptions,
12
+    checkDownloadFilePath: checkDownloadFilePath,
13
+    checkFollowRedirectValue: checkFollowRedirectValue,
14
+    checkForBlacklistedHeaderKey: checkForBlacklistedHeaderKey,
15
+    checkForInvalidHeaderValue: checkForInvalidHeaderValue,
16
+    checkSerializer: checkSerializer,
17
+    checkSSLCertMode: checkSSLCertMode,
18
+    checkTimeoutValue: checkTimeoutValue,
19
+    checkUploadFileOptions: checkUploadFileOptions,
20
+    getMergedHeaders: getMergedHeaders,
21
+    processData: processData,
22
+    handleMissingCallbacks: handleMissingCallbacks,
23
+    handleMissingOptions: handleMissingOptions,
24
+    injectCookieHandler: injectCookieHandler,
25
+    injectFileEntryHandler: injectFileEntryHandler,
26
+    injectRawResponseHandler: injectRawResponseHandler,
27
+  };
28
+
29
+  // expose all functions for testing purposes
30
+  if (init.debug) {
31
+    interface.mergeHeaders = mergeHeaders;
32
+    interface.checkForValidStringValue = checkForValidStringValue;
33
+    interface.checkKeyValuePairObject = checkKeyValuePairObject;
34
+    interface.checkHttpMethod = checkHttpMethod;
35
+    interface.checkResponseType = checkResponseType;
36
+    interface.checkHeadersObject = checkHeadersObject;
37
+    interface.checkParamsObject = checkParamsObject;
38
+    interface.resolveCookieString = resolveCookieString;
39
+    interface.createFileEntry = createFileEntry;
40
+    interface.getCookieHeader = getCookieHeader;
41
+    interface.getMatchingHostHeaders = getMatchingHostHeaders;
42
+    interface.getAllowedDataTypes = getAllowedDataTypes;
43
+  }
44
+
45
+  return interface;
46
+
47
+  // Thanks Mozilla: https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#The_.22Unicode_Problem.22
48
+  function b64EncodeUnicode(str) {
49
+    return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function (match, p1) {
50
+      return String.fromCharCode('0x' + p1);
51
+    }));
52
+  }
53
+
54
+  function mergeHeaders(globalHeaders, localHeaders) {
55
+    var globalKeys = Object.keys(globalHeaders);
56
+    var key;
57
+
58
+    for (var i = 0; i < globalKeys.length; i++) {
59
+      key = globalKeys[i];
60
+
61
+      if (!localHeaders.hasOwnProperty(key)) {
62
+        localHeaders[key] = globalHeaders[key];
63
+      }
64
+    }
65
+
66
+    return localHeaders;
67
+  }
68
+
69
+  function checkForValidStringValue(list, value, onInvalidValueMessage) {
70
+    if (jsUtil.getTypeOf(value) !== 'String') {
71
+      throw new Error(onInvalidValueMessage + ' ' + list.join(', '));
72
+    }
73
+
74
+    value = value.trim().toLowerCase();
75
+
76
+    if (list.indexOf(value) === -1) {
77
+      throw new Error(onInvalidValueMessage + ' ' + list.join(', '));
78
+    }
79
+
80
+    return value;
81
+  }
82
+
83
+  function checkKeyValuePairObject(obj, allowedChildren, onInvalidValueMessage) {
84
+    if (jsUtil.getTypeOf(obj) !== 'Object') {
85
+      throw new Error(onInvalidValueMessage);
86
+    }
87
+
88
+    var keys = Object.keys(obj);
89
+
90
+    for (var i = 0; i < keys.length; i++) {
91
+      if (allowedChildren.indexOf(jsUtil.getTypeOf(obj[keys[i]])) === -1) {
92
+        throw new Error(onInvalidValueMessage);
93
+      }
94
+    }
95
+
96
+    return obj;
97
+  }
98
+
99
+  function checkArray(array, allowedDataTypes, onInvalidValueMessage) {
100
+    if (jsUtil.getTypeOf(array) !== 'Array') {
101
+      throw new Error(onInvalidValueMessage);
102
+    }
103
+
104
+    for (var i = 0; i < array.length; ++i) {
105
+      if (allowedDataTypes.indexOf(jsUtil.getTypeOf(array[i])) === -1) {
106
+        throw new Error(onInvalidValueMessage);
107
+      }
108
+    }
109
+
110
+    return array;
111
+  }
112
+
113
+  function checkHttpMethod(method) {
114
+    return checkForValidStringValue(validHttpMethods, method, messages.INVALID_HTTP_METHOD);
115
+  }
116
+
117
+  function checkResponseType(type) {
118
+    return checkForValidStringValue(validResponseTypes, type, messages.INVALID_RESPONSE_TYPE);
119
+  }
120
+
121
+  function checkSerializer(serializer) {
122
+    return checkForValidStringValue(validSerializers, serializer, messages.INVALID_DATA_SERIALIZER);
123
+  }
124
+
125
+  function checkSSLCertMode(mode) {
126
+    return checkForValidStringValue(validCertModes, mode, messages.INVALID_SSL_CERT_MODE);
127
+  }
128
+
129
+  function checkClientAuthMode(mode) {
130
+    return checkForValidStringValue(validClientAuthModes, mode, messages.INVALID_CLIENT_AUTH_MODE);
131
+  }
132
+
133
+  function checkClientAuthOptions(mode, options) {
134
+    options = options || {};
135
+
136
+    // none
137
+    if (mode === validClientAuthModes[0]) {
138
+      return {
139
+        alias: null,
140
+        rawPkcs: null,
141
+        pkcsPassword: ''
142
+      };
143
+    }
144
+
145
+    if (jsUtil.getTypeOf(options) !== 'Object') {
146
+      throw new Error(messages.INVALID_CLIENT_AUTH_OPTIONS);
147
+    }
148
+
149
+    // systemstore
150
+    if (mode === validClientAuthModes[1]) {
151
+      if (jsUtil.getTypeOf(options.alias) !== 'String'
152
+        && jsUtil.getTypeOf(options.alias) !== 'Undefined') {
153
+        throw new Error(messages.INVALID_CLIENT_AUTH_ALIAS);
154
+      }
155
+
156
+      return {
157
+        alias: jsUtil.getTypeOf(options.alias) === 'Undefined' ? null : options.alias,
158
+        rawPkcs: null,
159
+        pkcsPassword: ''
160
+      };
161
+    }
162
+
163
+    // buffer
164
+    if (mode === validClientAuthModes[2]) {
165
+      if (jsUtil.getTypeOf(options.rawPkcs) !== 'ArrayBuffer') {
166
+        throw new Error(messages.INVALID_CLIENT_AUTH_RAW_PKCS);
167
+      }
168
+
169
+      if (jsUtil.getTypeOf(options.pkcsPassword) !== 'String') {
170
+        throw new Error(messages.INVALID_CLIENT_AUTH_PKCS_PASSWORD);
171
+      }
172
+
173
+      return {
174
+        alias: null,
175
+        rawPkcs: options.rawPkcs,
176
+        pkcsPassword: options.pkcsPassword
177
+      }
178
+    }
179
+  }
180
+
181
+  function checkForBlacklistedHeaderKey(key) {
182
+    if (key.toLowerCase() === 'cookie') {
183
+      throw new Error(messages.ADDING_COOKIES_NOT_SUPPORTED);
184
+    }
185
+
186
+    return key;
187
+  }
188
+
189
+  function checkForInvalidHeaderValue(value) {
190
+    var type = jsUtil.getTypeOf(value);
191
+
192
+    if (type !== 'String' && type !== 'Null') {
193
+      throw new Error(messages.INVALID_HEADER_VALUE);
194
+    }
195
+
196
+    return value;
197
+  }
198
+
199
+  function checkTimeoutValue(timeout) {
200
+    if (jsUtil.getTypeOf(timeout) !== 'Number' || timeout < 0) {
201
+      throw new Error(messages.INVALID_TIMEOUT_VALUE);
202
+    }
203
+
204
+    return timeout;
205
+  }
206
+
207
+  function checkFollowRedirectValue(follow) {
208
+    if (jsUtil.getTypeOf(follow) !== 'Boolean') {
209
+      throw new Error(messages.INVALID_FOLLOW_REDIRECT_VALUE);
210
+    }
211
+
212
+    return follow;
213
+  }
214
+
215
+  function checkHeadersObject(headers) {
216
+    return checkKeyValuePairObject(headers, ['String'], messages.TYPE_MISMATCH_HEADERS);
217
+  }
218
+
219
+  function checkParamsObject(params) {
220
+    return checkKeyValuePairObject(params, ['String', 'Array'], messages.TYPE_MISMATCH_PARAMS);
221
+  }
222
+
223
+  function checkDownloadFilePath(filePath) {
224
+    if (!filePath || jsUtil.getTypeOf(filePath) !== 'String') {
225
+      throw new Error(messages.INVALID_DOWNLOAD_FILE_PATH);
226
+    }
227
+
228
+    return filePath;
229
+  }
230
+
231
+  function checkUploadFileOptions(filePaths, names) {
232
+    if (jsUtil.getTypeOf(filePaths) === 'String') {
233
+      filePaths = [filePaths];
234
+    }
235
+
236
+    if (jsUtil.getTypeOf(names) === 'String') {
237
+      names = [names];
238
+    }
239
+
240
+    var opts = {
241
+      filePaths: checkArray(filePaths, ['String'], messages.TYPE_MISMATCH_FILE_PATHS),
242
+      names: checkArray(names, ['String'], messages.TYPE_MISMATCH_NAMES)
243
+    };
244
+
245
+    if (!opts.filePaths.length) {
246
+      throw new Error(messages.EMPTY_FILE_PATHS);
247
+    }
248
+
249
+    if (!opts.names.length) {
250
+      throw new Error(messages.EMPTY_NAMES);
251
+    }
252
+
253
+    return opts;
254
+  }
255
+
256
+  function resolveCookieString(headers) {
257
+    var keys = Object.keys(headers || {});
258
+
259
+    for (var i = 0; i < keys.length; ++i) {
260
+      if (keys[i].match(/^set-cookie$/i)) {
261
+        return headers[keys[i]];
262
+      }
263
+    }
264
+
265
+    return null;
266
+  }
267
+
268
+  function createFileEntry(rawEntry) {
269
+    var entry = new (require('cordova-plugin-file.FileEntry'))();
270
+
271
+    entry.isDirectory = rawEntry.isDirectory;
272
+    entry.isFile = rawEntry.isFile;
273
+    entry.name = rawEntry.name;
274
+    entry.fullPath = rawEntry.fullPath;
275
+    entry.filesystem = new FileSystem(rawEntry.filesystemName || (rawEntry.filesystem == global.PERSISTENT ? 'persistent' : 'temporary'));
276
+    entry.nativeURL = rawEntry.nativeURL;
277
+
278
+    return entry;
279
+  }
280
+
281
+  function injectCookieHandler(url, cb) {
282
+    return function (response) {
283
+      cookieHandler.setCookieFromString(url, resolveCookieString(response.headers));
284
+      cb(response);
285
+    }
286
+  }
287
+
288
+  function injectRawResponseHandler(responseType, success, failure) {
289
+    return function (response) {
290
+      var dataType = jsUtil.getTypeOf(response.data);
291
+
292
+      // don't need post-processing if it's already binary type (on browser platform)
293
+      if (dataType === 'ArrayBuffer' || dataType === 'Blob') {
294
+        return success(response);
295
+      }
296
+
297
+      try {
298
+        // json
299
+        if (responseType === validResponseTypes[1]) {
300
+          response.data = response.data === ''
301
+            ? undefined
302
+            : JSON.parse(response.data);
303
+        }
304
+
305
+        // arraybuffer
306
+        else if (responseType === validResponseTypes[2]) {
307
+          response.data = response.data === ''
308
+            ? null
309
+            : base64.toArrayBuffer(response.data);
310
+        }
311
+
312
+        // blob
313
+        else if (responseType === validResponseTypes[3]) {
314
+          if (response.data === '') {
315
+            response.data = null;
316
+          } else {
317
+            var buffer = base64.toArrayBuffer(response.data);
318
+            var type = response.headers['content-type'] || '';
319
+            var blob = new Blob([buffer], { type: type });
320
+            response.data = blob;
321
+          }
322
+        }
323
+
324
+        success(response);
325
+      } catch (error) {
326
+        failure({
327
+          status: errorCodes.POST_PROCESSING_FAILED,
328
+          error: messages.POST_PROCESSING_FAILED + ' ' + error.message,
329
+          url: response.url,
330
+          headers: response.headers
331
+        });
332
+      }
333
+    }
334
+  }
335
+
336
+  function injectFileEntryHandler(cb) {
337
+    return function (response) {
338
+      cb(createFileEntry(response.file));
339
+    }
340
+  }
341
+
342
+  function getCookieHeader(url) {
343
+    var cookieString = cookieHandler.getCookieString(url);
344
+
345
+    if (cookieString.length) {
346
+      return { Cookie: cookieHandler.getCookieString(url) };
347
+    }
348
+
349
+    return {};
350
+  }
351
+
352
+  function getMatchingHostHeaders(url, headersList) {
353
+    var matches = url.match(/^https?\:\/\/([^\/?#]+)(?:[\/?#]|$)/i);
354
+    var domain = matches && matches[1];
355
+
356
+    return headersList[domain] || null;
357
+  }
358
+
359
+  function getMergedHeaders(url, requestHeaders, predefinedHeaders) {
360
+    var globalHeaders = predefinedHeaders['*'] || {};
361
+    var hostHeaders = getMatchingHostHeaders(url, predefinedHeaders) || {};
362
+    var mergedHeaders = mergeHeaders(globalHeaders, hostHeaders);
363
+
364
+    mergedHeaders = mergeHeaders(mergedHeaders, requestHeaders);
365
+    mergedHeaders = mergeHeaders(mergedHeaders, getCookieHeader(url));
366
+
367
+    return mergedHeaders;
368
+  }
369
+
370
+  function getAllowedDataTypes(dataSerializer) {
371
+    switch (dataSerializer) {
372
+      case 'utf8':
373
+        return ['String'];
374
+      case 'urlencoded':
375
+        return ['Object'];
376
+      case 'json':
377
+        return ['Array', 'Object'];
378
+      case 'raw':
379
+        return ['Uint8Array', 'ArrayBuffer'];
380
+      default:
381
+        return [];
382
+    }
383
+  }
384
+
385
+  function getAllowedInstanceTypes(dataSerializer) {
386
+    return dataSerializer === 'multipart' ? ['FormData'] : null;
387
+  }
388
+
389
+  function processData(data, dataSerializer, cb) {
390
+    var currentDataType = jsUtil.getTypeOf(data);
391
+    var allowedDataTypes = getAllowedDataTypes(dataSerializer);
392
+    var allowedInstanceTypes = getAllowedInstanceTypes(dataSerializer);
393
+
394
+    if (allowedInstanceTypes) {
395
+      var isCorrectInstanceType = false;
396
+
397
+      allowedInstanceTypes.forEach(function (type) {
398
+        if ((global[type] && data instanceof global[type]) || (ponyfills[type] && data instanceof ponyfills[type])) {
399
+          isCorrectInstanceType = true;
400
+        }
401
+      });
402
+
403
+      if (!isCorrectInstanceType) {
404
+        throw new Error(messages.INSTANCE_TYPE_MISMATCH_DATA + ' ' + allowedInstanceTypes.join(', '));
405
+      }
406
+    }
407
+
408
+    if (!allowedInstanceTypes && allowedDataTypes.indexOf(currentDataType) === -1) {
409
+      throw new Error(messages.TYPE_MISMATCH_DATA + ' ' + allowedDataTypes.join(', '));
410
+    }
411
+
412
+    switch (dataSerializer) {
413
+      case 'utf8':
414
+        return cb({ text: data });
415
+      case 'raw':
416
+        return cb(currentDataType === 'Uint8Array' ? data.buffer : data);
417
+      case 'multipart':
418
+        return processFormData(data, cb);
419
+      default:
420
+        return cb(data);
421
+    }
422
+  }
423
+
424
+  function processFormData(data, cb) {
425
+    dependencyValidator.checkBlobApi();
426
+    dependencyValidator.checkFileReaderApi();
427
+    dependencyValidator.checkTextEncoderApi();
428
+    dependencyValidator.checkFormDataInstance(data);
429
+
430
+    var textEncoder = new global.TextEncoder('utf8');
431
+    var iterator = data.entries();
432
+
433
+    var result = {
434
+      buffers: [],
435
+      names: [],
436
+      fileNames: [],
437
+      types: []
438
+    };
439
+
440
+    processFormDataIterator(iterator, textEncoder, result, cb);
441
+  }
442
+
443
+  function processFormDataIterator(iterator, textEncoder, result, onFinished) {
444
+    var entry = iterator.next();
445
+
446
+    if (entry.done) {
447
+      return onFinished(result);
448
+    }
449
+
450
+    if (entry.value[1] instanceof global.Blob || entry.value[1] instanceof global.File) {
451
+      var reader = new global.FileReader();
452
+
453
+      reader.onload = function () {
454
+        result.buffers.push(base64.fromArrayBuffer(reader.result));
455
+        result.names.push(entry.value[0]);
456
+        result.fileNames.push(entry.value[1].name !== undefined ? entry.value[1].name : 'blob');
457
+        result.types.push(entry.value[1].type || '');
458
+        processFormDataIterator(iterator, textEncoder, result, onFinished);
459
+      };
460
+
461
+      return reader.readAsArrayBuffer(entry.value[1]);
462
+    }
463
+
464
+    if (jsUtil.getTypeOf(entry.value[1]) === 'String') {
465
+      result.buffers.push(base64.fromArrayBuffer(textEncoder.encode(entry.value[1]).buffer));
466
+      result.names.push(entry.value[0]);
467
+      result.fileNames.push(null);
468
+      result.types.push('text/plain');
469
+
470
+      return processFormDataIterator(iterator, textEncoder, result, onFinished)
471
+    }
472
+
473
+    // skip items which are not supported
474
+    processFormDataIterator(iterator, textEncoder, result, onFinished);
475
+  }
476
+
477
+  function handleMissingCallbacks(successFn, failFn) {
478
+    if (jsUtil.getTypeOf(successFn) !== 'Function') {
479
+      throw new Error(messages.MANDATORY_SUCCESS);
480
+    }
481
+
482
+    if (jsUtil.getTypeOf(failFn) !== 'Function') {
483
+      throw new Error(messages.MANDATORY_FAIL);
484
+    }
485
+  }
486
+
487
+  function handleMissingOptions(options, globals) {
488
+    options = options || {};
489
+
490
+    return {
491
+      data: jsUtil.getTypeOf(options.data) === 'Undefined' ? null : options.data,
492
+      filePath: options.filePath,
493
+      followRedirect: checkFollowRedirectValue(options.followRedirect || globals.followRedirect),
494
+      headers: checkHeadersObject(options.headers || {}),
495
+      method: checkHttpMethod(options.method || validHttpMethods[0]),
496
+      name: options.name,
497
+      params: checkParamsObject(options.params || {}),
498
+      responseType: checkResponseType(options.responseType || validResponseTypes[0]),
499
+      serializer: checkSerializer(options.serializer || globals.serializer),
500
+      timeout: checkTimeoutValue(options.timeout || globals.timeout),
501
+    };
502
+  }
503
+};

+ 32
- 0
node_modules/cordova-plugin-advanced-http/www/js-util.js Visa fil

@@ -0,0 +1,32 @@
1
+module.exports = {
2
+  // typeof is not working reliably in JS
3
+  getTypeOf: function (object) {
4
+    switch (Object.prototype.toString.call(object)) {
5
+      case '[object Array]':
6
+        return 'Array';
7
+      case '[object Blob]':
8
+        return 'Blob';
9
+      case '[object Uint8Array]':
10
+        return 'Uint8Array';
11
+      case '[object ArrayBuffer]':
12
+        return 'ArrayBuffer';
13
+      case '[object Boolean]':
14
+        return 'Boolean';
15
+      case '[object Function]':
16
+        return 'Function';
17
+      case '[object Null]':
18
+        return 'Null';
19
+      case '[object Number]':
20
+        return 'Number';
21
+      case '[object Object]':
22
+        return 'Object';
23
+      case '[object String]':
24
+        return 'String';
25
+      case '[object Undefined]':
26
+        return 'Undefined';
27
+      default:
28
+        return 'Unknown';
29
+    }
30
+  }
31
+}
32
+

+ 181
- 0
node_modules/cordova-plugin-advanced-http/www/local-storage-store.js Visa fil

@@ -0,0 +1,181 @@
1
+/*
2
+ * The MIT License (MIT)
3
+ *
4
+ * Copyright (c) 2016 Exponent
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in all
14
+ * copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ * SOFTWARE.
23
+ *
24
+ * Based on "tough-cookie-web-storage-store" v1.0.0
25
+ * Thanks James Ide: https://github.com/exponentjs/tough-cookie-web-storage-store
26
+ *
27
+ * Modified by Sefa Ilkimen for cordova plugin integration
28
+ *
29
+ */
30
+
31
+'use strict';
32
+
33
+module.exports = function init(ToughCookie, _) {
34
+  function WebStorageCookieStore(storage, storeKey) {
35
+    ToughCookie.Store.call(this);
36
+    this._storage = storage;
37
+    this._storeKey = storeKey || '__cookieStore__';
38
+    this.synchronous = true;
39
+  }
40
+
41
+  WebStorageCookieStore.prototype = Object.create(ToughCookie.Store);
42
+
43
+  WebStorageCookieStore.prototype.findCookie = function (domain, path, key, callback) {
44
+    var store = this._readStore();
45
+    var cookie = _.get(store, [domain, path, key], null);
46
+
47
+    callback(null, ToughCookie.Cookie.fromJSON(cookie));
48
+  };
49
+
50
+  WebStorageCookieStore.prototype.findCookies = function (domain, path, callback) {
51
+    if (!domain) {
52
+      callback(null, []);
53
+      return;
54
+    }
55
+
56
+    var that = this;
57
+    var cookies = [];
58
+    var store = this._readStore();
59
+    var domains = ToughCookie.permuteDomain(domain) || [domain];
60
+
61
+    domains.forEach(function (domain) {
62
+      if (!store[domain]) {
63
+        return;
64
+      }
65
+
66
+      var matchingPaths = Object.keys(store[domain]);
67
+
68
+      if (path != null) {
69
+        matchingPaths = matchingPaths.filter(function (cookiePath) {
70
+          return that._isOnPath(cookiePath, path);
71
+        });
72
+      }
73
+
74
+      matchingPaths.forEach(function (path) {
75
+        Array.prototype.push.apply(cookies, _.values(store[domain][path]));
76
+      });
77
+    });
78
+
79
+    cookies = cookies.map(function (cookie) {
80
+      return ToughCookie.Cookie.fromJSON(cookie);
81
+    });
82
+
83
+    callback(null, cookies);
84
+  };
85
+
86
+  /**
87
+   * Returns whether `cookiePath` is on the given `urlPath`
88
+   */
89
+  WebStorageCookieStore.prototype._isOnPath = function (cookiePath, urlPath) {
90
+    if (!cookiePath) {
91
+      return false;
92
+    }
93
+
94
+    if (cookiePath === urlPath) {
95
+      return true;
96
+    }
97
+
98
+    if (urlPath.indexOf(cookiePath) !== 0) {
99
+      return false;
100
+    }
101
+
102
+    if (cookiePath[cookiePath.length - 1] !== '/' && urlPath[cookiePath.length] !== '/') {
103
+      return false;
104
+    }
105
+
106
+    return true;
107
+  };
108
+
109
+  WebStorageCookieStore.prototype.putCookie = function (cookie, callback) {
110
+    var store = this._readStore();
111
+
112
+    _.set(store, [cookie.domain, cookie.path, cookie.key], cookie);
113
+    this._writeStore(store);
114
+    callback(null);
115
+  };
116
+
117
+  WebStorageCookieStore.prototype.updateCookie = function (oldCookie, newCookie, callback) {
118
+    this.putCookie(newCookie, callback);
119
+  };
120
+
121
+
122
+  WebStorageCookieStore.prototype.removeCookie = function (domain, path, key, callback) {
123
+    var store = this._readStore();
124
+
125
+    _.unset(store, [domain, path, key]);
126
+    this._writeStore(store);
127
+    callback(null);
128
+  };
129
+
130
+  WebStorageCookieStore.prototype.removeCookies = function (domain, path, callback) {
131
+    var store = this._readStore();
132
+
133
+    if (path == null) {
134
+      _.unset(store, [domain]);
135
+    } else {
136
+      _.unset(store, [domain, path]);
137
+    }
138
+
139
+    this._writeStore(store);
140
+    callback(null);
141
+  };
142
+
143
+  WebStorageCookieStore.prototype.getAllCookies = function (callback) {
144
+    var cookies = [];
145
+    var store = this._readStore();
146
+
147
+    Object.keys(store).forEach(function (domain) {
148
+      Object.keys(store[domain]).forEach(function (path) {
149
+        Array.prototype.push.apply(cookies, _.values(store[domain][path]));
150
+      });
151
+    });
152
+
153
+    cookies = cookies.map(function (cookie) {
154
+      return ToughCookie.Cookie.fromJSON(cookie);
155
+    });
156
+
157
+    cookies.sort(function (c1, c2) {
158
+      return (c1.creationIndex || 0) - (c2.creationIndex || 0);
159
+    });
160
+
161
+    callback(null, cookies);
162
+  };
163
+
164
+  WebStorageCookieStore.prototype._readStore = function () {
165
+    var json = this._storage.getItem(this._storeKey);
166
+
167
+    if (json !== null) {
168
+      try {
169
+        return JSON.parse(json);
170
+      } catch (e) { }
171
+    }
172
+
173
+    return {};
174
+  };
175
+
176
+  WebStorageCookieStore.prototype._writeStore = function (store) {
177
+    this._storage.setItem(this._storeKey, JSON.stringify(store));
178
+  };
179
+
180
+  return WebStorageCookieStore;
181
+};

+ 20
- 0
node_modules/cordova-plugin-advanced-http/www/lodash.js Visa fil

@@ -0,0 +1,20 @@
1
+/**
2
+ * @license
3
+ * Lodash (Custom Build) lodash.com/license | Underscore.js 1.8.3 underscorejs.org/LICENSE
4
+ * Build: `lodash include="get,set,unset,values" exports="node"`
5
+ */
6
+;(function(){function t(t,e){for(var r=-1,n=null==t?0:t.length,o=Array(n);++r<n;)o[r]=e(t[r],r,t);return o}function e(t){return function(e){return t(e)}}function r(e,r){return t(r,function(t){return e[t]})}function n(){}function o(t){var e=-1,r=null==t?0:t.length;for(this.clear();++e<r;){var n=t[e];this.set(n[0],n[1])}}function u(t){var e=-1,r=null==t?0:t.length;for(this.clear();++e<r;){var n=t[e];this.set(n[0],n[1])}}function i(t){var e=-1,r=null==t?0:t.length;for(this.clear();++e<r;){var n=t[e];this.set(n[0],n[1]);
7
+}}function c(t,e){for(var r=t.length;r--;)if(m(t[r][0],e))return r;return-1}function a(t,e){e=h(e,t);for(var r=0,n=e.length;null!=t&&r<n;)t=t[j(e[r++])];return r&&r==n?t:E}function l(t){if(null==t)return t===E?"[object Undefined]":"[object Null]";t=Object(t);var e;if(nt&&nt in t){var r=Q.call(t,nt),n=t[nt];try{t[nt]=E,e=true}catch(t){}var o=Y.call(t);e&&(r?t[nt]=n:delete t[nt]),e=o}else e=Y.call(t);return e}function s(t){return w(t)&&"[object Arguments]"==l(t)}function f(t){return w(t)&&z(t.length)&&!!M[l(t)];
8
+}function p(e){if(typeof e=="string")return e;if(ft(e))return t(e,p)+"";if(x(e))return at?at.call(e):"";var r=e+"";return"0"==r&&1/e==-T?"-0":r}function h(t,e){var r;return ft(t)?r=t:(ft(t)?r=false:(r=typeof t,r=!("number"!=r&&"symbol"!=r&&"boolean"!=r&&null!=t&&!x(t))||(B.test(t)||!I.test(t)||null!=e&&t in Object(e))),r=r?[t]:lt(F(t))),r}function y(t,e){var r=t.__data__,n=typeof e;return("string"==n||"number"==n||"symbol"==n||"boolean"==n?"__proto__"!==e:null===e)?r[typeof e=="string"?"string":"hash"]:r.map;
9
+}function b(t,e){var r=null==t?E:t[e];return(!S(r)||X&&X in r?0:(O(r)?Z:L).test(g(r)))?r:E}function _(t,e){return e=null==e?9007199254740991:e,!!e&&(typeof t=="number"||R.test(t))&&-1<t&&0==t%1&&t<e}function j(t){if(typeof t=="string"||x(t))return t;var e=t+"";return"0"==e&&1/t==-T?"-0":e}function g(t){if(null!=t){try{return K.call(t)}catch(t){}return t+""}return""}function v(t){var e=null==t?0:t.length;return e?t[e-1]:E}function d(t,e){function r(){var n=arguments,o=e?e.apply(this,n):n[0],u=r.cache;
10
+return u.has(o)?u.get(o):(n=t.apply(this,n),r.cache=u.set(o,n)||u,n)}if(typeof t!="function"||null!=e&&typeof e!="function")throw new TypeError("Expected a function");return r.cache=new(d.Cache||i),r}function m(t,e){return t===e||t!==t&&e!==e}function A(t){return null!=t&&z(t.length)&&!O(t)}function O(t){return!!S(t)&&(t=l(t),"[object Function]"==t||"[object GeneratorFunction]"==t||"[object AsyncFunction]"==t||"[object Proxy]"==t)}function z(t){return typeof t=="number"&&-1<t&&0==t%1&&9007199254740991>=t;
11
+}function S(t){var e=typeof t;return null!=t&&("object"==e||"function"==e)}function w(t){return null!=t&&typeof t=="object"}function x(t){return typeof t=="symbol"||w(t)&&"[object Symbol]"==l(t)}function F(t){return null==t?"":p(t)}function $(t){if(A(t)){var e=ft(t),r=!e&&st(t),n=!e&&!r&&pt(t),o=!e&&!r&&!n&&ht(t);if(e=e||r||n||o){for(var r=t.length,u=String,i=-1,c=Array(r);++i<r;)c[i]=u(i);r=c}else r=[];var a,u=r.length;for(a in t)!Q.call(t,a)||e&&("length"==a||n&&("offset"==a||"parent"==a)||o&&("buffer"==a||"byteLength"==a||"byteOffset"==a)||_(a,u))||r.push(a);
12
+t=r}else if(a=t&&t.constructor,t===(typeof a=="function"&&a.prototype||H)){a=[];for(n in Object(t))Q.call(t,n)&&"constructor"!=n&&a.push(n);t=a}else t=ut(t);return t}function k(){return false}var E,T=1/0,I=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,B=/^\w*$/,P=/^\./,U=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,C=/\\(\\)?/g,L=/^\[object .+?Constructor\]$/,R=/^(?:0|[1-9]\d*)$/,M={};M["[object Float32Array]"]=M["[object Float64Array]"]=M["[object Int8Array]"]=M["[object Int16Array]"]=M["[object Int32Array]"]=M["[object Uint8Array]"]=M["[object Uint8ClampedArray]"]=M["[object Uint16Array]"]=M["[object Uint32Array]"]=true,
13
+M["[object Arguments]"]=M["[object Array]"]=M["[object ArrayBuffer]"]=M["[object Boolean]"]=M["[object DataView]"]=M["[object Date]"]=M["[object Error]"]=M["[object Function]"]=M["[object Map]"]=M["[object Number]"]=M["[object Object]"]=M["[object RegExp]"]=M["[object Set]"]=M["[object String]"]=M["[object WeakMap]"]=false;var N,D=typeof global=="object"&&global&&global.Object===Object&&global,V=typeof self=="object"&&self&&self.Object===Object&&self,q=D||V||Function("return this")(),G=(V=typeof exports=="object"&&exports&&!exports.nodeType&&exports)&&typeof module=="object"&&module&&!module.nodeType&&module,W=G&&G.exports===V,D=W&&D.process;
14
+t:{try{N=D&&D.binding&&D.binding("util");break t}catch(t){}N=void 0}N=N&&N.isTypedArray;var D=Array.prototype,H=Object.prototype,J=q["__core-js_shared__"],K=Function.prototype.toString,Q=H.hasOwnProperty,X=function(){var t=/[^.]+$/.exec(J&&J.keys&&J.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}(),Y=H.toString,Z=RegExp("^"+K.call(Q).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),tt=W?q.Buffer:E,W=q.Symbol,et=H.propertyIsEnumerable,rt=D.splice,nt=W?W.toStringTag:E,ot=function(){
15
+try{var t=b(Object,"defineProperty");return t({},"",{}),t}catch(t){}}(),D=tt?tt.isBuffer:E,ut=function(t,e){return function(r){return t(e(r))}}(Object.keys,Object),it=b(q,"Map"),ct=b(Object,"create"),at=(q=W?W.prototype:E)?q.toString:E;o.prototype.clear=function(){this.__data__=ct?ct(null):{},this.size=0},o.prototype.delete=function(t){return t=this.has(t)&&delete this.__data__[t],this.size-=t?1:0,t},o.prototype.get=function(t){var e=this.__data__;return ct?(t=e[t],"__lodash_hash_undefined__"===t?E:t):Q.call(e,t)?e[t]:E;
16
+},o.prototype.has=function(t){var e=this.__data__;return ct?e[t]!==E:Q.call(e,t)},o.prototype.set=function(t,e){var r=this.__data__;return this.size+=this.has(t)?0:1,r[t]=ct&&e===E?"__lodash_hash_undefined__":e,this},u.prototype.clear=function(){this.__data__=[],this.size=0},u.prototype.delete=function(t){var e=this.__data__;return t=c(e,t),!(0>t)&&(t==e.length-1?e.pop():rt.call(e,t,1),--this.size,true)},u.prototype.get=function(t){var e=this.__data__;return t=c(e,t),0>t?E:e[t][1]},u.prototype.has=function(t){
17
+return-1<c(this.__data__,t)},u.prototype.set=function(t,e){var r=this.__data__,n=c(r,t);return 0>n?(++this.size,r.push([t,e])):r[n][1]=e,this},i.prototype.clear=function(){this.size=0,this.__data__={hash:new o,map:new(it||u),string:new o}},i.prototype.delete=function(t){return t=y(this,t).delete(t),this.size-=t?1:0,t},i.prototype.get=function(t){return y(this,t).get(t)},i.prototype.has=function(t){return y(this,t).has(t)},i.prototype.set=function(t,e){var r=y(this,t),n=r.size;return r.set(t,e),this.size+=r.size==n?0:1,
18
+this};var lt=function(t){t=d(t,function(t){return 500===e.size&&e.clear(),t});var e=t.cache;return t}(function(t){var e=[];return P.test(t)&&e.push(""),t.replace(U,function(t,r,n,o){e.push(n?o.replace(C,"$1"):r||t)}),e});d.Cache=i;var st=s(function(){return arguments}())?s:function(t){return w(t)&&Q.call(t,"callee")&&!et.call(t,"callee")},ft=Array.isArray,pt=D||k,ht=N?e(N):f;n.keys=$,n.memoize=d,n.set=function(t,e,r){if(null!=t&&S(t)){e=h(e,t);for(var n=-1,o=e.length,u=o-1,i=t;null!=i&&++n<o;){var c=j(e[n]),a=r;
19
+if(n!=u){var l=i[c],a=E;a===E&&(a=S(l)?l:_(e[n+1])?[]:{})}var s=i,l=c,f=s[l];Q.call(s,l)&&m(f,a)&&(a!==E||l in s)||("__proto__"==l&&ot?ot(s,l,{configurable:true,enumerable:true,value:a,writable:true}):s[l]=a),i=i[c]}}return t},n.unset=function(t,e){var r;if(null==t)r=true;else{var n=t,o=r=h(e,n);if(!(2>o.length)){var u=0,i=-1,c=-1,l=o.length;for(0>u&&(u=-u>l?0:l+u),i=i>l?l:i,0>i&&(i+=l),l=u>i?0:i-u>>>0,u>>>=0,i=Array(l);++c<l;)i[c]=o[c+u];n=a(n,i)}r=j(v(r)),r=!(null!=n&&Q.call(n,r))||delete n[r]}return r;
20
+},n.values=function(t){return null==t?[]:r(t,$(t))},n.eq=m,n.get=function(t,e,r){return t=null==t?E:a(t,e),t===E?r:t},n.isArguments=st,n.isArray=ft,n.isArrayLike=A,n.isBuffer=pt,n.isFunction=O,n.isLength=z,n.isObject=S,n.isObjectLike=w,n.isSymbol=x,n.isTypedArray=ht,n.last=v,n.stubFalse=k,n.toString=F,n.VERSION="4.17.1",G&&((G.exports=n)._=n,V._=n)}).call(this);

+ 32
- 0
node_modules/cordova-plugin-advanced-http/www/messages.js Visa fil

@@ -0,0 +1,32 @@
1
+module.exports = {
2
+  ADDING_COOKIES_NOT_SUPPORTED: 'advanced-http: "setHeader" does not support adding cookies, please use "setCookie" function instead',
3
+  EMPTY_FILE_PATHS: 'advanced-http: "filePaths" option array must not be empty, <filePaths: string[]>',
4
+  EMPTY_NAMES: 'advanced-http: "names" option array must not be empty, <names: string[]>',
5
+  INSTANCE_TYPE_MISMATCH_DATA: 'advanced-http: "data" option is configured to support only following instance types:',
6
+  INVALID_CLIENT_AUTH_ALIAS: 'advanced-http: invalid client certificate alias, needs to be a string or undefined, <alias: string | undefined>',
7
+  INVALID_CLIENT_AUTH_MODE: 'advanced-http: invalid client certificate authentication mode, supported modes are:',
8
+  INVALID_CLIENT_AUTH_OPTIONS: 'advanced-http: invalid client certificate authentication options, needs to be an dictionary style object',
9
+  INVALID_CLIENT_AUTH_PKCS_PASSWORD: 'advanced-http: invalid PKCS12 container password, needs to be a string, <pkcsPassword: string>',
10
+  INVALID_CLIENT_AUTH_RAW_PKCS: 'advanced-http: invalid PKCS12 container, needs to be an array buffer, <rawPkcs: ArrayBuffer>',
11
+  INVALID_DATA_SERIALIZER: 'advanced-http: invalid serializer, supported serializers are:',
12
+  INVALID_DOWNLOAD_FILE_PATH: 'advanced-http: invalid "filePath" value, needs to be a string, <filePath: string>',
13
+  INVALID_FOLLOW_REDIRECT_VALUE: 'advanced-http: invalid follow redirect value, needs to be a boolean value, <followRedirect: boolean>',
14
+  INVALID_HEADER_VALUE: 'advanced-http: invalid header value, needs to be a string or null, <header: string | null>',
15
+  INVALID_HTTP_METHOD: 'advanced-http: invalid HTTP method, supported methods are:',
16
+  INVALID_RESPONSE_TYPE: 'advanced-http: invalid response type, supported types are:',
17
+  INVALID_SSL_CERT_MODE: 'advanced-http: invalid SSL cert mode, supported modes are:',
18
+  INVALID_TIMEOUT_VALUE: 'advanced-http: invalid timeout value, needs to be a positive numeric value, <timeout: number>',
19
+  MANDATORY_FAIL: 'advanced-http: missing mandatory "onFail" callback function',
20
+  MANDATORY_SUCCESS: 'advanced-http: missing mandatory "onSuccess" callback function',
21
+  MISSING_BLOB_API: 'advanced-http: Blob API is not supported in this webview. If you want to use "multipart/form-data" requests, you need to load a polyfill library before loading this plugin. Check out https://github.com/silkimen/cordova-plugin-advanced-http/wiki/Web-APIs-required-for-Multipart-requests for more info.',
22
+  MISSING_FILE_READER_API: 'advanced-http: FileReader API is not supported in this webview. If you want to use "multipart/form-data" requests, you need to load a polyfill library before loading this plugin. Check out https://github.com/silkimen/cordova-plugin-advanced-http/wiki/Web-APIs-required-for-Multipart-requests for more info.',
23
+  MISSING_FORMDATA_API: 'advanced-http: FormData API is not supported in this webview. If you want to use "multipart/form-data" requests, you need to load a polyfill library before loading this plugin. Check out https://github.com/silkimen/cordova-plugin-advanced-http/wiki/Web-APIs-required-for-Multipart-requests for more info.',
24
+  MISSING_FORMDATA_ENTRIES_API: 'advanced-http: Given instance of FormData does not implement FormData API specification correctly, FormData.entries() is missing. If you want to use "multipart/form-data" requests, you can use an included ponyfill. Check out https://github.com/silkimen/cordova-plugin-advanced-http/wiki/Web-APIs-required-for-Multipart-requests for more info.',
25
+  MISSING_TEXT_ENCODER_API: 'advanced-http: TextEncoder API is not supported in this webview. If you want to use "multipart/form-data" requests, you need to load a polyfill library before loading this plugin. Check out https://github.com/silkimen/cordova-plugin-advanced-http/wiki/Web-APIs-required-for-Multipart-requests for more info.',
26
+  POST_PROCESSING_FAILED: 'advanced-http: an error occured during post processing response:',
27
+  TYPE_MISMATCH_DATA: 'advanced-http: "data" option is configured to support only following data types:',
28
+  TYPE_MISMATCH_FILE_PATHS: 'advanced-http: "filePaths" option needs to be an string array, <filePaths: string[]>',
29
+  TYPE_MISMATCH_HEADERS: 'advanced-http: "headers" option needs to be an dictionary style object with string values, <headers: {[key: string]: string}>',
30
+  TYPE_MISMATCH_NAMES: 'advanced-http: "names" option needs to be an string array, <names: string[]>',
31
+  TYPE_MISMATCH_PARAMS: 'advanced-http: "params" option needs to be an dictionary style object, <params: {[key: string]: string | string[]}>',
32
+};

+ 47
- 0
node_modules/cordova-plugin-advanced-http/www/ponyfills.js Visa fil

@@ -0,0 +1,47 @@
1
+module.exports = function init(global) {
2
+  var interface = { FormData: FormData };
3
+
4
+  // expose all constructor functions for testing purposes
5
+  if (init.debug) {
6
+    interface.Iterator = Iterator;
7
+  }
8
+  
9
+  function FormData() {
10
+    this.__items = [];
11
+  }
12
+
13
+  FormData.prototype.append = function(name, value, filename) {
14
+    if (global.File && value instanceof global.File) {
15
+      // nothing to do
16
+    } else if (global.Blob && value instanceof global.Blob) {
17
+      // mimic File instance by adding missing properties
18
+      value.lastModifiedDate = new Date();
19
+      value.name = filename !== undefined ? filename : 'blob';
20
+    } else {
21
+      value = String(value);
22
+    }
23
+
24
+    this.__items.push([ name, value ]);
25
+  };
26
+
27
+  FormData.prototype.entries = function() {
28
+    return new Iterator(this.__items);
29
+  };
30
+
31
+  function Iterator(items) {
32
+    this.__items = items;
33
+    this.__position = -1;
34
+  }
35
+
36
+  Iterator.prototype.next = function() {
37
+    this.__position += 1;
38
+
39
+    if (this.__position < this.__items.length) {
40
+      return { done: false, value: this.__items[this.__position] };
41
+    }
42
+
43
+    return { done: true, value: undefined };
44
+  }
45
+
46
+  return interface;
47
+};

+ 202
- 0
node_modules/cordova-plugin-advanced-http/www/public-interface.js Visa fil

@@ -0,0 +1,202 @@
1
+module.exports = function init(exec, cookieHandler, urlUtil, helpers, globalConfigs, errorCodes, ponyfills) {
2
+  var publicInterface = {
3
+    getBasicAuthHeader: getBasicAuthHeader,
4
+    useBasicAuth: useBasicAuth,
5
+    getHeaders: getHeaders,
6
+    setHeader: setHeader,
7
+    getDataSerializer: getDataSerializer,
8
+    setDataSerializer: setDataSerializer,
9
+    setCookie: setCookie,
10
+    clearCookies: clearCookies,
11
+    removeCookies: removeCookies,
12
+    getCookieString: getCookieString,
13
+    getRequestTimeout: getRequestTimeout,
14
+    setRequestTimeout: setRequestTimeout,
15
+    getFollowRedirect: getFollowRedirect,
16
+    setFollowRedirect: setFollowRedirect,
17
+    setServerTrustMode: setServerTrustMode,
18
+    setClientAuthMode: setClientAuthMode,
19
+    sendRequest: sendRequest,
20
+    post: post,
21
+    put: put,
22
+    patch: patch,
23
+    get: get,
24
+    delete: del,
25
+    head: head,
26
+    options: options,
27
+    uploadFile: uploadFile,
28
+    downloadFile: downloadFile,
29
+    ErrorCode: errorCodes,
30
+    ponyfills: ponyfills
31
+  };
32
+
33
+  function getBasicAuthHeader(username, password) {
34
+    return { 'Authorization': 'Basic ' + helpers.b64EncodeUnicode(username + ':' + password) };
35
+  }
36
+
37
+  function useBasicAuth(username, password) {
38
+    this.setHeader('*', 'Authorization', 'Basic ' + helpers.b64EncodeUnicode(username + ':' + password));
39
+  }
40
+
41
+  function getHeaders(host) {
42
+    return globalConfigs.headers[host || '*'] || null;
43
+  }
44
+
45
+  function setHeader() {
46
+    // this one is for being backward compatible
47
+    var host = '*';
48
+    var header = arguments[0];
49
+    var value = arguments[1];
50
+
51
+    if (arguments.length === 3) {
52
+      host = arguments[0];
53
+      header = arguments[1];
54
+      value = arguments[2];
55
+    }
56
+
57
+    helpers.checkForBlacklistedHeaderKey(header);
58
+    helpers.checkForInvalidHeaderValue(value);
59
+
60
+    globalConfigs.headers[host] = globalConfigs.headers[host] || {};
61
+
62
+    if (value === null) {
63
+      delete globalConfigs.headers[host][header];
64
+    } else {
65
+      globalConfigs.headers[host][header] = value;
66
+    }
67
+  }
68
+
69
+  function getDataSerializer() {
70
+    return globalConfigs.serializer;
71
+  }
72
+
73
+  function setDataSerializer(serializer) {
74
+    globalConfigs.serializer = helpers.checkSerializer(serializer);
75
+  }
76
+
77
+  function setCookie(url, cookie, options) {
78
+    cookieHandler.setCookie(url, cookie, options);
79
+  }
80
+
81
+  function clearCookies() {
82
+    cookieHandler.clearCookies();
83
+  }
84
+
85
+  function removeCookies(url, callback) {
86
+    cookieHandler.removeCookies(url, callback);
87
+  }
88
+
89
+  function getCookieString(url) {
90
+    return cookieHandler.getCookieString(url);
91
+  }
92
+
93
+  function getRequestTimeout() {
94
+    return globalConfigs.timeout;
95
+  }
96
+
97
+  function setRequestTimeout(timeout) {
98
+    globalConfigs.timeout = helpers.checkTimeoutValue(timeout);
99
+  }
100
+
101
+  function getFollowRedirect() {
102
+    return globalConfigs.followRedirect;
103
+  }
104
+
105
+  function setFollowRedirect(follow) {
106
+    globalConfigs.followRedirect = helpers.checkFollowRedirectValue(follow);
107
+  }
108
+
109
+  function setServerTrustMode(mode, success, failure) {
110
+    helpers.handleMissingCallbacks(success, failure);
111
+
112
+    return exec(success, failure, 'CordovaHttpPlugin', 'setServerTrustMode', [helpers.checkSSLCertMode(mode)]);
113
+  }
114
+
115
+  function setClientAuthMode() {
116
+    var mode = arguments[0];
117
+    var options = null;
118
+    var success = arguments[1];
119
+    var failure = arguments[2];
120
+
121
+    if (arguments.length === 4) {
122
+      options = arguments[1];
123
+      success = arguments[2];
124
+      failure = arguments[3];
125
+    }
126
+
127
+    mode = helpers.checkClientAuthMode(mode);
128
+    options = helpers.checkClientAuthOptions(mode, options);
129
+
130
+    helpers.handleMissingCallbacks(success, failure);
131
+
132
+    return exec(success, failure, 'CordovaHttpPlugin', 'setClientAuthMode', [mode, options.alias, options.rawPkcs, options.pkcsPassword]);
133
+  }
134
+
135
+  function sendRequest(url, options, success, failure) {
136
+    helpers.handleMissingCallbacks(success, failure);
137
+
138
+    options = helpers.handleMissingOptions(options, globalConfigs);
139
+    url = urlUtil.appendQueryParamsString(url, urlUtil.serializeQueryParams(options.params, true));
140
+
141
+    var headers = helpers.getMergedHeaders(url, options.headers, globalConfigs.headers);
142
+
143
+    var onFail = helpers.injectCookieHandler(url, failure);
144
+    var onSuccess = helpers.injectCookieHandler(url, helpers.injectRawResponseHandler(options.responseType, success, failure));
145
+
146
+    switch (options.method) {
147
+      case 'post':
148
+      case 'put':
149
+      case 'patch':
150
+        return helpers.processData(options.data, options.serializer, function (data) {
151
+          exec(onSuccess, onFail, 'CordovaHttpPlugin', options.method, [url, data, options.serializer, headers, options.timeout, options.followRedirect, options.responseType]);
152
+        });
153
+      case 'upload':
154
+        var fileOptions = helpers.checkUploadFileOptions(options.filePath, options.name);
155
+        return exec(onSuccess, onFail, 'CordovaHttpPlugin', 'uploadFiles', [url, headers, fileOptions.filePaths, fileOptions.names, options.timeout, options.followRedirect, options.responseType]);
156
+      case 'download':
157
+        var filePath = helpers.checkDownloadFilePath(options.filePath);
158
+        var onDownloadSuccess = helpers.injectCookieHandler(url, helpers.injectFileEntryHandler(success));
159
+        return exec(onDownloadSuccess, onFail, 'CordovaHttpPlugin', 'downloadFile', [url, headers, filePath, options.timeout, options.followRedirect]);
160
+      default:
161
+        return exec(onSuccess, onFail, 'CordovaHttpPlugin', options.method, [url, headers, options.timeout, options.followRedirect, options.responseType]);
162
+    }
163
+  }
164
+
165
+  function post(url, data, headers, success, failure) {
166
+    return publicInterface.sendRequest(url, { method: 'post', data: data, headers: headers }, success, failure);
167
+  };
168
+
169
+  function put(url, data, headers, success, failure) {
170
+    return publicInterface.sendRequest(url, { method: 'put', data: data, headers: headers }, success, failure);
171
+  }
172
+
173
+  function patch(url, data, headers, success, failure) {
174
+    return publicInterface.sendRequest(url, { method: 'patch', data: data, headers: headers }, success, failure);
175
+  }
176
+
177
+  function get(url, params, headers, success, failure) {
178
+    return publicInterface.sendRequest(url, { method: 'get', params: params, headers: headers }, success, failure);
179
+  };
180
+
181
+  function del(url, params, headers, success, failure) {
182
+    return publicInterface.sendRequest(url, { method: 'delete', params: params, headers: headers }, success, failure);
183
+  }
184
+
185
+  function head(url, params, headers, success, failure) {
186
+    return publicInterface.sendRequest(url, { method: 'head', params: params, headers: headers }, success, failure);
187
+  }
188
+
189
+  function options(url, params, headers, success, failure) {
190
+    return publicInterface.sendRequest(url, { method: 'options', params: params, headers: headers }, success, failure);
191
+  };
192
+
193
+  function uploadFile(url, params, headers, filePath, name, success, failure) {
194
+    return publicInterface.sendRequest(url, { method: 'upload', params: params, headers: headers, filePath: filePath, name: name }, success, failure);
195
+  }
196
+
197
+  function downloadFile(url, params, headers, filePath, success, failure) {
198
+    return publicInterface.sendRequest(url, { method: 'download', params: params, headers: headers, filePath: filePath }, success, failure);
199
+  }
200
+
201
+  return publicInterface;
202
+}

+ 5089
- 0
node_modules/cordova-plugin-advanced-http/www/umd-tough-cookie.js
Filskillnaden har hållits tillbaka eftersom den är för stor
Visa fil


+ 103
- 0
node_modules/cordova-plugin-advanced-http/www/url-util.js Visa fil

@@ -0,0 +1,103 @@
1
+module.exports = function init(jsUtil) {
2
+  return {
3
+    parseUrl: parseUrl,
4
+    appendQueryParamsString: appendQueryParamsString,
5
+    serializeQueryParams: serializeQueryParams
6
+  }
7
+
8
+  function parseUrl(url) {
9
+    var match = url.match(/^(https?\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)([\/]{0,1}[^?#]*)(\?[^#]*|)(#.*|)$/);
10
+
11
+    return match && {
12
+        protocol: match[1],
13
+        host: match[2],
14
+        hostname: match[3],
15
+        port: match[4] || '',
16
+        pathname: match[5],
17
+        search: match[6],
18
+        hash: match[7]
19
+    }
20
+  }
21
+
22
+  function appendQueryParamsString(url, params) {
23
+    if (!url.length || !params.length) {
24
+      return url;
25
+    }
26
+
27
+    var parsed = parseUrl(url);
28
+
29
+    return parsed.protocol
30
+      + '//'
31
+      + parsed.host
32
+      + parsed.pathname
33
+      + (parsed.search.length ? parsed.search + '&' + params : '?' + params)
34
+      + parsed.hash;
35
+  }
36
+
37
+  function serializeQueryParams(params, encode) {
38
+    return serializeObject('', params, encode);
39
+  }
40
+
41
+  function serializeObject(parentKey, object, encode) {
42
+    var parts = [];
43
+
44
+    for (var key in object) {
45
+      if (!object.hasOwnProperty(key)) {
46
+        continue;
47
+      }
48
+
49
+      var identifier = parentKey.length ? parentKey + '[' + key + ']' : key;
50
+
51
+      if (jsUtil.getTypeOf(object[key]) === 'Array') {
52
+        parts.push(serializeArray(identifier, object[key], encode));
53
+        continue;
54
+      } else if (jsUtil.getTypeOf(object[key]) === 'Object') {
55
+        parts.push(serializeObject(identifier, object[key], encode));
56
+        continue;
57
+      }
58
+
59
+      parts.push(serializeIdentifier(parentKey, key, encode) + '=' + serializeValue(object[key], encode));
60
+    }
61
+
62
+    return parts.join('&');
63
+  }
64
+
65
+  function serializeArray(parentKey, array, encode) {
66
+    var parts = [];
67
+
68
+    for (var i = 0; i < array.length; ++i) {
69
+      if (jsUtil.getTypeOf(array[i]) === 'Array') {
70
+        parts.push(serializeArray(parentKey + '[]', array[i], encode));
71
+        continue;
72
+      } else if (jsUtil.getTypeOf(array[i]) === 'Object') {
73
+        parts.push(serializeObject(parentKey + '[]' + array[i], encode));
74
+        continue;
75
+      }
76
+
77
+      parts.push(serializeIdentifier(parentKey, '', encode) + '=' + serializeValue(array[i], encode));
78
+    }
79
+
80
+    return parts.join('&');
81
+  }
82
+
83
+  function serializeIdentifier(parentKey, key, encode) {
84
+    if (!parentKey.length) {
85
+      return encode ? encodeURIComponent(key) : key;
86
+    }
87
+
88
+    if (encode) {
89
+      return encodeURIComponent(parentKey) + '[' + encodeURIComponent(key) + ']';
90
+    } else {
91
+      return parentKey + '[' + key + ']';
92
+    }
93
+  }
94
+
95
+  function serializeValue(value, encode) {
96
+    if (encode) {
97
+      return encodeURIComponent(value);
98
+    } else {
99
+      return value;
100
+    }
101
+  }
102
+};
103
+

+ 30
- 0
node_modules/cordova-plugin-file/.jshintrc Visa fil

@@ -0,0 +1,30 @@
1
+{
2
+    "browser": true
3
+  , "devel": true
4
+  , "bitwise": true
5
+  , "undef": true
6
+  , "trailing": true
7
+  , "quotmark": false
8
+  , "indent": 4
9
+  , "unused": "vars"
10
+  , "latedef": "nofunc"
11
+  , "globals": {
12
+        "module": false,
13
+        "exports": false,
14
+        "require": false,
15
+        "cordova": false,
16
+        "File": true,
17
+        "FileSystem": true,
18
+        "FileReader": true,
19
+        "FileWriter": true,
20
+        "FileError": true,
21
+        "LocalFileSystem": true,
22
+        "Metadata": true,
23
+        "Flags": true,
24
+        "DirectoryEntry": true,
25
+        "resolveLocalFileSystemURL": false,
26
+        "requestFileSystem": true,
27
+        "FILESYSTEM_PREFIX": true,
28
+        "FILESYSTEM_PROTOCOL": true
29
+    }
30
+}

+ 1
- 0
node_modules/cordova-plugin-file/.ratignore Visa fil

@@ -0,0 +1 @@
1
+asset-test.txt

+ 37
- 0
node_modules/cordova-plugin-file/CONTRIBUTING.md Visa fil

@@ -0,0 +1,37 @@
1
+<!--
2
+#
3
+# Licensed to the Apache Software Foundation (ASF) under one
4
+# or more contributor license agreements.  See the NOTICE file
5
+# distributed with this work for additional information
6
+# regarding copyright ownership.  The ASF licenses this file
7
+# to you under the Apache License, Version 2.0 (the
8
+# "License"); you may not use this file except in compliance
9
+# with the License.  You may obtain a copy of the License at
10
+#
11
+# http://www.apache.org/licenses/LICENSE-2.0
12
+#
13
+# Unless required by applicable law or agreed to in writing,
14
+# software distributed under the License is distributed on an
15
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16
+#  KIND, either express or implied.  See the License for the
17
+# specific language governing permissions and limitations
18
+# under the License.
19
+#
20
+-->
21
+
22
+# Contributing to Apache Cordova
23
+
24
+Anyone can contribute to Cordova. And we need your contributions.
25
+
26
+There are multiple ways to contribute: report bugs, improve the docs, and
27
+contribute code.
28
+
29
+For instructions on this, start with the 
30
+[contribution overview](http://cordova.apache.org/contribute/).
31
+
32
+The details are explained there, but the important items are:
33
+ - Sign and submit an Apache ICLA (Contributor License Agreement).
34
+ - Have a Jira issue open that corresponds to your contribution.
35
+ - Run the tests so your patch doesn't break existing functionality.
36
+
37
+We look forward to your contributions!

+ 202
- 0
node_modules/cordova-plugin-file/LICENSE Visa fil

@@ -0,0 +1,202 @@
1
+
2
+                                 Apache License
3
+                           Version 2.0, January 2004
4
+                        http://www.apache.org/licenses/
5
+
6
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+   1. Definitions.
9
+
10
+      "License" shall mean the terms and conditions for use, reproduction,
11
+      and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+      "Licensor" shall mean the copyright owner or entity authorized by
14
+      the copyright owner that is granting the License.
15
+
16
+      "Legal Entity" shall mean the union of the acting entity and all
17
+      other entities that control, are controlled by, or are under common
18
+      control with that entity. For the purposes of this definition,
19
+      "control" means (i) the power, direct or indirect, to cause the
20
+      direction or management of such entity, whether by contract or
21
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+      outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+      "You" (or "Your") shall mean an individual or Legal Entity
25
+      exercising permissions granted by this License.
26
+
27
+      "Source" form shall mean the preferred form for making modifications,
28
+      including but not limited to software source code, documentation
29
+      source, and configuration files.
30
+
31
+      "Object" form shall mean any form resulting from mechanical
32
+      transformation or translation of a Source form, including but
33
+      not limited to compiled object code, generated documentation,
34
+      and conversions to other media types.
35
+
36
+      "Work" shall mean the work of authorship, whether in Source or
37
+      Object form, made available under the License, as indicated by a
38
+      copyright notice that is included in or attached to the work
39
+      (an example is provided in the Appendix below).
40
+
41
+      "Derivative Works" shall mean any work, whether in Source or Object
42
+      form, that is based on (or derived from) the Work and for which the
43
+      editorial revisions, annotations, elaborations, or other modifications
44
+      represent, as a whole, an original work of authorship. For the purposes
45
+      of this License, Derivative Works shall not include works that remain
46
+      separable from, or merely link (or bind by name) to the interfaces of,
47
+      the Work and Derivative Works thereof.
48
+
49
+      "Contribution" shall mean any work of authorship, including
50
+      the original version of the Work and any modifications or additions
51
+      to that Work or Derivative Works thereof, that is intentionally
52
+      submitted to Licensor for inclusion in the Work by the copyright owner
53
+      or by an individual or Legal Entity authorized to submit on behalf of
54
+      the copyright owner. For the purposes of this definition, "submitted"
55
+      means any form of electronic, verbal, or written communication sent
56
+      to the Licensor or its representatives, including but not limited to
57
+      communication on electronic mailing lists, source code control systems,
58
+      and issue tracking systems that are managed by, or on behalf of, the
59
+      Licensor for the purpose of discussing and improving the Work, but
60
+      excluding communication that is conspicuously marked or otherwise
61
+      designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+      "Contributor" shall mean Licensor and any individual or Legal Entity
64
+      on behalf of whom a Contribution has been received by Licensor and
65
+      subsequently incorporated within the Work.
66
+
67
+   2. Grant of Copyright License. Subject to the terms and conditions of
68
+      this License, each Contributor hereby grants to You a perpetual,
69
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+      copyright license to reproduce, prepare Derivative Works of,
71
+      publicly display, publicly perform, sublicense, and distribute the
72
+      Work and such Derivative Works in Source or Object form.
73
+
74
+   3. Grant of Patent License. Subject to the terms and conditions of
75
+      this License, each Contributor hereby grants to You a perpetual,
76
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+      (except as stated in this section) patent license to make, have made,
78
+      use, offer to sell, sell, import, and otherwise transfer the Work,
79
+      where such license applies only to those patent claims licensable
80
+      by such Contributor that are necessarily infringed by their
81
+      Contribution(s) alone or by combination of their Contribution(s)
82
+      with the Work to which such Contribution(s) was submitted. If You
83
+      institute patent litigation against any entity (including a
84
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+      or a Contribution incorporated within the Work constitutes direct
86
+      or contributory patent infringement, then any patent licenses
87
+      granted to You under this License for that Work shall terminate
88
+      as of the date such litigation is filed.
89
+
90
+   4. Redistribution. You may reproduce and distribute copies of the
91
+      Work or Derivative Works thereof in any medium, with or without
92
+      modifications, and in Source or Object form, provided that You
93
+      meet the following conditions:
94
+
95
+      (a) You must give any other recipients of the Work or
96
+          Derivative Works a copy of this License; and
97
+
98
+      (b) You must cause any modified files to carry prominent notices
99
+          stating that You changed the files; and
100
+
101
+      (c) You must retain, in the Source form of any Derivative Works
102
+          that You distribute, all copyright, patent, trademark, and
103
+          attribution notices from the Source form of the Work,
104
+          excluding those notices that do not pertain to any part of
105
+          the Derivative Works; and
106
+
107
+      (d) If the Work includes a "NOTICE" text file as part of its
108
+          distribution, then any Derivative Works that You distribute must
109
+          include a readable copy of the attribution notices contained
110
+          within such NOTICE file, excluding those notices that do not
111
+          pertain to any part of the Derivative Works, in at least one
112
+          of the following places: within a NOTICE text file distributed
113
+          as part of the Derivative Works; within the Source form or
114
+          documentation, if provided along with the Derivative Works; or,
115
+          within a display generated by the Derivative Works, if and
116
+          wherever such third-party notices normally appear. The contents
117
+          of the NOTICE file are for informational purposes only and
118
+          do not modify the License. You may add Your own attribution
119
+          notices within Derivative Works that You distribute, alongside
120
+          or as an addendum to the NOTICE text from the Work, provided
121
+          that such additional attribution notices cannot be construed
122
+          as modifying the License.
123
+
124
+      You may add Your own copyright statement to Your modifications and
125
+      may provide additional or different license terms and conditions
126
+      for use, reproduction, or distribution of Your modifications, or
127
+      for any such Derivative Works as a whole, provided Your use,
128
+      reproduction, and distribution of the Work otherwise complies with
129
+      the conditions stated in this License.
130
+
131
+   5. Submission of Contributions. Unless You explicitly state otherwise,
132
+      any Contribution intentionally submitted for inclusion in the Work
133
+      by You to the Licensor shall be under the terms and conditions of
134
+      this License, without any additional terms or conditions.
135
+      Notwithstanding the above, nothing herein shall supersede or modify
136
+      the terms of any separate license agreement you may have executed
137
+      with Licensor regarding such Contributions.
138
+
139
+   6. Trademarks. This License does not grant permission to use the trade
140
+      names, trademarks, service marks, or product names of the Licensor,
141
+      except as required for reasonable and customary use in describing the
142
+      origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+   7. Disclaimer of Warranty. Unless required by applicable law or
145
+      agreed to in writing, Licensor provides the Work (and each
146
+      Contributor provides its Contributions) on an "AS IS" BASIS,
147
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+      implied, including, without limitation, any warranties or conditions
149
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+      PARTICULAR PURPOSE. You are solely responsible for determining the
151
+      appropriateness of using or redistributing the Work and assume any
152
+      risks associated with Your exercise of permissions under this License.
153
+
154
+   8. Limitation of Liability. In no event and under no legal theory,
155
+      whether in tort (including negligence), contract, or otherwise,
156
+      unless required by applicable law (such as deliberate and grossly
157
+      negligent acts) or agreed to in writing, shall any Contributor be
158
+      liable to You for damages, including any direct, indirect, special,
159
+      incidental, or consequential damages of any character arising as a
160
+      result of this License or out of the use or inability to use the
161
+      Work (including but not limited to damages for loss of goodwill,
162
+      work stoppage, computer failure or malfunction, or any and all
163
+      other commercial damages or losses), even if such Contributor
164
+      has been advised of the possibility of such damages.
165
+
166
+   9. Accepting Warranty or Additional Liability. While redistributing
167
+      the Work or Derivative Works thereof, You may choose to offer,
168
+      and charge a fee for, acceptance of support, warranty, indemnity,
169
+      or other liability obligations and/or rights consistent with this
170
+      License. However, in accepting such obligations, You may act only
171
+      on Your own behalf and on Your sole responsibility, not on behalf
172
+      of any other Contributor, and only if You agree to indemnify,
173
+      defend, and hold each Contributor harmless for any liability
174
+      incurred by, or claims asserted against, such Contributor by reason
175
+      of your accepting any such warranty or additional liability.
176
+
177
+   END OF TERMS AND CONDITIONS
178
+
179
+   APPENDIX: How to apply the Apache License to your work.
180
+
181
+      To apply the Apache License to your work, attach the following
182
+      boilerplate notice, with the fields enclosed by brackets "[]"
183
+      replaced with your own identifying information. (Don't include
184
+      the brackets!)  The text should be enclosed in the appropriate
185
+      comment syntax for the file format. We also recommend that a
186
+      file or class name and description of purpose be included on the
187
+      same "printed page" as the copyright notice for easier
188
+      identification within third-party archives.
189
+
190
+   Copyright [yyyy] [name of copyright owner]
191
+
192
+   Licensed under the Apache License, Version 2.0 (the "License");
193
+   you may not use this file except in compliance with the License.
194
+   You may obtain a copy of the License at
195
+
196
+       http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+   Unless required by applicable law or agreed to in writing, software
199
+   distributed under the License is distributed on an "AS IS" BASIS,
200
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+   See the License for the specific language governing permissions and
202
+   limitations under the License.

+ 5
- 0
node_modules/cordova-plugin-file/NOTICE Visa fil

@@ -0,0 +1,5 @@
1
+Apache Cordova
2
+Copyright 2012 The Apache Software Foundation
3
+
4
+This product includes software developed at
5
+The Apache Software Foundation (http://www.apache.org/).

+ 833
- 0
node_modules/cordova-plugin-file/README.md Visa fil

@@ -0,0 +1,833 @@
1
+---
2
+title: File
3
+description: Read/write files on the device.
4
+---
5
+<!--
6
+# license: Licensed to the Apache Software Foundation (ASF) under one
7
+#         or more contributor license agreements.  See the NOTICE file
8
+#         distributed with this work for additional information
9
+#         regarding copyright ownership.  The ASF licenses this file
10
+#         to you under the Apache License, Version 2.0 (the
11
+#         "License"); you may not use this file except in compliance
12
+#         with the License.  You may obtain a copy of the License at
13
+#
14
+#           http://www.apache.org/licenses/LICENSE-2.0
15
+#
16
+#         Unless required by applicable law or agreed to in writing,
17
+#         software distributed under the License is distributed on an
18
+#         "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
19
+#         KIND, either express or implied.  See the License for the
20
+#         specific language governing permissions and limitations
21
+#         under the License.
22
+-->
23
+
24
+|AppVeyor|Travis CI|
25
+|:-:|:-:|
26
+|[![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)|
27
+
28
+# cordova-plugin-file
29
+
30
+This plugin implements a File API allowing read/write access to files residing on the device.
31
+
32
+This plugin is based on several specs, including :
33
+The HTML5 File API
34
+[http://www.w3.org/TR/FileAPI/](http://www.w3.org/TR/FileAPI/)
35
+
36
+The Directories and System extensions
37
+Latest:
38
+[http://www.w3.org/TR/2012/WD-file-system-api-20120417/](http://www.w3.org/TR/2012/WD-file-system-api-20120417/)
39
+Although most of the plugin code was written when an earlier spec was current:
40
+[http://www.w3.org/TR/2011/WD-file-system-api-20110419/](http://www.w3.org/TR/2011/WD-file-system-api-20110419/)
41
+
42
+It also implements the FileWriter spec :
43
+[http://dev.w3.org/2009/dap/file-system/file-writer.html](http://dev.w3.org/2009/dap/file-system/file-writer.html)
44
+
45
+>*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.
46
+
47
+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/)
48
+
49
+For an overview of other storage options, refer to Cordova's
50
+[storage guide](http://cordova.apache.org/docs/en/latest/cordova/storage/storage.html).
51
+
52
+This plugin defines global `cordova.file` object.
53
+
54
+Although in the global scope, it is not available until after the `deviceready` event.
55
+
56
+    document.addEventListener("deviceready", onDeviceReady, false);
57
+    function onDeviceReady() {
58
+        console.log(cordova.file);
59
+    }
60
+
61
+## Installation
62
+
63
+    cordova plugin add cordova-plugin-file
64
+
65
+## Supported Platforms
66
+
67
+- Android
68
+- iOS
69
+- OS X
70
+- Windows*
71
+- Browser
72
+
73
+\* _These platforms do not support `FileReader.readAsArrayBuffer` nor `FileWriter.write(blob)`._
74
+
75
+## Where to Store Files
76
+
77
+As of v1.2.0, URLs to important file-system directories are provided.
78
+Each URL is in the form _file:///path/to/spot/_, and can be converted to a
79
+`DirectoryEntry` using `window.resolveLocalFileSystemURL()`.
80
+
81
+* `cordova.file.applicationDirectory` - Read-only directory where the application
82
+  is installed. (_iOS_, _Android_, _BlackBerry 10_, _OSX_, _windows_)
83
+
84
+* `cordova.file.applicationStorageDirectory` - Root directory of the application's
85
+  sandbox; on iOS & windows this location is read-only (but specific subdirectories [like
86
+  `/Documents` on iOS or `/localState` on windows] are read-write). All data contained within
87
+  is private to the app. (_iOS_, _Android_, _BlackBerry 10_, _OSX_)
88
+
89
+* `cordova.file.dataDirectory` - Persistent and private data storage within the
90
+  application's sandbox using internal memory (on Android, if you need to use
91
+  external memory, use `.externalDataDirectory`). On iOS, this directory is not
92
+  synced with iCloud (use `.syncedDataDirectory`). (_iOS_, _Android_, _BlackBerry 10_, _windows_)
93
+
94
+* `cordova.file.cacheDirectory` -  Directory for cached data files or any files
95
+  that your app can re-create easily. The OS may delete these files when the device
96
+  runs low on storage, nevertheless, apps should not rely on the OS to delete files
97
+  in here. (_iOS_, _Android_, _BlackBerry 10_, _OSX_, _windows_)
98
+
99
+* `cordova.file.externalApplicationStorageDirectory` - Application space on
100
+  external storage. (_Android_)
101
+
102
+* `cordova.file.externalDataDirectory` - Where to put app-specific data files on
103
+  external storage. (_Android_)
104
+
105
+* `cordova.file.externalCacheDirectory` - Application cache on external storage.
106
+  (_Android_)
107
+
108
+* `cordova.file.externalRootDirectory` - External storage (SD card) root. (_Android_, _BlackBerry 10_)
109
+
110
+* `cordova.file.tempDirectory` - Temp directory that the OS can clear at will. Do not
111
+  rely on the OS to clear this directory; your app should always remove files as
112
+  applicable. (_iOS_, _OSX_, _windows_)
113
+
114
+* `cordova.file.syncedDataDirectory` - Holds app-specific files that should be synced
115
+  (e.g. to iCloud). (_iOS_, _windows_)
116
+
117
+* `cordova.file.documentsDirectory` - Files private to the app, but that are meaningful
118
+  to other application (e.g. Office files). Note that for _OSX_ this is the user's `~/Documents` directory. (_iOS_, _OSX_)
119
+
120
+* `cordova.file.sharedDirectory` - Files globally available to all applications (_BlackBerry 10_)
121
+
122
+## File System Layouts
123
+
124
+Although technically an implementation detail, it can be very useful to know how
125
+the `cordova.file.*` properties map to physical paths on a real device.
126
+
127
+### iOS File System Layout
128
+
129
+| Device Path                                    | `cordova.file.*`            | `iosExtraFileSystems` | r/w? | persistent? | OS clears | sync | private |
130
+|:-----------------------------------------------|:----------------------------|:----------------------|:----:|:-----------:|:---------:|:----:|:-------:|
131
+| `/var/mobile/Applications/<UUID>/`             | applicationStorageDirectory | -                     | r    |     N/A     |     N/A   | N/A  |   Yes   |
132
+| &nbsp;&nbsp;&nbsp;`appname.app/`               | applicationDirectory        | bundle                | r    |     N/A     |     N/A   | N/A  |   Yes   |
133
+| &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`www/`     | -                           | -                     | r    |     N/A     |     N/A   | N/A  |   Yes   |
134
+| &nbsp;&nbsp;&nbsp;`Documents/`                 | documentsDirectory          | documents             | r/w  |     Yes     |     No    | Yes  |   Yes   |
135
+| &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`NoCloud/` | -                           | documents-nosync      | r/w  |     Yes     |     No    | No   |   Yes   |
136
+| &nbsp;&nbsp;&nbsp;`Library`                    | -                           | library               | r/w  |     Yes     |     No    | Yes? |   Yes   |
137
+| &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`NoCloud/` | dataDirectory               | library-nosync        | r/w  |     Yes     |     No    | No   |   Yes   |
138
+| &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`Cloud/`   | syncedDataDirectory         | -                     | r/w  |     Yes     |     No    | Yes  |   Yes   |
139
+| &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`Caches/`  | cacheDirectory              | cache                 | r/w  |     Yes*    |  Yes\*\*\*| No   |   Yes   |
140
+| &nbsp;&nbsp;&nbsp;`tmp/`                       | tempDirectory               | -                     | r/w  |     No\*\*  |  Yes\*\*\*| No   |   Yes   |
141
+
142
+
143
+  \* Files persist across app restarts and upgrades, but this directory can
144
+     be cleared whenever the OS desires. Your app should be able to recreate any
145
+     content that might be deleted.
146
+
147
+\*\* Files may persist across app restarts, but do not rely on this behavior. Files
148
+     are not guaranteed to persist across updates. Your app should remove files from
149
+     this directory when it is applicable, as the OS does not guarantee when (or even
150
+     if) these files are removed.
151
+
152
+\*\*\* The OS may clear the contents of this directory whenever it feels it is
153
+     necessary, but do not rely on this. You should clear this directory as
154
+     appropriate for your application.
155
+
156
+### Android File System Layout
157
+
158
+| Device Path                                     | `cordova.file.*`            | `AndroidExtraFileSystems` | r/w? | persistent? | OS clears | private |
159
+|:------------------------------------------------|:----------------------------|:--------------------------|:----:|:-----------:|:---------:|:-------:|
160
+| `file:///android_asset/`                        | applicationDirectory        | assets                    | r    |     N/A     |     N/A   |   Yes   |
161
+| `/data/data/<app-id>/`                          | applicationStorageDirectory | -                         | r/w  |     N/A     |     N/A   |   Yes   |
162
+| &nbsp;&nbsp;&nbsp;`cache`                       | cacheDirectory              | cache                     | r/w  |     Yes     |     Yes\* |   Yes   |
163
+| &nbsp;&nbsp;&nbsp;`files`                       | dataDirectory               | files                     | r/w  |     Yes     |     No    |   Yes   |
164
+| &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`Documents` |                             | documents                 | r/w  |     Yes     |     No    |   Yes   |
165
+| `<sdcard>/`                                     | externalRootDirectory       | sdcard                    | r/w  |     Yes     |     No    |   No    |
166
+| &nbsp;&nbsp;&nbsp;`Android/data/<app-id>/`      | externalApplicationStorageDirectory | -                 | r/w  |     Yes     |     No    |   No    |
167
+| &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`cache`     | externalCacheDirectory       | cache-external            | r/w  |     Yes     |     No\*\*|   No    |
168
+| &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`files`     | externalDataDirectory       | files-external            | r/w  |     Yes     |     No    |   No    |
169
+
170
+\* The OS may periodically clear this directory, but do not rely on this behavior. Clear
171
+   the contents of this directory as appropriate for your application. Should a user
172
+   purge the cache manually, the contents of this directory are removed.
173
+
174
+\*\* The OS does not clear this directory automatically; you are responsible for managing
175
+     the contents yourself. Should the user purge the cache manually, the contents of the
176
+     directory are removed.
177
+
178
+**Note**: If external storage can't be mounted, the `cordova.file.external*`
179
+properties are `null`.
180
+
181
+### OS X File System Layout
182
+
183
+| Device Path                                      | `cordova.file.*`            | `iosExtraFileSystems` | r/w? |  OS clears | private |
184
+|:-------------------------------------------------|:----------------------------|:----------------------|:----:|:---------:|:-------:|
185
+| `/Applications/<appname>.app/`                   | -                           | bundle                | r    |     N/A   |   Yes   |
186
+| &nbsp;&nbsp;&nbsp;&nbsp;`Content/Resources/`     | applicationDirectory        | -                     | r    |     N/A   |   Yes   |
187
+| `~/Library/Application Support/<bundle-id>/`     | applicationStorageDirectory | -                     | r/w  |     No    |   Yes   |
188
+| &nbsp;&nbsp;&nbsp;&nbsp;`files/`                 | dataDirectory               | -                     | r/w  |     No    |   Yes   |
189
+| `~/Documents/`                                   | documentsDirectory          | documents             | r/w  |     No    |    No   |
190
+| `~/Library/Caches/<bundle-id>/`                  | cacheDirectory              | cache                 | r/w  |     No    |   Yes   |
191
+| `/tmp/`                                          | tempDirectory               | -                     | r/w  |    Yes\*  |   Yes   |
192
+| `/`                                              | rootDirectory               | root                  | r/w  |    No\*\* |    No   |
193
+
194
+**Note**: This is the layout for non sandboxed applications. I you enable sandboxing, the `applicationStorageDirectory` will be below ` ~/Library/Containers/<bundle-id>/Data/Library/Application Support`.
195
+
196
+\* Files persist across app restarts and upgrades, but this directory can
197
+     be cleared whenever the OS desires. Your app should be able to recreate any
198
+     content that might be deleted. You should clear this directory as
199
+     appropriate for your application.
200
+
201
+\*\* Allows access to the entire file system. This is only available for non sandboxed apps.
202
+
203
+### Windows File System Layout
204
+
205
+| Device Path                                           | `cordova.file.*`            | r/w? | persistent? | OS clears | private |
206
+|:------------------------------------------------------|:----------------------------|:----:|:-----------:|:---------:|:-------:|
207
+| `ms-appdata:///`                                      | applicationDirectory        | r    |     N/A     |     N/A   |   Yes   |
208
+| &nbsp;&nbsp;&nbsp;`local/`                            | dataDirectory               | r/w  |     Yes     |     No    |   Yes   |
209
+| &nbsp;&nbsp;&nbsp;`temp/`                             | cacheDirectory              | r/w  |     No      |     Yes\* |   Yes   |
210
+| &nbsp;&nbsp;&nbsp;`temp/`                             | tempDirectory               | r/w  |     No      |     Yes\* |   Yes   |
211
+| &nbsp;&nbsp;&nbsp;`roaming/`                          | syncedDataDirectory         | r/w  |     Yes     |     No    |   Yes   |
212
+
213
+\* The OS may periodically clear this directory
214
+
215
+
216
+## Android Quirks
217
+
218
+### Android Persistent storage location
219
+
220
+There are multiple valid locations to store persistent files on an Android
221
+device. See [this page](http://developer.android.com/guide/topics/data/data-storage.html)
222
+for an extensive discussion of the various possibilities.
223
+
224
+Previous versions of the plugin would choose the location of the temporary and
225
+persistent files on startup, based on whether the device claimed that the SD
226
+Card (or equivalent storage partition) was mounted. If the SD Card was mounted,
227
+or if a large internal storage partition was available (such as on Nexus
228
+devices,) then the persistent files would be stored in the root of that space.
229
+This meant that all Cordova apps could see all of the files available on the
230
+card.
231
+
232
+If the SD card was not available, then previous versions would store data under
233
+`/data/data/<packageId>`, which isolates apps from each other, but may still
234
+cause data to be shared between users.
235
+
236
+It is now possible to choose whether to store files in the internal file
237
+storage location, or using the previous logic, with a preference in your
238
+application's `config.xml` file. To do this, add one of these two lines to
239
+`config.xml`:
240
+
241
+    <preference name="AndroidPersistentFileLocation" value="Internal" />
242
+
243
+    <preference name="AndroidPersistentFileLocation" value="Compatibility" />
244
+
245
+Without this line, the File plugin will use `Internal` as the default. If
246
+a preference tag is present, and is not one of these values, the application
247
+will not start.
248
+
249
+If your application has previously been shipped to users, using an older (pre-
250
+3.0.0) version of this plugin, and has stored files in the persistent filesystem,
251
+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
252
+"Internal" would mean that existing users who upgrade their application may be
253
+unable to access their previously-stored files, depending on their device.
254
+
255
+If your application is new, or has never previously stored files in the
256
+persistent filesystem, then the `Internal` setting is generally recommended.
257
+
258
+### Slow recursive operations for /android_asset
259
+
260
+Listing asset directories is really slow on Android. You can speed it up though, by
261
+adding `src/android/build-extras.gradle` to the root of your android project (also
262
+requires cordova-android@4.0.0 or greater).
263
+
264
+### Permisson to write to external storage when it's not mounted on Marshmallow
265
+
266
+Marshmallow requires the apps to ask for permissions when reading/writing to external locations. By
267
+[default](http://developer.android.com/guide/topics/data/data-storage.html#filesExternal), your app has permission to write to
268
+`cordova.file.applicationStorageDirectory` and `cordova.file.externalApplicationStorageDirectory`, and the plugin doesn't request permission
269
+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
270
+permission to write to `cordova.file.externalApplicationStorageDirectory`.
271
+
272
+## iOS Quirks
273
+
274
+- `cordova.file.applicationStorageDirectory` is read-only; attempting to store
275
+  files within the root directory will fail. Use one of the other `cordova.file.*`
276
+  properties defined for iOS (only `applicationDirectory` and `applicationStorageDirectory` are
277
+  read-only).
278
+- `FileReader.readAsText(blob, encoding)`
279
+  - The `encoding` parameter is not supported, and UTF-8 encoding is always in effect.
280
+
281
+### iOS Persistent storage location
282
+
283
+There are two valid locations to store persistent files on an iOS device: the
284
+Documents directory and the Library directory. Previous versions of the plugin
285
+only ever stored persistent files in the Documents directory. This had the
286
+side-effect of making all of an application's files visible in iTunes, which
287
+was often unintended, especially for applications which handle lots of small
288
+files, rather than producing complete documents for export, which is the
289
+intended purpose of the directory.
290
+
291
+It is now possible to choose whether to store files in the documents or library
292
+directory, with a preference in your application's `config.xml` file. To do this,
293
+add one of these two lines to `config.xml`:
294
+
295
+    <preference name="iosPersistentFileLocation" value="Library" />
296
+
297
+    <preference name="iosPersistentFileLocation" value="Compatibility" />
298
+
299
+Without this line, the File plugin will use `Compatibility` as the default. If
300
+a preference tag is present, and is not one of these values, the application
301
+will not start.
302
+
303
+If your application has previously been shipped to users, using an older (pre-
304
+1.0) version of this plugin, and has stored files in the persistent filesystem,
305
+then you should set the preference to `Compatibility`. Switching the location to
306
+`Library` would mean that existing users who upgrade their application would be
307
+unable to access their previously-stored files.
308
+
309
+If your application is new, or has never previously stored files in the
310
+persistent filesystem, then the `Library` setting is generally recommended.
311
+
312
+## Browser Quirks
313
+
314
+### Common quirks and remarks
315
+- Each browser uses its own sandboxed filesystem. IE and Firefox use IndexedDB as a base.
316
+All browsers use forward slash as directory separator in a path.
317
+- Directory entries have to be created successively.
318
+For example, the call `fs.root.getDirectory('dir1/dir2', {create:true}, successCallback, errorCallback)`
319
+will fail if dir1 did not exist.
320
+- The plugin requests user permission to use persistent storage at the application first start.
321
+- Plugin supports `cdvfile://localhost` (local resources) only. I.e. external resources are not supported via `cdvfile`.
322
+- 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).
323
+- Blob and File' `close` function is not supported.
324
+- `FileSaver` and `BlobBuilder` are not supported by this plugin and don't have stubs.
325
+- The plugin does not support `requestAllFileSystems`. This function is also missing in the specifications.
326
+- Entries in directory will not be removed if you use `create: true` flag for existing directory.
327
+- Files created via constructor are not supported. You should use entry.file method instead.
328
+- Each browser uses its own form for blob URL references.
329
+- `readAsDataURL` function is supported, but the mediatype in Chrome depends on entry name extension,
330
+mediatype in IE is always empty (which is the same as `text-plain` according the specification),
331
+the mediatype in Firefox is always `application/octet-stream`.
332
+For example, if the content is `abcdefg` then Firefox returns `data:application/octet-stream;base64,YWJjZGVmZw==`,
333
+IE returns `data:;base64,YWJjZGVmZw==`, Chrome returns `data:<mediatype depending on extension of entry name>;base64,YWJjZGVmZw==`.
334
+- `toInternalURL` returns the path in the form `file:///persistent/path/to/entry` (Firefox, IE).
335
+Chrome returns the path in the form `cdvfile://localhost/persistent/file`.
336
+
337
+### Chrome quirks
338
+- Chrome filesystem is not immediately ready after device ready event. As a workaround you can subscribe to `filePluginIsReady` event.
339
+Example:
340
+```javascript
341
+window.addEventListener('filePluginIsReady', function(){ console.log('File plugin is ready');}, false);
342
+```
343
+You can use `window.isFilePluginReadyRaised` function to check whether event was already raised.
344
+- window.requestFileSystem TEMPORARY and PERSISTENT filesystem quotas are not limited in Chrome.
345
+- To increase persistent storage in Chrome you need to call `window.initPersistentFileSystem` method. Persistent storage quota is 5 MB by default.
346
+- Chrome requires `--allow-file-access-from-files` run argument to support API via `file:///` protocol.
347
+- `File` object will be not changed if you use flag `{create:true}` when getting an existing `Entry`.
348
+- 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).
349
+- `toURL` function in Chrome returns `filesystem:`-prefixed path depending on application host.
350
+For example, `filesystem:file:///persistent/somefile.txt`, `filesystem:http://localhost:8080/persistent/somefile.txt`.
351
+- `toURL` function result does not contain trailing slash in case of directory entry.
352
+Chrome resolves directories with slash-trailed urls correctly though.
353
+- `resolveLocalFileSystemURL` method requires the inbound `url` to have `filesystem` prefix. For example, `url` parameter for `resolveLocalFileSystemURL`
354
+should be in the form `filesystem:file:///persistent/somefile.txt` as opposed to the form `file:///persistent/somefile.txt` in Android.
355
+- Deprecated `toNativeURL` function is not supported and does not have a stub.
356
+- `setMetadata` function is not stated in the specifications and not supported.
357
+- INVALID_MODIFICATION_ERR (code: 9) is thrown instead of SYNTAX_ERR(code: 8) on requesting of a non-existant filesystem.
358
+- 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.
359
+- 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.
360
+- INVALID_MODIFICATION_ERR (code: 9) is thrown instead of NOT_FOUND_ERR(code: 1) on trying to moveTo directory that does not exist.
361
+
362
+### IndexedDB-based impl quirks (Firefox and IE)
363
+- `.` and `..` are not supported.
364
+- IE does not support `file:///`-mode; only hosted mode is supported (http://localhost:xxxx).
365
+- Firefox filesystem size is not limited but each 50MB extension will request a user permission.
366
+IE10 allows up to 10mb of combined AppCache and IndexedDB used in implementation of filesystem without prompting,
367
+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.
368
+So `size` parameter for `requestFileSystem` function does not affect filesystem in Firefox and IE.
369
+- `readAsBinaryString` function is not stated in the Specs and not supported in IE and does not have a stub.
370
+- `file.type` is always null.
371
+- You should not create entry using DirectoryEntry instance callback result which was deleted.
372
+Otherwise, you will get a 'hanging entry'.
373
+- Before you can read a file, which was just written you need to get a new instance of this file.
374
+- `setMetadata` function, which is not stated in the Specs supports `modificationTime` field change only.
375
+- `copyTo` and `moveTo` functions do not support directories.
376
+- Directories metadata is not supported.
377
+- Both Entry.remove and directoryEntry.removeRecursively don't fail when removing
378
+non-empty directories - directories being removed are cleaned along with contents instead.
379
+- `abort` and `truncate` functions are not supported.
380
+- progress events are not fired. For example, this handler will be not executed:
381
+```javascript
382
+writer.onprogress = function() { /*commands*/ };
383
+```
384
+
385
+## Upgrading Notes
386
+
387
+In v1.0.0 of this plugin, the `FileEntry` and `DirectoryEntry` structures have changed,
388
+to be more in line with the published specification.
389
+
390
+Previous (pre-1.0.0) versions of the plugin stored the device-absolute-file-location
391
+in the `fullPath` property of `Entry` objects. These paths would typically look like
392
+
393
+    /var/mobile/Applications/<application UUID>/Documents/path/to/file  (iOS)
394
+    /storage/emulated/0/path/to/file                                    (Android)
395
+
396
+These paths were also returned by the `toURL()` method of the `Entry` objects.
397
+
398
+With v1.0.0, the `fullPath` attribute is the path to the file, _relative to the root of
399
+the HTML filesystem_. So, the above paths would now both be represented by a `FileEntry`
400
+object with a `fullPath` of
401
+
402
+    /path/to/file
403
+
404
+If your application works with device-absolute-paths, and you previously retrieved those
405
+paths through the `fullPath` property of `Entry` objects, then you should update your code
406
+to use `entry.toURL()` instead.
407
+
408
+For backwards compatibility, the `resolveLocalFileSystemURL()` method will accept a
409
+device-absolute-path, and will return an `Entry` object corresponding to it, as long as that
410
+file exists within either the `TEMPORARY` or `PERSISTENT` filesystems.
411
+
412
+This has particularly been an issue with the File-Transfer plugin, which previously used
413
+device-absolute-paths (and can still accept them). It has been updated to work correctly
414
+with FileSystem URLs, so replacing `entry.fullPath` with `entry.toURL()` should resolve any
415
+issues getting that plugin to work with files on the device.
416
+
417
+In v1.1.0 the return value of `toURL()` was changed (see [CB-6394](https://issues.apache.org/jira/browse/CB-6394))
418
+to return an absolute 'file://' URL. wherever possible. To ensure a 'cdvfile:'-URL you can use `toInternalURL()` now.
419
+This method will now return filesystem URLs of the form
420
+
421
+    cdvfile://localhost/persistent/path/to/file
422
+
423
+which can be used to identify the file uniquely.
424
+
425
+## cdvfile protocol
426
+**Purpose**
427
+
428
+`cdvfile://localhost/persistent|temporary|another-fs-root*/path/to/file` can be used for platform-independent file paths.
429
+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`.
430
+
431
+__*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.
432
+
433
+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.
434
+
435
+You can also use `cdvfile://` paths directly in the DOM, for example:
436
+```HTML
437
+<img src="cdvfile://localhost/persistent/img/logo.png" />
438
+```
439
+
440
+__Note__: This method requires following Content Security rules updates:
441
+* Add `cdvfile:` scheme to `Content-Security-Policy` meta tag of the index page, e.g.:
442
+  - `<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: `**cdvfile:**` https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">`
443
+* Add `<access origin="cdvfile://*" />` to `config.xml`.
444
+
445
+**Converting cdvfile:// to native path**
446
+
447
+```javascript
448
+resolveLocalFileSystemURL('cdvfile://localhost/temporary/path/to/file.mp4', function(entry) {
449
+    var nativePath = entry.toURL();
450
+    console.log('Native URI: ' + nativePath);
451
+    document.getElementById('video').src = nativePath;
452
+```
453
+
454
+**Converting native path to cdvfile://**
455
+
456
+```javascript
457
+resolveLocalFileSystemURL(nativePath, function(entry) {
458
+    console.log('cdvfile URI: ' + entry.toInternalURL());
459
+```
460
+
461
+**Using cdvfile in core plugins**
462
+
463
+```javascript
464
+fileTransfer.download(uri, 'cdvfile://localhost/temporary/path/to/file.mp3', function (entry) { ...
465
+```
466
+```javascript
467
+var my_media = new Media('cdvfile://localhost/temporary/path/to/file.mp3', ...);
468
+my_media.play();
469
+```
470
+
471
+#### cdvfile quirks
472
+- Using `cdvfile://` paths in the DOM is not supported on Windows platform (a path can be converted to native instead).
473
+
474
+
475
+## List of Error Codes and Meanings
476
+When an error is thrown, one of the following codes will be used.
477
+
478
+| Code | Constant                      |
479
+|-----:|:------------------------------|
480
+|    1 | `NOT_FOUND_ERR`               |
481
+|    2 | `SECURITY_ERR`                |
482
+|    3 | `ABORT_ERR`                   |
483
+|    4 | `NOT_READABLE_ERR`            |
484
+|    5 | `ENCODING_ERR`                |
485
+|    6 | `NO_MODIFICATION_ALLOWED_ERR` |
486
+|    7 | `INVALID_STATE_ERR`           |
487
+|    8 | `SYNTAX_ERR`                  |
488
+|    9 | `INVALID_MODIFICATION_ERR`    |
489
+|   10 | `QUOTA_EXCEEDED_ERR`          |
490
+|   11 | `TYPE_MISMATCH_ERR`           |
491
+|   12 | `PATH_EXISTS_ERR`             |
492
+
493
+## Configuring the Plugin (Optional)
494
+
495
+The set of available filesystems can be configured per-platform. Both iOS and
496
+Android recognize a <preference> tag in `config.xml` which names the
497
+filesystems to be installed. By default, all file-system roots are enabled.
498
+
499
+    <preference name="iosExtraFilesystems" value="library,library-nosync,documents,documents-nosync,cache,bundle,root" />
500
+    <preference name="AndroidExtraFilesystems" value="files,files-external,documents,sdcard,cache,cache-external,assets,root" />
501
+
502
+### Android
503
+
504
+* `files`: The application's internal file storage directory
505
+* `files-external`: The application's external file storage directory
506
+* `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.
507
+* `cache`: The application's internal cache directory
508
+* `cache-external`: The application's external cache directory
509
+* `assets`: The application's bundle (read-only)
510
+* `root`: The entire device filesystem
511
+* `applicationDirectory`: ReadOnly with restricted access. Copying files in this directory is possible, but reading it directly results in 'file not found'.
512
+Android also supports a special filesystem named "documents", which represents a "/Documents/" subdirectory within the "files" filesystem.
513
+
514
+### iOS
515
+
516
+* `library`: The application's Library directory
517
+* `documents`: The application's Documents directory
518
+* `cache`: The application's Cache directory
519
+* `bundle`: The application's bundle; the location of the app itself on disk (read-only)
520
+* `root`: The entire device filesystem
521
+
522
+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.
523
+
524
+## Sample: Create Files and Directories, Write, Read, and Append files <a name="sample"></a>
525
+
526
+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:
527
+* [Accessing the file system](#persistent)
528
+* Using cross-platform Cordova file URLs to [store your files](#appendFile) (see _Where to Store Files_ for more info)
529
+* Creating [files](#persistent) and [directories](#createDir)
530
+* [Writing to files](#writeFile)
531
+* [Reading files](#readFile)
532
+* [Appending files](#appendFile)
533
+* [Display an image file](#displayImage)
534
+
535
+## Create a persistent file <a name="persistent"></a>
536
+
537
+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.
538
+
539
+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_.)
540
+
541
+Here is a request for persistent storage.
542
+
543
+>*Note* When targeting WebView clients (instead of a browser) or native apps (Windows), you dont need to use `requestQuota` before using persistent storage.
544
+
545
+```js
546
+window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fs) {
547
+
548
+    console.log('file system open: ' + fs.name);
549
+    fs.root.getFile("newPersistentFile.txt", { create: true, exclusive: false }, function (fileEntry) {
550
+
551
+        console.log("fileEntry is file?" + fileEntry.isFile.toString());
552
+        // fileEntry.name == 'someFile.txt'
553
+        // fileEntry.fullPath == '/someFile.txt'
554
+        writeFile(fileEntry, null);
555
+
556
+    }, onErrorCreateFile);
557
+
558
+}, onErrorLoadFs);
559
+```
560
+
561
+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.
562
+
563
+The success callback for `getFile` receives a FileEntry object. You can use this to perform file write and file read operations.
564
+
565
+## Create a temporary file
566
+
567
+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.
568
+
569
+```js
570
+window.requestFileSystem(window.TEMPORARY, 5 * 1024 * 1024, function (fs) {
571
+
572
+    console.log('file system open: ' + fs.name);
573
+    createFile(fs.root, "newTempFile.txt", false);
574
+
575
+}, onErrorLoadFs);
576
+```
577
+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.
578
+
579
+```js
580
+function createFile(dirEntry, fileName, isAppend) {
581
+    // Creates a new file or returns the file if it already exists.
582
+    dirEntry.getFile(fileName, {create: true, exclusive: false}, function(fileEntry) {
583
+
584
+        writeFile(fileEntry, null, isAppend);
585
+
586
+    }, onErrorCreateFile);
587
+
588
+}
589
+```
590
+
591
+## Write to a file <a name="writeFile"></a>
592
+
593
+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.
594
+
595
+```js
596
+function writeFile(fileEntry, dataObj) {
597
+    // Create a FileWriter object for our FileEntry (log.txt).
598
+    fileEntry.createWriter(function (fileWriter) {
599
+
600
+        fileWriter.onwriteend = function() {
601
+            console.log("Successful file write...");
602
+            readFile(fileEntry);
603
+        };
604
+
605
+        fileWriter.onerror = function (e) {
606
+            console.log("Failed file write: " + e.toString());
607
+        };
608
+
609
+        // If data object is not passed in,
610
+        // create a new Blob instead.
611
+        if (!dataObj) {
612
+            dataObj = new Blob(['some file data'], { type: 'text/plain' });
613
+        }
614
+
615
+        fileWriter.write(dataObj);
616
+    });
617
+}
618
+```
619
+
620
+## Read a file <a name="readFile"></a>
621
+
622
+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.
623
+
624
+```js
625
+function readFile(fileEntry) {
626
+
627
+    fileEntry.file(function (file) {
628
+        var reader = new FileReader();
629
+
630
+        reader.onloadend = function() {
631
+            console.log("Successful file read: " + this.result);
632
+            displayFileData(fileEntry.fullPath + ": " + this.result);
633
+        };
634
+
635
+        reader.readAsText(file);
636
+
637
+    }, onErrorReadFile);
638
+}
639
+```
640
+
641
+## Append a file using alternative methods <a name="appendFile"></a>
642
+
643
+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.
644
+
645
+```js
646
+window.resolveLocalFileSystemURL(cordova.file.dataDirectory, function (dirEntry) {
647
+    console.log('file system open: ' + dirEntry.name);
648
+    var isAppend = true;
649
+    createFile(dirEntry, "fileToAppend.txt", isAppend);
650
+}, onErrorLoadFs);
651
+```
652
+
653
+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_.
654
+
655
+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.
656
+
657
+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.
658
+
659
+```js
660
+function writeFile(fileEntry, dataObj, isAppend) {
661
+    // Create a FileWriter object for our FileEntry (log.txt).
662
+    fileEntry.createWriter(function (fileWriter) {
663
+
664
+        fileWriter.onwriteend = function() {
665
+            console.log("Successful file read...");
666
+            readFile(fileEntry);
667
+        };
668
+
669
+        fileWriter.onerror = function (e) {
670
+            console.log("Failed file read: " + e.toString());
671
+        };
672
+
673
+        // If we are appending data to file, go to the end of the file.
674
+        if (isAppend) {
675
+            try {
676
+                fileWriter.seek(fileWriter.length);
677
+            }
678
+            catch (e) {
679
+                console.log("file doesn't exist!");
680
+            }
681
+        }
682
+        fileWriter.write(dataObj);
683
+    });
684
+}
685
+```
686
+
687
+## Store an existing binary file <a name="binaryFile"></a>
688
+
689
+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.
690
+
691
+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.
692
+
693
+```js
694
+window.requestFileSystem(window.TEMPORARY, 5 * 1024 * 1024, function (fs) {
695
+
696
+    console.log('file system open: ' + fs.name);
697
+    getSampleFile(fs.root);
698
+
699
+}, onErrorLoadFs);
700
+```
701
+
702
+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).
703
+
704
+```js
705
+function getSampleFile(dirEntry) {
706
+
707
+    var xhr = new XMLHttpRequest();
708
+    xhr.open('GET', 'http://cordova.apache.org/static/img/cordova_bot.png', true);
709
+    xhr.responseType = 'blob';
710
+
711
+    xhr.onload = function() {
712
+        if (this.status == 200) {
713
+
714
+            var blob = new Blob([this.response], { type: 'image/png' });
715
+            saveFile(dirEntry, blob, "downloadedImage.png");
716
+        }
717
+    };
718
+    xhr.send();
719
+}
720
+```
721
+>*Note* For Cordova 5 security, the preceding code requires that you add the domain name, http://cordova.apache.org, to the Content-Security-Policy <meta> element in index.html.
722
+
723
+After getting the file, copy the contents to a new file. The current DirectoryEntry object is already associated with the app cache.
724
+
725
+```js
726
+function saveFile(dirEntry, fileData, fileName) {
727
+
728
+    dirEntry.getFile(fileName, { create: true, exclusive: false }, function (fileEntry) {
729
+
730
+        writeFile(fileEntry, fileData);
731
+
732
+    }, onErrorCreateFile);
733
+}
734
+```
735
+
736
+In writeFile, you pass in the Blob object as the dataObj and you will save that in the new file.
737
+
738
+```js
739
+function writeFile(fileEntry, dataObj, isAppend) {
740
+
741
+    // Create a FileWriter object for our FileEntry (log.txt).
742
+    fileEntry.createWriter(function (fileWriter) {
743
+
744
+        fileWriter.onwriteend = function() {
745
+            console.log("Successful file write...");
746
+            if (dataObj.type == "image/png") {
747
+                readBinaryFile(fileEntry);
748
+            }
749
+            else {
750
+                readFile(fileEntry);
751
+            }
752
+        };
753
+
754
+        fileWriter.onerror = function(e) {
755
+            console.log("Failed file write: " + e.toString());
756
+        };
757
+
758
+        fileWriter.write(dataObj);
759
+    });
760
+}
761
+```
762
+
763
+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.
764
+
765
+```js
766
+function readBinaryFile(fileEntry) {
767
+
768
+    fileEntry.file(function (file) {
769
+        var reader = new FileReader();
770
+
771
+        reader.onloadend = function() {
772
+
773
+            console.log("Successful file write: " + this.result);
774
+            displayFileData(fileEntry.fullPath + ": " + this.result);
775
+
776
+            var blob = new Blob([new Uint8Array(this.result)], { type: "image/png" });
777
+            displayImage(blob);
778
+        };
779
+
780
+        reader.readAsArrayBuffer(file);
781
+
782
+    }, onErrorReadFile);
783
+}
784
+```
785
+
786
+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.
787
+
788
+```js
789
+function displayImage(blob) {
790
+
791
+    // Displays image if result is a valid DOM string for an image.
792
+    var elem = document.getElementById('imageFile');
793
+    // Note: Use window.URL.revokeObjectURL when finished with image.
794
+    elem.src = window.URL.createObjectURL(blob);
795
+}
796
+```
797
+
798
+## Display an image file <a name="displayImage"></a>
799
+
800
+To display an image using a FileEntry, you can call the `toURL` method.
801
+
802
+```js
803
+function displayImageByFileURL(fileEntry) {
804
+    var elem = document.getElementById('imageFile');
805
+    elem.src = fileEntry.toURL();
806
+}
807
+```
808
+
809
+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 <meta> element in index.html. For example, on Windows 10, you can include `ms-appdata:` in your <meta> element. Here is an example.
810
+
811
+```html
812
+<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: ms-appdata: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">
813
+```
814
+
815
+## Create Directories <a name="createDir"></a>
816
+
817
+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.
818
+
819
+This code creates the /NewDirInRoot/images folder in the application cache. For platform-specific values, look at _File System Layouts_.
820
+
821
+```js
822
+function createDirectory(rootDirEntry) {
823
+    rootDirEntry.getDirectory('NewDirInRoot', { create: true }, function (dirEntry) {
824
+        dirEntry.getDirectory('images', { create: true }, function (subDirEntry) {
825
+
826
+            createFile(subDirEntry, "fileInNewSubDir.txt");
827
+
828
+        }, onErrorGetDir);
829
+    }, onErrorGetDir);
830
+}
831
+```
832
+
833
+When creating subfolders, you need to create each folder separately as shown in the preceding code.

+ 496
- 0
node_modules/cordova-plugin-file/RELEASENOTES.md Visa fil

@@ -0,0 +1,496 @@
1
+<!--
2
+#
3
+# Licensed to the Apache Software Foundation (ASF) under one
4
+# or more contributor license agreements.  See the NOTICE file
5
+# distributed with this work for additional information
6
+# regarding copyright ownership.  The ASF licenses this file
7
+# to you under the Apache License, Version 2.0 (the
8
+# "License"); you may not use this file except in compliance
9
+# with the License.  You may obtain a copy of the License at
10
+#
11
+# http://www.apache.org/licenses/LICENSE-2.0
12
+#
13
+# Unless required by applicable law or agreed to in writing,
14
+# software distributed under the License is distributed on an
15
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16
+#  KIND, either express or implied.  See the License for the
17
+# specific language governing permissions and limitations
18
+# under the License.
19
+#
20
+-->
21
+# Release Notes
22
+
23
+### 6.0.2 (Jun 27, 2019)
24
+
25
+-   fix: manually fix line endings of some files that were using CRLF ([`e8e06c3`](https://github.com/apache/cordova-plugin-file/commit/e8e06c3))
26
+-   chore: fix repo and issue urls and license in package.json and plugin.xml ([`1bca166`](https://github.com/apache/cordova-plugin-file/commit/1bca166))
27
+-   docs: remove outdated translations ([`a898b85`](https://github.com/apache/cordova-plugin-file/commit/a898b85))
28
+-   build: add `.gitattributes` to force LF (instead of possible CRLF on Windows) ([`d691a04`](https://github.com/apache/cordova-plugin-file/commit/d691a04))
29
+-   build: add `.npmignore` to remove unneeded files from npm package ([`a255202`](https://github.com/apache/cordova-plugin-file/commit/a255202))
30
+-   ci(travis): Update Travis CI configuration for new paramedic ([#314](https://github.com/apache/cordova-plugin-file/issues/314)) ([`2b93a67`](https://github.com/apache/cordova-plugin-file/commit/2b93a67))
31
+-   fix(browser): support safari private browsing mode by using base64 text instead of blob ([#301](https://github.com/apache/cordova-plugin-file/issues/301)) ([`c609ff6`](https://github.com/apache/cordova-plugin-file/commit/c609ff6))
32
+-   chore(github): Add or update GitHub pull request and issue template ([`b762743`](https://github.com/apache/cordova-plugin-file/commit/b762743))
33
+-   fix(types): CB-13569: fix inverted LocalFileSystem enum ([#274](https://github.com/apache/cordova-plugin-file/issues/274)) ([`d135cd0`](https://github.com/apache/cordova-plugin-file/commit/d135cd0))
34
+-   docs: remove JIRA link ([`341fa9c`](https://github.com/apache/cordova-plugin-file/commit/341fa9c))
35
+-   fix(types): CB-13850: Fix spelling in typed-file: property name filesystem (wrong… ([#229](https://github.com/apache/cordova-plugin-file/issues/229)) ([`4642fde`](https://github.com/apache/cordova-plugin-file/commit/4642fde))
36
+-   fix(types): CB-13960: fix FileWriter.write argument type definition for typescript ([#231](https://github.com/apache/cordova-plugin-file/issues/231)) ([`5353b84`](https://github.com/apache/cordova-plugin-file/commit/5353b84))
37
+-   ci(travis): also accept terms for android sdk `android-27` ([`6e7871b`](https://github.com/apache/cordova-plugin-file/commit/6e7871b))
38
+-   docs: add details for `applicationDirectory` on android ([#234](https://github.com/apache/cordova-plugin-file/issues/234)) ([`c2f5216`](https://github.com/apache/cordova-plugin-file/commit/c2f5216))
39
+-   fix: require FileReader in FileWriter to fix 'write' exec not being called ([#237](https://github.com/apache/cordova-plugin-file/issues/237)) ([`4a92bbb`](https://github.com/apache/cordova-plugin-file/commit/4a92bbb))
40
+-   fix(android): CB-14181: (android) Fix bug - Cannot read property 'filesystemName' of null ([#235](https://github.com/apache/cordova-plugin-file/issues/235)) ([`cc3aedb`](https://github.com/apache/cordova-plugin-file/commit/cc3aedb))
41
+-   ci(travis): CB-13753: Add build-tools-26.0.2 to travis ([#228](https://github.com/apache/cordova-plugin-file/issues/228)) ([`d8cc0fd`](https://github.com/apache/cordova-plugin-file/commit/d8cc0fd), [`5e12b5e`](https://github.com/apache/cordova-plugin-file/commit/5e12b5e))
42
+-   chore: Fix release notes ([#227](https://github.com/apache/cordova-plugin-file/issues/227)) ([`c248827`](https://github.com/apache/cordova-plugin-file/commit/c248827))
43
+
44
+
45
+### 6.0.1 (Dec 27, 2017)
46
+* [CB-13704](https://issues.apache.org/jira/browse/CB-13704) Fix to allow 6.0.0 version install
47
+
48
+### 6.0.0 (Dec 15, 2017)
49
+* [CB-13668](https://issues.apache.org/jira/browse/CB-13668) Remove deprecated platforms
50
+
51
+### 5.0.0 (Nov 06, 2017)
52
+* [CB-13481](https://issues.apache.org/jira/browse/CB-13481) (android) Don't ask for permission to read `file:///android_asset/`
53
+* [CB-13518](https://issues.apache.org/jira/browse/CB-13518) Add 'protective' entry to `cordovaDependencies`
54
+* [CB-13472](https://issues.apache.org/jira/browse/CB-13472) (CI) Fixed Travis **Android** builds again
55
+* [CB-13294](https://issues.apache.org/jira/browse/CB-13294) Remove `cordova-plugin-compat`
56
+* fixing `README` in use of `window.resolveLocalFileSystemURL`
57
+* [CB-12895](https://issues.apache.org/jira/browse/CB-12895) setup `eslint` and took out `jshint`
58
+* [CB-13028](https://issues.apache.org/jira/browse/CB-13028) (CI) **Browser** builds on Travis
59
+* [CB-13000](https://issues.apache.org/jira/browse/CB-13000) (CI) Speed up **Android** builds
60
+* [CB-12355](https://issues.apache.org/jira/browse/CB-12355) (iOS) add desciption about the `mimeTypeForFileAtPath` method
61
+* [CB-12355](https://issues.apache.org/jira/browse/CB-12355) (iOS) fix `FileEntry.file.type`
62
+* [CB-12847](https://issues.apache.org/jira/browse/CB-12847) added `bugs` entry to `package.json`.
63
+
64
+### 4.3.3 (Apr 27, 2017)
65
+* [CB-12622](https://issues.apache.org/jira/browse/CB-12622) Added **Android 6.0** build badge to `README`
66
+* [CB-12685](https://issues.apache.org/jira/browse/CB-12685) added `package.json` to tests folder
67
+
68
+### 4.3.2 (Feb 28, 2017)
69
+* [CB-12353](https://issues.apache.org/jira/browse/CB-12353) Corrected merges usage in `plugin.xml`
70
+* [CB-12369](https://issues.apache.org/jira/browse/CB-12369) Add plugin typings from `DefinitelyTyped`
71
+* [CB-12363](https://issues.apache.org/jira/browse/CB-12363) Added build badges for **iOS 9.3** and **iOS 10.0**
72
+* [CB-12230](https://issues.apache.org/jira/browse/CB-12230) Removed **Windows 8.1** build badges
73
+
74
+### 4.3.1 (Dec 07, 2016)
75
+* [CB-12224](https://issues.apache.org/jira/browse/CB-12224) Updated version and RELEASENOTES.md for release 4.3.1
76
+* [CB-12112](https://issues.apache.org/jira/browse/CB-12112) windows: Make available to move folder trees
77
+* fix ENCODING_ERR for applicationDirectory
78
+* [CB-11848](https://issues.apache.org/jira/browse/CB-11848) windows: Remove duplicate slash after file system path
79
+* [CB-11917](https://issues.apache.org/jira/browse/CB-11917) - Remove pull request template checklist item: "iCLA has been submitted…"
80
+* [CB-11947](https://issues.apache.org/jira/browse/CB-11947) fixed typo that occurs when adding file-transfer plugin
81
+* [CB-11832](https://issues.apache.org/jira/browse/CB-11832) Incremented plugin version.
82
+
83
+### 4.3.0 (Sep 08, 2016)
84
+* [CB-11795](https://issues.apache.org/jira/browse/CB-11795) Add 'protective' entry to cordovaDependencies
85
+* Add handling for `SecurityException`
86
+* [CB-11368](https://issues.apache.org/jira/browse/CB-11368) **android**: Resolve content `URLs` produced by contacts plugin
87
+* Plugin uses `Android Log class` and not `Cordova LOG class`
88
+* [CB-11693](https://issues.apache.org/jira/browse/CB-11693) **ios**: Run copy and move operations in the background thread
89
+* [CB-11699](https://issues.apache.org/jira/browse/CB-11699) Read files as Data URLs properly
90
+* [CB-11305](https://issues.apache.org/jira/browse/CB-11305) Enable `cdvfile: assets fs root` for `DOM` requests
91
+* [CB-11385](https://issues.apache.org/jira/browse/CB-11385) android: Import java.nio.charset.Charset in LocalFileSystem class
92
+* Add badges for paramedic builds on Jenkins
93
+* [CB-11407](https://issues.apache.org/jira/browse/CB-11407) ios: added extern keyword to constants to fix phonegap-webview-ios template issue.
94
+* [CB-11385](https://issues.apache.org/jira/browse/CB-11385) **android**: Does not pass sonarqube scan
95
+* Add pull request template.
96
+* Minor edits to the `README.md`
97
+* [CB-11142](https://issues.apache.org/jira/browse/CB-11142) Fix the `NeedPermission` code for the case when external media is not mounted in Android
98
+* [CB-11003](https://issues.apache.org/jira/browse/CB-11003) Adding samples to Readme.
99
+* [CB-10996](https://issues.apache.org/jira/browse/CB-10996) Adding front matter to README.md
100
+* [CB-11115](https://issues.apache.org/jira/browse/CB-11115) **android**: Removing dependency on FileDescriptor toString in content provider tests
101
+
102
+### 4.2.0 (Apr 15, 2016)
103
+* [CB-10960](https://issues.apache.org/jira/browse/CB-10960) Uncaught `#<FileError>` in `write()` when `readyState != WRITING ?`
104
+* Replace `PermissionHelper.java` with `cordova-plugin-compat`
105
+* [CB-10977](https://issues.apache.org/jira/browse/CB-10977) **Android** Removing global state used for permission requests
106
+* CB-10798, [CB-10384](https://issues.apache.org/jira/browse/CB-10384) Fixing permissions for **Marshmallow**.
107
+* Fix test failure on **WP 8.1**
108
+* [CB-10577](https://issues.apache.org/jira/browse/CB-10577) **Windows** `resolveLocalFileSystemURL` should omit trailing slash for file
109
+* [CB-7862](https://issues.apache.org/jira/browse/CB-7862) `FileReader` reads large files in chunks with progress.
110
+* [CB-10577](https://issues.apache.org/jira/browse/CB-10577) **Android** `resolveLocalFileSystemURL` should detect directory vs file.
111
+* [CB-9753](https://issues.apache.org/jira/browse/CB-9753) index out of bounds on `requestFileSystem`.
112
+* Remove `warning` emoji, as it doesn't correctly display in the docs website: cordova.apache.org/docs/en/dev/cordova-plugin-file/index.html. This closes #166
113
+* [CB-10636](https://issues.apache.org/jira/browse/CB-10636) Add `JSHint` for plugins
114
+* [CB-10411](https://issues.apache.org/jira/browse/CB-10411) Error in `file.spec.129` of `cordova-plugin-file`
115
+
116
+### 4.1.1 (Feb 09, 2016)
117
+* Edit package.json license to match SPDX id
118
+* [CB-10419](https://issues.apache.org/jira/browse/CB-10419) cordova-plugin-file 4.0.0 error with browserify workflow
119
+
120
+### 4.1.0 (Jan 15, 2016)
121
+* added `.ratignore` file
122
+* [CB-10319](https://issues.apache.org/jira/browse/CB-10319) **android** Adding reflective helper methods for permission requests
123
+* [CB-10023](https://issues.apache.org/jira/browse/CB-10023) Fix `proxy not found error` on Chrome.
124
+* [CB-8863](https://issues.apache.org/jira/browse/CB-8863) **ios** Fix block usage of self
125
+
126
+### 4.0.0 (Nov 18, 2015)
127
+* [CB-10035](https://issues.apache.org/jira/browse/CB-10035) Updated `RELEASENOTES` to be newest to oldest
128
+* [CB-8497](https://issues.apache.org/jira/browse/CB-8497) Fix handling of file paths with `#` character
129
+* Do not inject default `AndroidPersistentFileLocation` into `config.xml`
130
+* [CB-9891](https://issues.apache.org/jira/browse/CB-9891): Fix permission errors due to `URI encoding` inconsistency on **Android**
131
+* Fixed `NullPointer Exception` in **Android 5** and above due to invalid column name on cursor
132
+* Fix default persistent file location
133
+* fix `applicationDirectory` to use `ms-appx:///`
134
+* Add **Windows** paths to `cordova.file` object
135
+* [CB-9851](https://issues.apache.org/jira/browse/CB-9851) Document `cdvfile` protocol quirk - using `cdvfile://` in the `DOM` is not supported on **Windows**
136
+* [CB-9752](https://issues.apache.org/jira/browse/CB-9752) `getDirectory` fails on valid directory with assets filesystem
137
+* [CB-7253](https://issues.apache.org/jira/browse/CB-7253) `requestFileSystem` fails when no external storage is present
138
+* Adding permissions for **Marshmallow**. Now supports **Anrdoid 6.0**
139
+* Fixing contribute link.
140
+* always use setters to fix memory issues without `ARC` for **iOS**
141
+* [CB-9331](https://issues.apache.org/jira/browse/CB-9331) `getFreeDiskSpace` **iOS**.
142
+* override `resolveLocalFileSystemURL` by `webkitResolveLocalFileSystemURL` for **browser** platform add `.project` into git ignore list
143
+* Fail with `FileError.ENCODING_ERR` on encoding exception.
144
+* [CB-9544](https://issues.apache.org/jira/browse/CB-9544) Add file plugin for **OSX**
145
+* [CB-9539](https://issues.apache.org/jira/browse/CB-9539) Fixed test failure on **Android** emulator
146
+* Added docs on `CSP` rules needed for using `cdvfile` in DOM src. This closes #120
147
+* Added `cdvfile` protocol purpose description and examples
148
+
149
+### 3.0.0 (Aug 18, 2015)
150
+* Make Android default persistent file location internal
151
+* Fixed issue with file paths not existing when using browserify
152
+* [CB-9251](https://issues.apache.org/jira/browse/CB-9251): Changed from Intents to Preferences object as per the issue
153
+* [CB-9215](https://issues.apache.org/jira/browse/CB-9215) Add cordova-plugin-file manual test for windows platform
154
+
155
+### 2.1.0 (Jun 17, 2015)
156
+* added missing license header
157
+* [CB-9128](https://issues.apache.org/jira/browse/CB-9128) cordova-plugin-file documentation translation: cordova-plugin-file
158
+* fix npm md
159
+* [CB-8844](https://issues.apache.org/jira/browse/CB-8844) Increased timeout for asset tests
160
+* Updated resolveFileSystem.js so it can be parsed by uglifyJS
161
+* [CB-8860](https://issues.apache.org/jira/browse/CB-8860) cordova-plugin-file documentation translation: cordova-plugin-file
162
+* [CB-8792](https://issues.apache.org/jira/browse/CB-8792) Fixes reading of json files using readAsText
163
+
164
+### 2.0.0 (Apr 15, 2015)
165
+* [CB-8849](https://issues.apache.org/jira/browse/CB-8849) Fixed ReadAsArrayBuffer to return ArrayBuffer and not Array on WP8
166
+* [CB-8819](https://issues.apache.org/jira/browse/CB-8819) Fixed FileReader's readAsBinaryString on wp8
167
+* [CB-8746](https://issues.apache.org/jira/browse/CB-8746) gave plugin major version bump
168
+* [CB-8683](https://issues.apache.org/jira/browse/CB-8683) android: Fix broken unit tests from plugin rename
169
+* [CB-8683](https://issues.apache.org/jira/browse/CB-8683) changed plugin-id to pacakge-name
170
+* [CB-8653](https://issues.apache.org/jira/browse/CB-8653) properly updated translated docs to use new id
171
+* [CB-8653](https://issues.apache.org/jira/browse/CB-8653) updated translated docs to use new id
172
+* Use TRAVIS_BUILD_DIR, install paramedic by npm
173
+* docs: added Windows to supported platforms
174
+* [CB-8699](https://issues.apache.org/jira/browse/CB-8699) [CB-6428](https://issues.apache.org/jira/browse/CB-6428) Fix uncompressed assets being copied as zero length files
175
+* [CB-6428](https://issues.apache.org/jira/browse/CB-6428) android: Fix assets FileEntry having size of -1
176
+* android: Move URLforFullPath into base class (and rename to localUrlforFullPath)
177
+* [CB-6428](https://issues.apache.org/jira/browse/CB-6428) Mention build-extras.gradle in README
178
+* [CB-7109](https://issues.apache.org/jira/browse/CB-7109) android: Parse arguments off of the main thread (close #97)
179
+* [CB-8695](https://issues.apache.org/jira/browse/CB-8695) ios: Fix `blob.slice()` for `asset-library` URLs (close #105)
180
+* Tweak build-extras.gradle to just read/write to main `assets/` instead of `build/`
181
+* [CB-8689](https://issues.apache.org/jira/browse/CB-8689) Fix NPE in makeEntryForNativeUri (was affecting file-transfer)
182
+* [CB-8675](https://issues.apache.org/jira/browse/CB-8675) Revert "CB-8351 ios: Use base64EncodedStringWithOptions instead of CordovaLib's class extension"
183
+* [CB-8653](https://issues.apache.org/jira/browse/CB-8653) Updated Readme
184
+* [CB-8659](https://issues.apache.org/jira/browse/CB-8659): ios: 4.0.x Compatibility: Remove use of initWebView method
185
+* Add a cache to speed up AssetFilesystem directory listings
186
+* [CB-8663](https://issues.apache.org/jira/browse/CB-8663) android: Don't notify MediaScanner of private files
187
+* Don't log stacktrace for normal exceptions (e.g. file not found)
188
+* android: Don't use LimitedInputStream when reading entire file (optimization)
189
+* [CB-6428](https://issues.apache.org/jira/browse/CB-6428) android: Add support for directory copies from assets -> filesystem
190
+* android: Add `listChildren()`: Java-consumable version of `readEntriesAtLocalURL()`
191
+* [CB-6428](https://issues.apache.org/jira/browse/CB-6428) android: Add support for file:///android_asset URLs
192
+* [CB-8642](https://issues.apache.org/jira/browse/CB-8642) android: Fix content URIs not working with resolve / copy
193
+* Tweak tests to fail if deleteEntry fails (rather than time out)
194
+* android: Ensure LocalFilesystemURL can only be created with "cdvfile" URLs
195
+* android: Move CordovaResourceApi into Filesystem base class
196
+* android: Use `CordovaResourceApi.mapUriToFile()` rather than own custom logic in ContentFilesystem
197
+* android: Use Uri.parse rather than manual parsing in resolveLocalFileSystemURI
198
+* Tweak test case that failed twice on error rather than just once
199
+* android: Delete invalid JavaDoc (lint errors)
200
+* android: Use CordovaResourceApi rather than FileHelper
201
+* [CB-8032](https://issues.apache.org/jira/browse/CB-8032) - File Plugin - Add nativeURL external method support for CDVFileSystem->makeEntryForPath:isDirectory: (closes #96)
202
+* [CB-8567](https://issues.apache.org/jira/browse/CB-8567) Integrate TravisCI
203
+* [CB-8438](https://issues.apache.org/jira/browse/CB-8438) cordova-plugin-file documentation translation: cordova-plugin-file
204
+* [CB-8538](https://issues.apache.org/jira/browse/CB-8538) Added package.json file
205
+* [CB-7956](https://issues.apache.org/jira/browse/CB-7956) Add cordova-plugin-file support for browser platform
206
+* [CB-8423](https://issues.apache.org/jira/browse/CB-8423) Corrected usage of done() in async tests
207
+* [CB-8459](https://issues.apache.org/jira/browse/CB-8459) Fixes spec 111 failure due to incorrect relative paths handling
208
+* Code cleanup, whitespace
209
+* Added nativeURL property to FileEntry, implemented readAsArrayBuffer and readAsBinaryString
210
+
211
+### 1.3.3 (Feb 04, 2015)
212
+* [CB-7927](https://issues.apache.org/jira/browse/CB-7927) Encoding data to bytes instead of chars when writing a file.
213
+* ios: Fix compile warning about implicit int conversion
214
+* [CB-8351](https://issues.apache.org/jira/browse/CB-8351) ios: Use base64EncodedStringWithOptions instead of CordovaLib's class extension
215
+* [CB-8351](https://issues.apache.org/jira/browse/CB-8351) ios: Use argumentForIndex rather than NSArray extension
216
+* [CB-8351](https://issues.apache.org/jira/browse/CB-8351) ios: Use a local copy of valueForKeyIsNumber rather than CordovaLib's version
217
+* windows: Handle url's containing absolute windows path starting with drive letter and colon (encoded as %3A) through root FS
218
+* windows: Rework to use normal url form
219
+* android: refactor: Make Filesystem base class store its own name, rootUri, and rootEntry
220
+* android: Simplify code a bit by making makeEntryForPath not throw JSONException
221
+* [CB-6431](https://issues.apache.org/jira/browse/CB-6431) android: Fix plugin breaking content: URLs
222
+* [CB-7375](https://issues.apache.org/jira/browse/CB-7375) Never create new FileSystem instances (except on windows since they don't implement requestAllFileSystems())
223
+
224
+### 1.3.2 (Dec 02, 2014)
225
+* Gets rid of thread block error in File plugin
226
+* [CB-7917](https://issues.apache.org/jira/browse/CB-7917) Made tests file.spec.114 - 116 pass for **Windows** platform
227
+* [CB-7977](https://issues.apache.org/jira/browse/CB-7977) Mention `deviceready` in plugin docs
228
+* [CB-7602](https://issues.apache.org/jira/browse/CB-7602): Fix `isCopyOnItself` logic
229
+* [CB-7700](https://issues.apache.org/jira/browse/CB-7700) cordova-plugin-file documentation translation: cordova-plugin-file
230
+* Use one proxy for both **Windows** and **Windows8** platforms
231
+* [CB-6994](https://issues.apache.org/jira/browse/CB-6994) Fixes result, returned by proxy's write method
232
+* [fxos] update `__format__` to match `pathsPrefix`
233
+* [CB-6994](https://issues.apache.org/jira/browse/CB-6994) Improves merged code to be able to write a File
234
+* Optimize `FileProxy` for **Windows** platforms
235
+* Synchronize changes with **Windows** platform
236
+* Fix function write for big files on **Windows 8**
237
+* Write file in background
238
+* [CB-7487](https://issues.apache.org/jira/browse/CB-7487) **Android** Broadcast file write This allows MTP USB shares to show the file immediately without reboot/manual refresh using 3rd party app.
239
+* [CB-7700](https://issues.apache.org/jira/browse/CB-7700) cordova-plugin-file documentation translation: cordova-plugin-file
240
+* [CB-7571](https://issues.apache.org/jira/browse/CB-7571) Bump version of nested plugin to match parent plugin
241
+
242
+### 1.3.1 (Sep 17, 2014)
243
+* [CB-7471](https://issues.apache.org/jira/browse/CB-7471) cordova-plugin-file documentation translation
244
+* [CB-7272](https://issues.apache.org/jira/browse/CB-7272) Replace confusing "r/o" abbreviation with just "r"
245
+* [CB-7423](https://issues.apache.org/jira/browse/CB-7423) encode path before attempting to resolve
246
+* [CB-7375](https://issues.apache.org/jira/browse/CB-7375) Fix the filesystem name in resolveLocalFileSystemUri
247
+* [CB-7445](https://issues.apache.org/jira/browse/CB-7445) [BlackBerry10] resolveLocalFileSystemURI - change DEFAULT_SIZE to MAX_SIZE
248
+* [CB-7458](https://issues.apache.org/jira/browse/CB-7458) [BlackBerry10] resolveLocalFileSystemURL - add filesystem property
249
+* [CB-7445](https://issues.apache.org/jira/browse/CB-7445) [BlackBerry10] Add default file system size to prevent quota exceeded error on initial install
250
+* [CB-7431](https://issues.apache.org/jira/browse/CB-7431) Avoid calling done() twice in file.spec.109 test
251
+* [CB-7413](https://issues.apache.org/jira/browse/CB-7413) Adds support of 'ms-appdata://' URIs
252
+* [CB-7422](https://issues.apache.org/jira/browse/CB-7422) [File Tests] Use proper fileSystem to create fullPath
253
+* [CB-7375](https://issues.apache.org/jira/browse/CB-7375) [Entry] get proper filesystem in Entry
254
+* Amazon related changes.
255
+* [CB-7375](https://issues.apache.org/jira/browse/CB-7375) Remove leading slash statement from condition
256
+* Refactored much of the logic in FileMetadata constructor.  Directory.size will return 0
257
+* [CB-7419](https://issues.apache.org/jira/browse/CB-7419) [WP8] Added support to get metada from dir
258
+* [CB-7418](https://issues.apache.org/jira/browse/CB-7418) [DirectoryEntry] Added fullPath variable as part of condition
259
+* [CB-7417](https://issues.apache.org/jira/browse/CB-7417) [File tests] added proper matcher to compare fullPath property
260
+* [CB-7375](https://issues.apache.org/jira/browse/CB-7375) Partial revert to resolve WP8 failures
261
+* Overwrite existing file on getFile when create is true
262
+* [CB-7375](https://issues.apache.org/jira/browse/CB-7375) [CB-6148](https://issues.apache.org/jira/browse/CB-6148): Ensure that return values from copy and move operations reference the correct filesystem
263
+* [CB-6724](https://issues.apache.org/jira/browse/CB-6724) changed style detail on documentation
264
+* Added new js files to amazon-fireos platform.
265
+* Adds Windows platform
266
+* Fixes multiple mobilespec tests errors
267
+* Removed test/tests.js module from main plugin.xml
268
+* [CB-7094](https://issues.apache.org/jira/browse/CB-7094) renamed folder to tests + added nested plugin.xml
269
+* added documentation for manual tests
270
+* [CB-6923](https://issues.apache.org/jira/browse/CB-6923) Adding support to handle relative paths
271
+* Style improvements on Manual tests
272
+* [CB-7094](https://issues.apache.org/jira/browse/CB-7094) Ported File manual tests
273
+
274
+### 1.3.0 (Aug 06, 2014)
275
+* **FFOS** Remove unsupported paths from requestAllPaths
276
+* **FFOS** Support for resolve URI, request all paths and local app directory.
277
+* [CB-4263](https://issues.apache.org/jira/browse/CB-4263) set ready state to done before onload
278
+* [CB-7167](https://issues.apache.org/jira/browse/CB-7167) [BlackBerry10] copyTo - return wrapped entry rather than native
279
+* [CB-7167](https://issues.apache.org/jira/browse/CB-7167) [BlackBerry10] Add directory support to getFileMetadata
280
+* [CB-7167](https://issues.apache.org/jira/browse/CB-7167) [BlackBerry10] Fix tests detection of blob support (window.Blob is BlobConstructor object)
281
+* [CB-7161](https://issues.apache.org/jira/browse/CB-7161) [BlackBerry10] Add file system directory paths
282
+* [CB-7093](https://issues.apache.org/jira/browse/CB-7093) Create separate plugin.xml for new-style tests
283
+* [CB-7057](https://issues.apache.org/jira/browse/CB-7057) Docs update: elaborate on what directories are for
284
+* [CB-7093](https://issues.apache.org/jira/browse/CB-7093): Undo the effects of an old bad S&R command
285
+* [CB-7093](https://issues.apache.org/jira/browse/CB-7093): Remove a bunch of unneeded log messages
286
+* [CB-7093](https://issues.apache.org/jira/browse/CB-7093): Add JS module to plugin.xml file for auto-tests
287
+* [CB-7093](https://issues.apache.org/jira/browse/CB-7093) Ported automated file tests
288
+* **WINDOWS** remove extra function closure, not    needed
289
+* **WINDOWS** remove check for undefined fail(), it is defined by the proxy and always exists
290
+* **WINDOWS** re-apply readAsBinaryString and readAsArrayBuffer
291
+* **WINDOWS** Moved similar calls to be the same calls, aliased long namespaced functions
292
+* [CB-6127](https://issues.apache.org/jira/browse/CB-6127) Updated translations for docs.
293
+* [CB-6571](https://issues.apache.org/jira/browse/CB-6571) Fix getParentForLocalURL to work correctly with directories with trailing '/' (This closes #58)
294
+* UTTypeCopyPreferredTagWithClass returns nil mimetype for css when there is no network
295
+* updated spec links in docs ( en only )
296
+* [CB-6571](https://issues.apache.org/jira/browse/CB-6571) add trailing space it is missing in DirectoryEnty constructor.
297
+* [CB-6980](https://issues.apache.org/jira/browse/CB-6980) Fixing filesystem:null property in Entry
298
+* Add win8 support for readAsBinaryString and readAsArrayBuffer
299
+* [FFOS] Update FileProxy.js
300
+* [CB-6940](https://issues.apache.org/jira/browse/CB-6940): Fixing up commit from dzeims
301
+* [CB-6940](https://issues.apache.org/jira/browse/CB-6940): Android: cleanup try/catch exception handling
302
+* [CB-6940](https://issues.apache.org/jira/browse/CB-6940): `context.getExternal*` methods return null if sdcard isn't in mounted state, causing exceptions that prevent startup from reaching readystate
303
+* Fix mis-handling of filesystem reference in Entry.moveTo ('this' used in closure).
304
+* [CB-6902](https://issues.apache.org/jira/browse/CB-6902): Use File.lastModified rather than .lastModifiedDate
305
+* [CB-6922](https://issues.apache.org/jira/browse/CB-6922): Remove unused getMetadata native code
306
+* [CB-6922](https://issues.apache.org/jira/browse/CB-6922): Use getFileMetadata consistently to get metadata
307
+* changed fullPath to self.rootDocsPath
308
+* [CB-6890](https://issues.apache.org/jira/browse/CB-6890): Fix pluginManager access for 4.0.x branch
309
+
310
+### 1.2.1
311
+* [CB-6922](https://issues.apache.org/jira/browse/CB-6922) Fix inconsistent handling of lastModifiedDate and modificationTime
312
+* [CB-285](https://issues.apache.org/jira/browse/CB-285): Document filesystem root properties
313
+
314
+### 1.2.0 (Jun 05, 2014)
315
+* [CB-6127](https://issues.apache.org/jira/browse/CB-6127) Spanish and French Translations added. Github close #31
316
+* updated this reference to window
317
+* Add missing semicolon (copy & paste error)
318
+* Fix compiler warning about symbol in interface not matching implementation
319
+* Fix sorting order in supported platforms
320
+* ubuntu: increase quota value
321
+* ubuntu: Change FS URL scheme to 'cdvfile'
322
+* ubuntu: Return size with Entry.getMetadata() method
323
+* [CB-6803](https://issues.apache.org/jira/browse/CB-6803) Add license
324
+* Initial implementation for Firefox OS
325
+* Small wording tweaks
326
+* Fixed toURL() toInternalURL() information in the doku
327
+* ios: Don't fail a write of zero-length payload.
328
+* [CB-285](https://issues.apache.org/jira/browse/CB-285) Docs for cordova.file.\*Directory properties
329
+* [CB-285](https://issues.apache.org/jira/browse/CB-285) Add cordova.file.\*Directory properties for iOS & Android
330
+* [CB-3440](https://issues.apache.org/jira/browse/CB-3440) [BlackBerry10] Proxy based implementation
331
+* Fix typo in docs "app-bundle" -> "bundle"
332
+* [CB-6583](https://issues.apache.org/jira/browse/CB-6583) ios: Fix failing to create entry when space in parent path
333
+* [CB-6571](https://issues.apache.org/jira/browse/CB-6571) android: Make DirectoryEntry.toURL() have a trailing /
334
+* [CB-6491](https://issues.apache.org/jira/browse/CB-6491) add CONTRIBUTING.md
335
+* [CB-6525](https://issues.apache.org/jira/browse/CB-6525) android, ios: Allow file: URLs in all APIs. Fixes FileTransfer.download not being called.
336
+* fix the Windows 8  implementation of the getFile method
337
+* Update File.js for typo: lastModifiedData --> lastModifiedDate (closes #38)
338
+* Add error codes.
339
+* [CB-5980](https://issues.apache.org/jira/browse/CB-5980) Updated version and RELEASENOTES.md for release 1.0.0
340
+* Add NOTICE file
341
+* [CB-6114](https://issues.apache.org/jira/browse/CB-6114) Updated version and RELEASENOTES.md for release 1.0.1
342
+* [CB-5980](https://issues.apache.org/jira/browse/CB-5980) Updated version and RELEASENOTES.md for release 1.0.0
343
+
344
+### 1.1.0 (Apr 17, 2014)
345
+* [CB-4965](https://issues.apache.org/jira/browse/CB-4965): Remove tests from file plugin
346
+* Android: Allow file:/ URLs
347
+* [CB-6422](https://issues.apache.org/jira/browse/CB-6422): [windows8] use cordova/exec/proxy
348
+* [CB-6249](https://issues.apache.org/jira/browse/CB-6249): [android] Opportunistically resolve content urls to file
349
+* [CB-6394](https://issues.apache.org/jira/browse/CB-6394): [ios, android] Add extra filesystem roots
350
+* [CB-6394](https://issues.apache.org/jira/browse/CB-6394): [ios, android] Fix file resolution for the device root case
351
+* [CB-6394](https://issues.apache.org/jira/browse/CB-6394): [ios] Return ENCODING_ERR when fs name is not valid
352
+* [CB-6393](https://issues.apache.org/jira/browse/CB-6393): Change behaviour of toURL and toNativeURL
353
+* ios: Style: plugin initialization
354
+* ios: Fix handling of file URLs with encoded spaces
355
+* Always use Android's recommended temp file location for temporary file system
356
+* [CB-6352](https://issues.apache.org/jira/browse/CB-6352): Allow FileSystem objects to be serialized to JSON
357
+* [CB-5959](https://issues.apache.org/jira/browse/CB-5959): size is explicitly 0 if not set, file.spec.46&47 are testing the type of size
358
+* [CB-6242](https://issues.apache.org/jira/browse/CB-6242): [BlackBerry10] Add deprecated version of resolveLocalFileSystemURI
359
+* [CB-6242](https://issues.apache.org/jira/browse/CB-6242): [BlackBerry10] add file:/// prefix for toURI / toURL
360
+* [CB-6242](https://issues.apache.org/jira/browse/CB-6242): [BlackBerry10] Polyfill window.requestAnimationFrame for OS < 10.2
361
+* [CB-6242](https://issues.apache.org/jira/browse/CB-6242): [BlackBerry10] Override window.resolveLocalFileSystemURL
362
+* [CB-6212](https://issues.apache.org/jira/browse/CB-6212): [iOS] fix warnings compiled under arm64 64-bit
363
+* ios: Don't cache responses from CDVFile's URLProtocol
364
+* [CB-6199](https://issues.apache.org/jira/browse/CB-6199): [iOS] Fix toNativeURL() not escaping characters properly
365
+* [CB-6148](https://issues.apache.org/jira/browse/CB-6148): Fix cross-filesystem copy and move
366
+* fixed setMetadata() to use the formatted fullPath
367
+* corrected typo which leads to a "comma expression"
368
+* [CB-4952](https://issues.apache.org/jira/browse/CB-4952): ios: Resolve symlinks in file:// URLs
369
+* Add docs about the extraFileSystems preference
370
+* [CB-6460](https://issues.apache.org/jira/browse/CB-6460): Update license headers
371
+
372
+### 1.0.1 (Feb 28, 2014)
373
+* [CB-6116](https://issues.apache.org/jira/browse/CB-6116) Fix error where resolveLocalFileSystemURL would fail
374
+* [CB-6106](https://issues.apache.org/jira/browse/CB-6106) Add support for nativeURL attribute on Entry objects
375
+* [CB-6110](https://issues.apache.org/jira/browse/CB-6110) iOS: Fix typo in filesystemPathForURL: method
376
+* Android: Use most specific FS match when resolving file: URIs
377
+* iOS: Update fileSystemURLforLocalPath: to return the most match url.
378
+* Allow third-party plugin registration, and the total count of fs type is not limited to just 4.
379
+* [CB-6097](https://issues.apache.org/jira/browse/CB-6097) Added missing files for amazon-fireos platform. Added onLoad flag to true.
380
+* [CB-6087](https://issues.apache.org/jira/browse/CB-6087) Android, iOS: Load file plugin on startup
381
+* [CB-6013](https://issues.apache.org/jira/browse/CB-6013) BlackBerry10: wrap webkit prefixed called in requestAnimationFrame
382
+* Update plugin writers' documentation
383
+* [CB-6080](https://issues.apache.org/jira/browse/CB-6080) Fix file copy when src and dst are on different local file systems
384
+* [CB-6057](https://issues.apache.org/jira/browse/CB-6057) Add methods for plugins to convert between URLs and paths
385
+* [CB-6050](https://issues.apache.org/jira/browse/CB-6050) Public method for returning a FileEntry from a device file path
386
+* [CB-2432](https://issues.apache.org/jira/browse/CB-2432) [CB-3185](https://issues.apache.org/jira/browse/CB-3185), [CB-5975](https://issues.apache.org/jira/browse/CB-5975): Fix Android handling of content:// URLs
387
+* [CB-6022](https://issues.apache.org/jira/browse/CB-6022) Add upgrade notes to doc
388
+* [CB-5233](https://issues.apache.org/jira/browse/CB-5233) Make asset-library urls work properly on iOS
389
+* [CB-6012](https://issues.apache.org/jira/browse/CB-6012) Preserve query strings on cdvfile:// URLs where necessary
390
+* [CB-6010](https://issues.apache.org/jira/browse/CB-6010) Test properly for presence of URLforFilesystemPath method
391
+* [CB-5959](https://issues.apache.org/jira/browse/CB-5959) Entry.getMetadata should return size attribute
392
+
393
+### 1.0.0 (Feb 05, 2014)
394
+* [CB-5974](https://issues.apache.org/jira/browse/CB-5974): Use safe 'Compatibilty' mode by default
395
+* [CB-5915](https://issues.apache.org/jira/browse/CB-5915): [CB-5916](https://issues.apache.org/jira/browse/CB-5916): Reorganize preference code to make defaults possible
396
+* [CB-5974](https://issues.apache.org/jira/browse/CB-5974): Android: Don't allow File operations to continue when not configured
397
+* [CB-5960](https://issues.apache.org/jira/browse/CB-5960): ios: android: Properly handle parent references in getFile/getDirectory
398
+* [ubuntu] adopt to recent changes
399
+* Add default FS root to new FS objects
400
+* [CB-5899](https://issues.apache.org/jira/browse/CB-5899): Make DirectoryReader.readEntries return properly formatted Entry objects
401
+* Add constuctor params to FileUploadResult related to [CB-2421](https://issues.apache.org/jira/browse/CB-2421)
402
+* Fill out filesystem attribute of entities returned from resolveLocalFileSystemURL
403
+* [CB-5916](https://issues.apache.org/jira/browse/CB-5916): Create documents directories if they don't exist
404
+* [CB-5915](https://issues.apache.org/jira/browse/CB-5915): Create documents directories if they don't exist
405
+* [CB-5916](https://issues.apache.org/jira/browse/CB-5916): Android: Fix unfortunate NPE in config check
406
+* [CB-5916](https://issues.apache.org/jira/browse/CB-5916): Android: Add "/files/" to persistent files path
407
+* [CB-5915](https://issues.apache.org/jira/browse/CB-5915): ios: Update config preference (and docs) to match issue
408
+* [CB-5916](https://issues.apache.org/jira/browse/CB-5916): Android: Add config preference for Android persistent storage location
409
+* iOS: Add config preference for iOS persistent storage location
410
+* iOS: Android: Allow third-party plugin registration
411
+* Android: Expose filePlugin getter so that other plugins can register filesystems
412
+* Fix typos in deprecation message
413
+* Add backwards-compatibility shim for file-transfer
414
+* Android: Allow third-party plugin registration
415
+* [CB-5810](https://issues.apache.org/jira/browse/CB-5810) [BlackBerry10] resolve local:/// paths (application assets)
416
+* [CB-5774](https://issues.apache.org/jira/browse/CB-5774): create DirectoryEntry instead of FileEntry
417
+* Initial fix for [CB-5747](https://issues.apache.org/jira/browse/CB-5747)
418
+* Change default FS URL scheme to "cdvfile"
419
+* Android: Properly format content urls
420
+* Android, iOS: Replace "filesystem" protocol string with constant
421
+* Android: Allow absolute paths on Entry.getFile / Entry.getDirectory
422
+* Android: Make clear that getFile takes a path, not just a filename
423
+* [CB-5008](https://issues.apache.org/jira/browse/CB-5008): Rename resolveLocalFileSystemURI to resolveLocalFileSystemURL; deprecate original
424
+* Remove old file reference from plugin.xml
425
+* Android: Refactor File API
426
+* [CB-4899](https://issues.apache.org/jira/browse/CB-4899) [BlackBerry10] Fix resolve directories
427
+* [CB-5602](https://issues.apache.org/jira/browse/CB-5602) Windows8. Fix File Api mobile spec tests
428
+* Android: Better support for content urls and cross-filesystem copy/move ops
429
+* [CB-5699](https://issues.apache.org/jira/browse/CB-5699) [BlackBerry10] Update resolveLocalFileSystemURI implementation
430
+* [CB-5658](https://issues.apache.org/jira/browse/CB-5658) Update license comment formatting of doc/index.md
431
+* [CB-5658](https://issues.apache.org/jira/browse/CB-5658) Add doc.index.md for File plugin.
432
+* [CB-5658](https://issues.apache.org/jira/browse/CB-5658) Delete stale snapshot of plugin docs
433
+* [CB-5403](https://issues.apache.org/jira/browse/CB-5403): Backwards-compatibility with file:// urls where possible
434
+* [CB-5407](https://issues.apache.org/jira/browse/CB-5407): Fixes for ContentFilesystem
435
+* Android: Add method for testing backwards-compatibility of filetransfer plugin
436
+* iOS: Add method for testing backwards-compatiblity of filetransfer plugin
437
+* Android: Updates to allow FileTransfer to continue to work
438
+* Android: Clean up unclosed file objects
439
+* [CB-5407](https://issues.apache.org/jira/browse/CB-5407): Cleanup
440
+* [CB-5407](https://issues.apache.org/jira/browse/CB-5407): Add new Android source files to plugin.xml
441
+* [CB-5407](https://issues.apache.org/jira/browse/CB-5407): Move read, write and truncate methods into modules
442
+* [CB-5407](https://issues.apache.org/jira/browse/CB-5407): Move copy/move methods into FS modules
443
+* [CB-5407](https://issues.apache.org/jira/browse/CB-5407): Move getParent into FS modules
444
+* [CB-5407](https://issues.apache.org/jira/browse/CB-5407): Move getmetadata methods into FS modules
445
+* [CB-5407](https://issues.apache.org/jira/browse/CB-5407): Move readdir methods into FS modules
446
+* [CB-5407](https://issues.apache.org/jira/browse/CB-5407): Move remove methods into FS modules
447
+* [CB-5407](https://issues.apache.org/jira/browse/CB-5407): Move getFile into FS modules
448
+* [CB-5407](https://issues.apache.org/jira/browse/CB-5407): Start refactoring android code: Modular filesystems, rfs, rlfsurl
449
+* [CB-5407](https://issues.apache.org/jira/browse/CB-5407): Update android JS to use FS urls
450
+* [CB-5405](https://issues.apache.org/jira/browse/CB-5405): Use URL formatting for Entry.toURL
451
+* [CB-5532](https://issues.apache.org/jira/browse/CB-5532) Fix
452
+* Log file path for File exceptions.
453
+* Partial fix for iOS File compatibility with previous fileTransfer plugin
454
+* [CB-5532](https://issues.apache.org/jira/browse/CB-5532) WP8. Add binary data support to FileWriter
455
+* [CB-5531](https://issues.apache.org/jira/browse/CB-5531) WP8. File Api readAsText incorrectly handles position args
456
+* Added ubuntu platform support
457
+* Added amazon-fireos platform support
458
+* [CB-5118](https://issues.apache.org/jira/browse/CB-5118) [BlackBerry10] Add check for undefined error handler
459
+* [CB-5406](https://issues.apache.org/jira/browse/CB-5406): Extend public API for dependent plugins
460
+* [CB-5403](https://issues.apache.org/jira/browse/CB-5403): Bump File plugin major version
461
+* [CB-5406](https://issues.apache.org/jira/browse/CB-5406): Split iOS file plugin into modules
462
+* [CB-5406](https://issues.apache.org/jira/browse/CB-5406): Factor out filesystem providers in iOS
463
+* [CB-5408](https://issues.apache.org/jira/browse/CB-5408): Add handler for filesystem:// urls
464
+* [CB-5406](https://issues.apache.org/jira/browse/CB-5406): Update iOS native code to use filesystem URLs internally
465
+* [CB-5405](https://issues.apache.org/jira/browse/CB-5405): Update JS code to use URLs exclusively
466
+* [CB-4816](https://issues.apache.org/jira/browse/CB-4816) Fix file creation outside sandbox for BB10
467
+
468
+### 0.2.5 (Oct 28, 2013)
469
+* [CB-5129](https://issues.apache.org/jira/browse/CB-5129): Add a consistent filesystem attribute to FileEntry and DirectoryEntry objects
470
+* [CB-5128](https://issues.apache.org/jira/browse/CB-5128): added repo + issue tag to plugin.xml for file plugin
471
+* [CB-5015](https://issues.apache.org/jira/browse/CB-5015) [BlackBerry10] Add missing dependency for File.slice
472
+* [CB-5010](https://issues.apache.org/jira/browse/CB-5010) Incremented plugin version on dev branch.
473
+
474
+### 0.2.4 (Oct 9, 2013)
475
+* [CB-5020](https://issues.apache.org/jira/browse/CB-5020) - File plugin should execute on a separate thread
476
+* [CB-4915](https://issues.apache.org/jira/browse/CB-4915) Incremented plugin version on dev branch.
477
+* [CB-4504](https://issues.apache.org/jira/browse/CB-4504): Updating FileUtils.java to compensate for Java porting failures in the Android SDK. This fails because Java knows nothing about android_asset not being an actual filesystem
478
+
479
+### 0.2.3 (Sept 25, 2013)
480
+* [CB-4889](https://issues.apache.org/jira/browse/CB-4889) bumping&resetting version
481
+* [CB-4903](https://issues.apache.org/jira/browse/CB-4903) File Plugin not loading Windows8
482
+* [CB-4903](https://issues.apache.org/jira/browse/CB-4903) File Plugin not loading Windows8
483
+* [CB-4889](https://issues.apache.org/jira/browse/CB-4889) renaming references
484
+* [CB-4889](https://issues.apache.org/jira/browse/CB-4889) renaming org.apache.cordova.core.file to org.apache.cordova.file
485
+* Rename CHANGELOG.md -> RELEASENOTES.md
486
+* [CB-4771](https://issues.apache.org/jira/browse/CB-4771) Expose TEMPORARY and PERSISTENT constants on window.
487
+* Fix compiler/lint warnings
488
+* [CB-4764](https://issues.apache.org/jira/browse/CB-4764) Move DirectoryManager.java into file plugin
489
+* [CB-4763](https://issues.apache.org/jira/browse/CB-4763) Copy FileHelper.java into the plugin.
490
+* [CB-2901](https://issues.apache.org/jira/browse/CB-2901) [BlackBerry10] Automatically unsandbox filesystem if path is not in app sandbox
491
+* [CB-4752](https://issues.apache.org/jira/browse/CB-4752) Incremented plugin version on dev branch.
492
+
493
+### 0.2.1 (Sept 5, 2013)
494
+* [CB-4656](https://issues.apache.org/jira/browse/CB-4656) Don't add newlines in data urls within readAsDataUrl.
495
+* [CB-4514](https://issues.apache.org/jira/browse/CB-4514) Making DirectoryCopy Recursive
496
+* [iOS] Simplify the code in resolveLocalFileSystemURI

+ 120
- 0
node_modules/cordova-plugin-file/doc/plugins.md Visa fil

@@ -0,0 +1,120 @@
1
+<!---
2
+    Licensed to the Apache Software Foundation (ASF) under one
3
+    or more contributor license agreements.  See the NOTICE file
4
+    distributed with this work for additional information
5
+    regarding copyright ownership.  The ASF licenses this file
6
+    to you under the Apache License, Version 2.0 (the
7
+    "License"); you may not use this file except in compliance
8
+    with the License.  You may obtain a copy of the License at
9
+
10
+      http://www.apache.org/licenses/LICENSE-2.0
11
+
12
+    Unless required by applicable law or agreed to in writing,
13
+    software distributed under the License is distributed on an
14
+    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15
+    KIND, either express or implied.  See the License for the
16
+    specific language governing permissions and limitations
17
+    under the License.
18
+-->
19
+
20
+Notes for plugin developers
21
+===========================
22
+
23
+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.
24
+
25
+Working with Cordova file system URLs
26
+-------------------------------------
27
+
28
+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. 
29
+
30
+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.
31
+
32
+### Converting cdvfile:// URLs to fileystem paths
33
+
34
+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.
35
+
36
+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.
37
+
38
+#### Android
39
+
40
+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:
41
+
42
+    // webView is a member of the Plugin class
43
+    CordovaResourceApi resourceApi = webView.getResourceApi();
44
+
45
+    // Obtain a file:/// URL representing this file on the device,
46
+    // or the same URL unchanged if it cannot be mapped to a file
47
+    Uri fileURL = resourceApi.remapUri(Uri.parse(cdvfileURL));
48
+
49
+It is also possible to use the File plugin directly:
50
+
51
+    import org.apache.cordova.file.FileUtils;
52
+    import org.apache.cordova.file.FileSystem;
53
+    import java.net.MalformedURLException;
54
+
55
+    // Get the File plugin from the plugin manager
56
+    FileUtils filePlugin = (FileUtils)webView.pluginManager.getPlugin("File");
57
+
58
+    // Given a URL, get a path for it
59
+    try {
60
+        String path = filePlugin.filesystemPathForURL(cdvfileURL);
61
+    } catch (MalformedURLException e) {
62
+        // The filesystem url wasn't recognized
63
+    }
64
+
65
+To convert from a path to a `cdvfile://` URL:
66
+
67
+    import org.apache.cordova.file.LocalFilesystemURL;
68
+
69
+    // Get a LocalFilesystemURL object for a device path,
70
+    // or null if it cannot be represented as a cdvfile URL.
71
+    LocalFilesystemURL url = filePlugin.filesystemURLforLocalPath(path);
72
+    // Get the string representation of the URL object
73
+    String cdvfileURL = url.toString();
74
+
75
+If your plugin creates a file, and you want to return a FileEntry object for it, use the File plugin:
76
+
77
+    // Return a JSON structure suitable for returning to JavaScript,
78
+    // or null if this file is not representable as a cdvfile URL.
79
+    JSONObject entry = filePlugin.getEntryForFile(file);
80
+
81
+#### iOS
82
+
83
+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.
84
+
85
+    // Get a CDVFilesystem URL object from a URL string
86
+    CDVFilesystemURL* url = [CDVFilesystemURL fileSystemURLWithString:cdvfileURL];
87
+    // Get a path for the URL object, or nil if it cannot be mapped to a file
88
+    NSString* path = [filePlugin filesystemPathForURL:url];
89
+    
90
+
91
+    // Get a CDVFilesystem URL object for a device path, or
92
+    // nil if it cannot be represented as a cdvfile URL.
93
+    CDVFilesystemURL* url = [filePlugin fileSystemURLforLocalPath:path];
94
+    // Get the string representation of the URL object
95
+    NSString* cdvfileURL = [url absoluteString];
96
+
97
+If your plugin creates a file, and you want to return a FileEntry object for it, use the File plugin:
98
+
99
+    // Get a CDVFilesystem URL object for a device path, or
100
+    // nil if it cannot be represented as a cdvfile URL.
101
+    CDVFilesystemURL* url = [filePlugin fileSystemURLforLocalPath:path];
102
+    // Get a structure to return to JavaScript
103
+    NSDictionary* entry = [filePlugin makeEntryForLocalURL:url]
104
+
105
+#### JavaScript
106
+
107
+In JavaScript, to get a `cdvfile://` URL from a FileEntry or DirectoryEntry object, simply call `.toURL()` on it:
108
+
109
+    var cdvfileURL = entry.toURL();
110
+
111
+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:
112
+
113
+    // create appropriate Entry object
114
+    var entry;
115
+    if (entryStruct.isDirectory) {
116
+        entry = new DirectoryEntry(entryStruct.name, entryStruct.fullPath, new FileSystem(entryStruct.filesystemName));
117
+    } else {
118
+        entry = new FileEntry(entryStruct.name, entryStruct.fullPath, new FileSystem(entryStruct.filesystemName));
119
+    }
120
+

+ 87
- 0
node_modules/cordova-plugin-file/package.json Visa fil

@@ -0,0 +1,87 @@
1
+{
2
+  "_from": "cordova-plugin-file@>=2.0.0",
3
+  "_id": "cordova-plugin-file@6.0.2",
4
+  "_inBundle": false,
5
+  "_integrity": "sha512-m7cughw327CjONN/qjzsTpSesLaeybksQh420/gRuSXJX5Zt9NfgsSbqqKDon6jnQ9Mm7h7imgyO2uJ34XMBtA==",
6
+  "_location": "/cordova-plugin-file",
7
+  "_phantomChildren": {},
8
+  "_requested": {
9
+    "type": "range",
10
+    "registry": true,
11
+    "raw": "cordova-plugin-file@>=2.0.0",
12
+    "name": "cordova-plugin-file",
13
+    "escapedName": "cordova-plugin-file",
14
+    "rawSpec": ">=2.0.0",
15
+    "saveSpec": null,
16
+    "fetchSpec": ">=2.0.0"
17
+  },
18
+  "_requiredBy": [
19
+    "#DEV:/",
20
+    "#USER"
21
+  ],
22
+  "_resolved": "https://registry.npmjs.org/cordova-plugin-file/-/cordova-plugin-file-6.0.2.tgz",
23
+  "_shasum": "f3911479f8357e9aacb5576674f8d95b31a1fb20",
24
+  "_spec": "cordova-plugin-file@>=2.0.0",
25
+  "_where": "C:\\Users\\Chuch\\Documents\\Cordova\\artesanias",
26
+  "author": {
27
+    "name": "Apache Software Foundation"
28
+  },
29
+  "bugs": {
30
+    "url": "https://github.com/apache/cordova-plugin-file/issues"
31
+  },
32
+  "bundleDependencies": false,
33
+  "cordova": {
34
+    "id": "cordova-plugin-file",
35
+    "platforms": [
36
+      "android",
37
+      "browser",
38
+      "ios",
39
+      "osx",
40
+      "windows"
41
+    ]
42
+  },
43
+  "deprecated": false,
44
+  "description": "Cordova File Plugin",
45
+  "devDependencies": {
46
+    "eslint": "^3.19.0",
47
+    "eslint-config-semistandard": "^11.0.0",
48
+    "eslint-config-standard": "^10.2.1",
49
+    "eslint-plugin-import": "^2.3.0",
50
+    "eslint-plugin-node": "^5.0.0",
51
+    "eslint-plugin-promise": "^3.5.0",
52
+    "eslint-plugin-standard": "^3.0.1"
53
+  },
54
+  "engines": {
55
+    "cordovaDependencies": {
56
+      "5.0.0": {
57
+        "cordova-android": ">=6.3.0"
58
+      },
59
+      "7.0.0": {
60
+        "cordova": ">100"
61
+      }
62
+    }
63
+  },
64
+  "homepage": "https://github.com/apache/cordova-plugin-file#readme",
65
+  "keywords": [
66
+    "cordova",
67
+    "file",
68
+    "ecosystem:cordova",
69
+    "cordova-android",
70
+    "cordova-browser",
71
+    "cordova-ios",
72
+    "cordova-osx",
73
+    "cordova-windows"
74
+  ],
75
+  "license": "Apache-2.0",
76
+  "name": "cordova-plugin-file",
77
+  "repository": {
78
+    "type": "git",
79
+    "url": "git+https://github.com/apache/cordova-plugin-file.git"
80
+  },
81
+  "scripts": {
82
+    "eslint": "node node_modules/eslint/bin/eslint www && node node_modules/eslint/bin/eslint src && node node_modules/eslint/bin/eslint tests",
83
+    "test": "npm run eslint"
84
+  },
85
+  "types": "./types/index.d.ts",
86
+  "version": "6.0.2"
87
+}

+ 260
- 0
node_modules/cordova-plugin-file/plugin.xml Visa fil

@@ -0,0 +1,260 @@
1
+<?xml version="1.0" encoding="UTF-8"?>
2
+<!--
3
+  Licensed to the Apache Software Foundation (ASF) under one
4
+  or more contributor license agreements.  See the NOTICE file
5
+  distributed with this work for additional information
6
+  regarding copyright ownership.  The ASF licenses this file
7
+  to you under the Apache License, Version 2.0 (the
8
+  "License"); you may not use this file except in compliance
9
+  with the License.  You may obtain a copy of the License at
10
+
11
+    http://www.apache.org/licenses/LICENSE-2.0
12
+
13
+  Unless required by applicable law or agreed to in writing,
14
+  software distributed under the License is distributed on an
15
+  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16
+  KIND, either express or implied.  See the License for the
17
+  specific language governing permissions and limitations
18
+  under the License.
19
+-->
20
+
21
+<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0"
22
+xmlns:android="http://schemas.android.com/apk/res/android"
23
+           id="cordova-plugin-file"
24
+      version="6.0.2">
25
+    <name>File</name>
26
+    <description>Cordova File Plugin</description>
27
+    <license>Apache 2.0</license>
28
+    <keywords>cordova,file</keywords>
29
+    <repo>https://github.com/apache/cordova-plugin-file</repo>
30
+    <issue>https://github.com/apache/cordova-plugin-file/issues</issue>
31
+
32
+    <engines>
33
+        <engine name="cordova-android" version=">=6.3.0" />
34
+    </engines>
35
+
36
+    <js-module src="www/DirectoryEntry.js" name="DirectoryEntry">
37
+        <clobbers target="window.DirectoryEntry" />
38
+    </js-module>
39
+
40
+    <js-module src="www/DirectoryReader.js" name="DirectoryReader">
41
+        <clobbers target="window.DirectoryReader" />
42
+    </js-module>
43
+
44
+    <js-module src="www/Entry.js" name="Entry">
45
+        <clobbers target="window.Entry" />
46
+    </js-module>
47
+
48
+    <js-module src="www/File.js" name="File">
49
+        <clobbers target="window.File" />
50
+    </js-module>
51
+
52
+    <js-module src="www/FileEntry.js" name="FileEntry">
53
+        <clobbers target="window.FileEntry" />
54
+    </js-module>
55
+
56
+    <js-module src="www/FileError.js" name="FileError">
57
+        <clobbers target="window.FileError" />
58
+    </js-module>
59
+
60
+    <js-module src="www/FileReader.js" name="FileReader">
61
+        <clobbers target="window.FileReader" />
62
+    </js-module>
63
+
64
+    <js-module src="www/FileSystem.js" name="FileSystem">
65
+        <clobbers target="window.FileSystem" />
66
+    </js-module>
67
+
68
+    <js-module src="www/FileUploadOptions.js" name="FileUploadOptions">
69
+        <clobbers target="window.FileUploadOptions" />
70
+    </js-module>
71
+
72
+    <js-module src="www/FileUploadResult.js" name="FileUploadResult">
73
+        <clobbers target="window.FileUploadResult" />
74
+    </js-module>
75
+
76
+    <js-module src="www/FileWriter.js" name="FileWriter">
77
+        <clobbers target="window.FileWriter" />
78
+    </js-module>
79
+
80
+    <js-module src="www/Flags.js" name="Flags">
81
+        <clobbers target="window.Flags" />
82
+    </js-module>
83
+
84
+    <js-module src="www/LocalFileSystem.js" name="LocalFileSystem">
85
+        <!-- Non-standards way -->
86
+        <clobbers target="window.LocalFileSystem" />
87
+        <!-- Standards-compliant way -->
88
+        <merges target="window" />
89
+    </js-module>
90
+
91
+    <js-module src="www/Metadata.js" name="Metadata">
92
+        <clobbers target="window.Metadata" />
93
+    </js-module>
94
+
95
+    <js-module src="www/ProgressEvent.js" name="ProgressEvent">
96
+        <clobbers target="window.ProgressEvent" />
97
+    </js-module>
98
+
99
+    <js-module src="www/fileSystems.js" name="fileSystems" />
100
+
101
+    <js-module src="www/requestFileSystem.js" name="requestFileSystem">
102
+        <clobbers target="window.requestFileSystem" />
103
+    </js-module>
104
+
105
+    <js-module src="www/resolveLocalFileSystemURI.js" name="resolveLocalFileSystemURI">
106
+        <merges target="window" />
107
+    </js-module>
108
+
109
+    <!-- Required for browserify: we always link module below as there is conditional reference
110
+    to this module from requestFileSystem and resolveLocalFileSystemURI modules. -->
111
+    <js-module src="www/browser/isChrome.js" name="isChrome">
112
+        <runs />
113
+    </js-module>
114
+
115
+    <!-- android -->
116
+    <platform name="android">
117
+        <info>
118
+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.
119
+
120
+If this is a new application no changes are required.
121
+
122
+If this is an update to an existing application that did not specify an "AndroidPersistentFileLocation" you may need to add:
123
+
124
+      "&lt;preference name="AndroidPersistentFileLocation" value="Compatibility" /&gt;"
125
+
126
+to config.xml in order for the application to find previously stored files.
127
+        </info>
128
+        <config-file target="res/xml/config.xml" parent="/*">
129
+            <feature name="File" >
130
+                <param name="android-package" value="org.apache.cordova.file.FileUtils"/>
131
+                <param name="onload" value="true" />
132
+            </feature>
133
+            <allow-navigation href="cdvfile:*" />
134
+        </config-file>
135
+
136
+        <config-file target="AndroidManifest.xml" parent="/*">
137
+            <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
138
+        </config-file>
139
+
140
+        <source-file src="src/android/EncodingException.java" target-dir="src/org/apache/cordova/file" />
141
+        <source-file src="src/android/FileExistsException.java" target-dir="src/org/apache/cordova/file" />
142
+        <source-file src="src/android/InvalidModificationException.java" target-dir="src/org/apache/cordova/file" />
143
+        <source-file src="src/android/NoModificationAllowedException.java" target-dir="src/org/apache/cordova/file" />
144
+        <source-file src="src/android/TypeMismatchException.java" target-dir="src/org/apache/cordova/file" />
145
+        <source-file src="src/android/FileUtils.java" target-dir="src/org/apache/cordova/file" />
146
+        <source-file src="src/android/DirectoryManager.java" target-dir="src/org/apache/cordova/file" />
147
+        <source-file src="src/android/LocalFilesystemURL.java" target-dir="src/org/apache/cordova/file" />
148
+        <source-file src="src/android/Filesystem.java" target-dir="src/org/apache/cordova/file" />
149
+        <source-file src="src/android/LocalFilesystem.java" target-dir="src/org/apache/cordova/file" />
150
+        <source-file src="src/android/ContentFilesystem.java" target-dir="src/org/apache/cordova/file" />
151
+        <source-file src="src/android/AssetFilesystem.java" target-dir="src/org/apache/cordova/file" />
152
+        <source-file src="src/android/PendingRequests.java" target-dir="src/org/apache/cordova/file" />
153
+
154
+        <!-- android specific file apis -->
155
+        <js-module src="www/android/FileSystem.js" name="androidFileSystem">
156
+            <merges target="FileSystem" />
157
+        </js-module>
158
+        <js-module src="www/fileSystems-roots.js" name="fileSystems-roots">
159
+            <runs/>
160
+        </js-module>
161
+        <js-module src="www/fileSystemPaths.js" name="fileSystemPaths">
162
+            <merges target="cordova" />
163
+            <runs/>
164
+        </js-module>
165
+    </platform>
166
+
167
+    <!-- ios -->
168
+    <platform name="ios">
169
+        <config-file target="config.xml" parent="/*">
170
+            <feature name="File">
171
+                <param name="ios-package" value="CDVFile" />
172
+                <param name="onload" value="true" />
173
+            </feature>
174
+        </config-file>
175
+        <header-file src="src/ios/CDVFile.h" />
176
+        <source-file src="src/ios/CDVFile.m" />
177
+        <header-file src="src/ios/CDVLocalFilesystem.h" />
178
+        <source-file src="src/ios/CDVLocalFilesystem.m" />
179
+        <header-file src="src/ios/CDVAssetLibraryFilesystem.h" />
180
+        <source-file src="src/ios/CDVAssetLibraryFilesystem.m" />
181
+
182
+        <!-- ios specific file apis -->
183
+        <js-module src="www/ios/FileSystem.js" name="iosFileSystem">
184
+            <merges target="FileSystem" />
185
+        </js-module>
186
+
187
+        <js-module src="www/fileSystems-roots.js" name="fileSystems-roots">
188
+            <runs/>
189
+        </js-module>
190
+
191
+        <js-module src="www/fileSystemPaths.js" name="fileSystemPaths">
192
+            <merges target="cordova" />
193
+            <runs/>
194
+        </js-module>
195
+
196
+        <framework src="AssetsLibrary.framework" />
197
+        <framework src="MobileCoreServices.framework" />
198
+    </platform>
199
+
200
+    <!-- osx -->
201
+    <platform name="osx">
202
+        <config-file target="config.xml" parent="/*">
203
+            <feature name="File">
204
+                <param name="ios-package" value="CDVFile" />
205
+                <param name="onload" value="true" />
206
+            </feature>
207
+        </config-file>
208
+        <header-file src="src/osx/CDVFile.h" />
209
+        <source-file src="src/osx/CDVFile.m" />
210
+        <header-file src="src/osx/CDVLocalFilesystem.h" />
211
+        <source-file src="src/osx/CDVLocalFilesystem.m" />
212
+
213
+        <!-- osx specific file apis -->
214
+        <js-module src="www/osx/FileSystem.js" name="osxFileSystem">
215
+            <merges target="FileSystem" />
216
+        </js-module>
217
+
218
+        <js-module src="www/fileSystems-roots.js" name="fileSystems-roots">
219
+            <runs/>
220
+        </js-module>
221
+
222
+        <js-module src="www/fileSystemPaths.js" name="fileSystemPaths">
223
+            <merges target="cordova" />
224
+            <runs/>
225
+        </js-module>
226
+    </platform>
227
+
228
+    <!-- windows -->
229
+    <platform name="windows">
230
+        <js-module src="src/windows/FileProxy.js" name="FileProxy">
231
+            <runs />
232
+        </js-module>
233
+
234
+        <js-module src="www/fileSystemPaths.js" name="fileSystemPaths">
235
+            <merges target="cordova" />
236
+            <runs/>
237
+        </js-module>
238
+    </platform>
239
+
240
+    <platform name="browser">
241
+        <!-- File for Chrome -->
242
+        <js-module src="www/browser/Preparing.js" name="Preparing">
243
+            <runs />
244
+        </js-module>
245
+
246
+        <js-module src="src/browser/FileProxy.js" name="browserFileProxy">
247
+            <runs />
248
+        </js-module>
249
+
250
+        <js-module src="www/fileSystemPaths.js" name="fileSystemPaths">
251
+            <merges target="cordova" />
252
+            <runs />
253
+        </js-module>
254
+
255
+        <js-module src="www/browser/FileSystem.js" name="firefoxFileSystem">
256
+            <merges target="window.FileSystem" />
257
+        </js-module>
258
+    </platform>
259
+
260
+</plugin>

+ 294
- 0
node_modules/cordova-plugin-file/src/android/AssetFilesystem.java Visa fil

@@ -0,0 +1,294 @@
1
+/*
2
+       Licensed to the Apache Software Foundation (ASF) under one
3
+       or more contributor license agreements.  See the NOTICE file
4
+       distributed with this work for additional information
5
+       regarding copyright ownership.  The ASF licenses this file
6
+       to you under the Apache License, Version 2.0 (the
7
+       "License"); you may not use this file except in compliance
8
+       with the License.  You may obtain a copy of the License at
9
+
10
+         http://www.apache.org/licenses/LICENSE-2.0
11
+
12
+       Unless required by applicable law or agreed to in writing,
13
+       software distributed under the License is distributed on an
14
+       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15
+       KIND, either express or implied.  See the License for the
16
+       specific language governing permissions and limitations
17
+       under the License.
18
+ */
19
+package org.apache.cordova.file;
20
+
21
+import android.content.res.AssetManager;
22
+import android.net.Uri;
23
+
24
+import org.apache.cordova.CordovaResourceApi;
25
+import org.apache.cordova.LOG;
26
+import org.json.JSONArray;
27
+import org.json.JSONException;
28
+import org.json.JSONObject;
29
+
30
+import java.io.File;
31
+import java.io.FileNotFoundException;
32
+import java.io.IOException;
33
+import java.io.ObjectInputStream;
34
+import java.util.HashMap;
35
+import java.util.Map;
36
+
37
+public class AssetFilesystem extends Filesystem {
38
+
39
+    private final AssetManager assetManager;
40
+
41
+    // A custom gradle hook creates the cdvasset.manifest file, which speeds up asset listing a tonne.
42
+    // See: http://stackoverflow.com/questions/16911558/android-assetmanager-list-incredibly-slow
43
+    private static Object listCacheLock = new Object();
44
+    private static boolean listCacheFromFile;
45
+    private static Map<String, String[]> listCache;
46
+    private static Map<String, Long> lengthCache;
47
+
48
+    private static final String LOG_TAG = "AssetFilesystem";
49
+
50
+    private void lazyInitCaches() {
51
+        synchronized (listCacheLock) {
52
+            if (listCache == null) {
53
+                ObjectInputStream ois = null;
54
+                try {
55
+                    ois = new ObjectInputStream(assetManager.open("cdvasset.manifest"));
56
+                    listCache = (Map<String, String[]>) ois.readObject();
57
+                    lengthCache = (Map<String, Long>) ois.readObject();
58
+                    listCacheFromFile = true;
59
+                } catch (ClassNotFoundException e) {
60
+                    e.printStackTrace();
61
+                } catch (IOException e) {
62
+                    // Asset manifest won't exist if the gradle hook isn't set up correctly.
63
+                } finally {
64
+                    if (ois != null) {
65
+                        try {
66
+                            ois.close();
67
+                        } catch (IOException e) {
68
+                            LOG.d(LOG_TAG, e.getLocalizedMessage());
69
+                        }
70
+                    }
71
+                }
72
+                if (listCache == null) {
73
+                    LOG.w("AssetFilesystem", "Asset manifest not found. Recursive copies and directory listing will be slow.");
74
+                    listCache = new HashMap<String, String[]>();
75
+                }
76
+            }
77
+        }
78
+    }
79
+
80
+    private String[] listAssets(String assetPath) throws IOException {
81
+        if (assetPath.startsWith("/")) {
82
+            assetPath = assetPath.substring(1);
83
+        }
84
+        if (assetPath.endsWith("/")) {
85
+            assetPath = assetPath.substring(0, assetPath.length() - 1);
86
+        }
87
+        lazyInitCaches();
88
+        String[] ret = listCache.get(assetPath);
89
+        if (ret == null) {
90
+            if (listCacheFromFile) {
91
+                ret = new String[0];
92
+            } else {
93
+                ret = assetManager.list(assetPath);
94
+                listCache.put(assetPath, ret);
95
+            }
96
+        }
97
+        return ret;
98
+    }
99
+
100
+    private long getAssetSize(String assetPath) throws FileNotFoundException {
101
+        if (assetPath.startsWith("/")) {
102
+            assetPath = assetPath.substring(1);
103
+        }
104
+        lazyInitCaches();
105
+        if (lengthCache != null) {
106
+            Long ret = lengthCache.get(assetPath);
107
+            if (ret == null) {
108
+                throw new FileNotFoundException("Asset not found: " + assetPath);
109
+            }
110
+            return ret;
111
+        }
112
+        CordovaResourceApi.OpenForReadResult offr = null;
113
+        try {
114
+            offr = resourceApi.openForRead(nativeUriForFullPath(assetPath));
115
+            long length = offr.length;
116
+            if (length < 0) {
117
+                // available() doesn't always yield the file size, but for assets it does.
118
+                length = offr.inputStream.available();
119
+            }
120
+            return length;
121
+        } catch (IOException e) {
122
+            FileNotFoundException fnfe = new FileNotFoundException("File not found: " + assetPath);
123
+            fnfe.initCause(e);
124
+            throw fnfe;
125
+        } finally {
126
+            if (offr != null) {
127
+                try {
128
+                    offr.inputStream.close();
129
+                } catch (IOException e) {
130
+                    LOG.d(LOG_TAG, e.getLocalizedMessage());
131
+                }
132
+            }
133
+        }
134
+    }
135
+
136
+    public AssetFilesystem(AssetManager assetManager, CordovaResourceApi resourceApi) {
137
+        super(Uri.parse("file:///android_asset/"), "assets", resourceApi);
138
+        this.assetManager = assetManager;
139
+	}
140
+
141
+    @Override
142
+    public Uri toNativeUri(LocalFilesystemURL inputURL) {
143
+        return nativeUriForFullPath(inputURL.path);
144
+    }
145
+
146
+    @Override
147
+    public LocalFilesystemURL toLocalUri(Uri inputURL) {
148
+        if (!"file".equals(inputURL.getScheme())) {
149
+            return null;
150
+        }
151
+        File f = new File(inputURL.getPath());
152
+        // Removes and duplicate /s (e.g. file:///a//b/c)
153
+        Uri resolvedUri = Uri.fromFile(f);
154
+        String rootUriNoTrailingSlash = rootUri.getEncodedPath();
155
+        rootUriNoTrailingSlash = rootUriNoTrailingSlash.substring(0, rootUriNoTrailingSlash.length() - 1);
156
+        if (!resolvedUri.getEncodedPath().startsWith(rootUriNoTrailingSlash)) {
157
+            return null;
158
+        }
159
+        String subPath = resolvedUri.getEncodedPath().substring(rootUriNoTrailingSlash.length());
160
+        // Strip leading slash
161
+        if (!subPath.isEmpty()) {
162
+            subPath = subPath.substring(1);
163
+        }
164
+        Uri.Builder b = new Uri.Builder()
165
+            .scheme(LocalFilesystemURL.FILESYSTEM_PROTOCOL)
166
+            .authority("localhost")
167
+            .path(name);
168
+        if (!subPath.isEmpty()) {
169
+            b.appendEncodedPath(subPath);
170
+        }
171
+        if (isDirectory(subPath) || inputURL.getPath().endsWith("/")) {
172
+            // Add trailing / for directories.
173
+            b.appendEncodedPath("");
174
+        }
175
+        return LocalFilesystemURL.parse(b.build());
176
+    }
177
+
178
+    private boolean isDirectory(String assetPath) {
179
+        try {
180
+            return listAssets(assetPath).length != 0;
181
+        } catch (IOException e) {
182
+            return false;
183
+        }
184
+    }
185
+
186
+    @Override
187
+    public LocalFilesystemURL[] listChildren(LocalFilesystemURL inputURL) throws FileNotFoundException {
188
+        String pathNoSlashes = inputURL.path.substring(1);
189
+        if (pathNoSlashes.endsWith("/")) {
190
+            pathNoSlashes = pathNoSlashes.substring(0, pathNoSlashes.length() - 1);
191
+        }
192
+
193
+        String[] files;
194
+        try {
195
+            files = listAssets(pathNoSlashes);
196
+        } catch (IOException e) {
197
+            FileNotFoundException fnfe = new FileNotFoundException();
198
+            fnfe.initCause(e);
199
+            throw fnfe;
200
+        }
201
+
202
+        LocalFilesystemURL[] entries = new LocalFilesystemURL[files.length];
203
+        for (int i = 0; i < files.length; ++i) {
204
+            entries[i] = localUrlforFullPath(new File(inputURL.path, files[i]).getPath());
205
+        }
206
+        return entries;
207
+	}
208
+
209
+    @Override
210
+    public JSONObject getFileForLocalURL(LocalFilesystemURL inputURL,
211
+                                         String path, JSONObject options, boolean directory)
212
+            throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException {
213
+        if (options != null && options.optBoolean("create")) {
214
+            throw new UnsupportedOperationException("Assets are read-only");
215
+        }
216
+
217
+        // Check whether the supplied path is absolute or relative
218
+        if (directory && !path.endsWith("/")) {
219
+            path += "/";
220
+        }
221
+
222
+        LocalFilesystemURL requestedURL;
223
+        if (path.startsWith("/")) {
224
+            requestedURL = localUrlforFullPath(normalizePath(path));
225
+        } else {
226
+            requestedURL = localUrlforFullPath(normalizePath(inputURL.path + "/" + path));
227
+        }
228
+
229
+        // Throws a FileNotFoundException if it doesn't exist.
230
+        getFileMetadataForLocalURL(requestedURL);
231
+
232
+        boolean isDir = isDirectory(requestedURL.path);
233
+        if (directory && !isDir) {
234
+            throw new TypeMismatchException("path doesn't exist or is file");
235
+        } else if (!directory && isDir) {
236
+            throw new TypeMismatchException("path doesn't exist or is directory");
237
+        }
238
+
239
+        // Return the directory
240
+        return makeEntryForURL(requestedURL);
241
+    }
242
+
243
+    @Override
244
+	public JSONObject getFileMetadataForLocalURL(LocalFilesystemURL inputURL) throws FileNotFoundException {
245
+        JSONObject metadata = new JSONObject();
246
+        long size = inputURL.isDirectory ? 0 : getAssetSize(inputURL.path);
247
+        try {
248
+        	metadata.put("size", size);
249
+        	metadata.put("type", inputURL.isDirectory ? "text/directory" : resourceApi.getMimeType(toNativeUri(inputURL)));
250
+        	metadata.put("name", new File(inputURL.path).getName());
251
+        	metadata.put("fullPath", inputURL.path);
252
+        	metadata.put("lastModifiedDate", 0);
253
+        } catch (JSONException e) {
254
+            return null;
255
+        }
256
+        return metadata;
257
+	}
258
+
259
+	@Override
260
+	public boolean canRemoveFileAtLocalURL(LocalFilesystemURL inputURL) {
261
+		return false;
262
+	}
263
+
264
+    @Override
265
+    long writeToFileAtURL(LocalFilesystemURL inputURL, String data, int offset, boolean isBinary) throws NoModificationAllowedException, IOException {
266
+        throw new NoModificationAllowedException("Assets are read-only");
267
+    }
268
+
269
+    @Override
270
+    long truncateFileAtURL(LocalFilesystemURL inputURL, long size) throws IOException, NoModificationAllowedException {
271
+        throw new NoModificationAllowedException("Assets are read-only");
272
+    }
273
+
274
+    @Override
275
+    String filesystemPathForURL(LocalFilesystemURL url) {
276
+        return new File(rootUri.getPath(), url.path).toString();
277
+    }
278
+
279
+    @Override
280
+    LocalFilesystemURL URLforFilesystemPath(String path) {
281
+        return null;
282
+    }
283
+
284
+    @Override
285
+    boolean removeFileAtLocalURL(LocalFilesystemURL inputURL) throws InvalidModificationException, NoModificationAllowedException {
286
+        throw new NoModificationAllowedException("Assets are read-only");
287
+    }
288
+
289
+    @Override
290
+    boolean recursiveRemoveFileAtLocalURL(LocalFilesystemURL inputURL) throws NoModificationAllowedException {
291
+        throw new NoModificationAllowedException("Assets are read-only");
292
+    }
293
+
294
+}

+ 223
- 0
node_modules/cordova-plugin-file/src/android/ContentFilesystem.java Visa fil

@@ -0,0 +1,223 @@
1
+/*
2
+       Licensed to the Apache Software Foundation (ASF) under one
3
+       or more contributor license agreements.  See the NOTICE file
4
+       distributed with this work for additional information
5
+       regarding copyright ownership.  The ASF licenses this file
6
+       to you under the Apache License, Version 2.0 (the
7
+       "License"); you may not use this file except in compliance
8
+       with the License.  You may obtain a copy of the License at
9
+
10
+         http://www.apache.org/licenses/LICENSE-2.0
11
+
12
+       Unless required by applicable law or agreed to in writing,
13
+       software distributed under the License is distributed on an
14
+       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15
+       KIND, either express or implied.  See the License for the
16
+       specific language governing permissions and limitations
17
+       under the License.
18
+ */
19
+package org.apache.cordova.file;
20
+
21
+import android.content.ContentResolver;
22
+import android.content.Context;
23
+import android.database.Cursor;
24
+import android.net.Uri;
25
+import android.provider.DocumentsContract;
26
+import android.provider.MediaStore;
27
+import android.provider.OpenableColumns;
28
+import java.io.File;
29
+import java.io.FileNotFoundException;
30
+import java.io.IOException;
31
+import org.apache.cordova.CordovaResourceApi;
32
+import org.json.JSONException;
33
+import org.json.JSONObject;
34
+
35
+public class ContentFilesystem extends Filesystem {
36
+
37
+    private final Context context;
38
+
39
+	public ContentFilesystem(Context context, CordovaResourceApi resourceApi) {
40
+		super(Uri.parse("content://"), "content", resourceApi);
41
+        this.context = context;
42
+	}
43
+
44
+    @Override
45
+    public Uri toNativeUri(LocalFilesystemURL inputURL) {
46
+        String authorityAndPath = inputURL.uri.getEncodedPath().substring(this.name.length() + 2);
47
+        if (authorityAndPath.length() < 2) {
48
+            return null;
49
+        }
50
+        String ret = "content://" + authorityAndPath;
51
+        String query = inputURL.uri.getEncodedQuery();
52
+        if (query != null) {
53
+            ret += '?' + query;
54
+        }
55
+        String frag = inputURL.uri.getEncodedFragment();
56
+        if (frag != null) {
57
+            ret += '#' + frag;
58
+        }
59
+        return Uri.parse(ret);
60
+    }
61
+
62
+    @Override
63
+    public LocalFilesystemURL toLocalUri(Uri inputURL) {
64
+        if (!"content".equals(inputURL.getScheme())) {
65
+            return null;
66
+        }
67
+        String subPath = inputURL.getEncodedPath();
68
+        if (subPath.length() > 0) {
69
+            subPath = subPath.substring(1);
70
+        }
71
+        Uri.Builder b = new Uri.Builder()
72
+            .scheme(LocalFilesystemURL.FILESYSTEM_PROTOCOL)
73
+            .authority("localhost")
74
+            .path(name)
75
+            .appendPath(inputURL.getAuthority());
76
+        if (subPath.length() > 0) {
77
+            b.appendEncodedPath(subPath);
78
+        }
79
+        Uri localUri = b.encodedQuery(inputURL.getEncodedQuery())
80
+            .encodedFragment(inputURL.getEncodedFragment())
81
+            .build();
82
+        return LocalFilesystemURL.parse(localUri);
83
+    }
84
+
85
+    @Override
86
+	public JSONObject getFileForLocalURL(LocalFilesystemURL inputURL,
87
+			String fileName, JSONObject options, boolean directory) throws IOException, TypeMismatchException, JSONException {
88
+        throw new UnsupportedOperationException("getFile() not supported for content:. Use resolveLocalFileSystemURL instead.");
89
+	}
90
+
91
+	@Override
92
+	public boolean removeFileAtLocalURL(LocalFilesystemURL inputURL)
93
+			throws NoModificationAllowedException {
94
+        Uri contentUri = toNativeUri(inputURL);
95
+		try {
96
+            context.getContentResolver().delete(contentUri, null, null);
97
+		} catch (UnsupportedOperationException t) {
98
+			// Was seeing this on the File mobile-spec tests on 4.0.3 x86 emulator.
99
+			// The ContentResolver applies only when the file was registered in the
100
+			// first case, which is generally only the case with images.
101
+            NoModificationAllowedException nmae = new NoModificationAllowedException("Deleting not supported for content uri: " + contentUri);
102
+            nmae.initCause(t);
103
+            throw nmae;
104
+		}
105
+        return true;
106
+	}
107
+
108
+	@Override
109
+	public boolean recursiveRemoveFileAtLocalURL(LocalFilesystemURL inputURL)
110
+			throws NoModificationAllowedException {
111
+		throw new NoModificationAllowedException("Cannot remove content url");
112
+	}
113
+
114
+    @Override
115
+    public LocalFilesystemURL[] listChildren(LocalFilesystemURL inputURL) throws FileNotFoundException {
116
+        throw new UnsupportedOperationException("readEntriesAtLocalURL() not supported for content:. Use resolveLocalFileSystemURL instead.");
117
+    }
118
+
119
+	@Override
120
+	public JSONObject getFileMetadataForLocalURL(LocalFilesystemURL inputURL) throws FileNotFoundException {
121
+        long size = -1;
122
+        long lastModified = 0;
123
+        Uri nativeUri = toNativeUri(inputURL);
124
+        String mimeType = resourceApi.getMimeType(nativeUri);
125
+        Cursor cursor = openCursorForURL(nativeUri);
126
+        try {
127
+            if (cursor != null && cursor.moveToFirst()) {
128
+                Long sizeForCursor = resourceSizeForCursor(cursor);
129
+                if (sizeForCursor != null) {
130
+                    size = sizeForCursor.longValue();
131
+                }
132
+                Long modified = lastModifiedDateForCursor(cursor);
133
+                if (modified != null)
134
+                    lastModified = modified.longValue();
135
+            } else {
136
+                // Some content providers don't support cursors at all!
137
+                CordovaResourceApi.OpenForReadResult offr = resourceApi.openForRead(nativeUri);
138
+                size = offr.length;
139
+            }
140
+        } catch (IOException e) {
141
+            FileNotFoundException fnfe = new FileNotFoundException();
142
+            fnfe.initCause(e);
143
+            throw fnfe;
144
+        } finally {
145
+        	if (cursor != null)
146
+        		cursor.close();
147
+        }
148
+
149
+        JSONObject metadata = new JSONObject();
150
+        try {
151
+        	metadata.put("size", size);
152
+        	metadata.put("type", mimeType);
153
+        	metadata.put("name", name);
154
+        	metadata.put("fullPath", inputURL.path);
155
+        	metadata.put("lastModifiedDate", lastModified);
156
+        } catch (JSONException e) {
157
+        	return null;
158
+        }
159
+        return metadata;
160
+	}
161
+
162
+	@Override
163
+	public long writeToFileAtURL(LocalFilesystemURL inputURL, String data,
164
+			int offset, boolean isBinary) throws NoModificationAllowedException {
165
+        throw new NoModificationAllowedException("Couldn't write to file given its content URI");
166
+    }
167
+	@Override
168
+	public long truncateFileAtURL(LocalFilesystemURL inputURL, long size)
169
+			throws NoModificationAllowedException {
170
+        throw new NoModificationAllowedException("Couldn't truncate file given its content URI");
171
+	}
172
+
173
+	protected Cursor openCursorForURL(Uri nativeUri) {
174
+        ContentResolver contentResolver = context.getContentResolver();
175
+        try {
176
+            return contentResolver.query(nativeUri, null, null, null, null);
177
+        } catch (UnsupportedOperationException e) {
178
+            return null;
179
+        }
180
+	}
181
+
182
+	private Long resourceSizeForCursor(Cursor cursor) {
183
+        int columnIndex = cursor.getColumnIndex(OpenableColumns.SIZE);
184
+        if (columnIndex != -1) {
185
+            String sizeStr = cursor.getString(columnIndex);
186
+            if (sizeStr != null) {
187
+            	return Long.parseLong(sizeStr);
188
+            }
189
+        }
190
+        return null;
191
+	}
192
+	
193
+	protected Long lastModifiedDateForCursor(Cursor cursor) {
194
+        int columnIndex = cursor.getColumnIndex(MediaStore.MediaColumns.DATE_MODIFIED);
195
+        if (columnIndex == -1) {
196
+            columnIndex = cursor.getColumnIndex(DocumentsContract.Document.COLUMN_LAST_MODIFIED);
197
+        }
198
+        if (columnIndex != -1) {
199
+            String dateStr = cursor.getString(columnIndex);
200
+            if (dateStr != null) {
201
+                return Long.parseLong(dateStr);
202
+            }
203
+        }
204
+        return null;
205
+	}
206
+
207
+    @Override
208
+    public String filesystemPathForURL(LocalFilesystemURL url) {
209
+        File f = resourceApi.mapUriToFile(toNativeUri(url));
210
+        return f == null ? null : f.getAbsolutePath();
211
+    }
212
+
213
+	@Override
214
+	public LocalFilesystemURL URLforFilesystemPath(String path) {
215
+		// Returns null as we don't support reverse mapping back to content:// URLs
216
+		return null;
217
+	}
218
+
219
+	@Override
220
+	public boolean canRemoveFileAtLocalURL(LocalFilesystemURL inputURL) {
221
+		return true;
222
+	}
223
+}

+ 134
- 0
node_modules/cordova-plugin-file/src/android/DirectoryManager.java Visa fil

@@ -0,0 +1,134 @@
1
+/*
2
+       Licensed to the Apache Software Foundation (ASF) under one
3
+       or more contributor license agreements.  See the NOTICE file
4
+       distributed with this work for additional information
5
+       regarding copyright ownership.  The ASF licenses this file
6
+       to you under the Apache License, Version 2.0 (the
7
+       "License"); you may not use this file except in compliance
8
+       with the License.  You may obtain a copy of the License at
9
+
10
+         http://www.apache.org/licenses/LICENSE-2.0
11
+
12
+       Unless required by applicable law or agreed to in writing,
13
+       software distributed under the License is distributed on an
14
+       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15
+       KIND, either express or implied.  See the License for the
16
+       specific language governing permissions and limitations
17
+       under the License.
18
+*/
19
+package org.apache.cordova.file;
20
+
21
+import android.os.Environment;
22
+import android.os.StatFs;
23
+
24
+import java.io.File;
25
+
26
+/**
27
+ * This class provides file directory utilities.
28
+ * All file operations are performed on the SD card.
29
+ *
30
+ * It is used by the FileUtils class.
31
+ */
32
+public class DirectoryManager {
33
+
34
+    @SuppressWarnings("unused")
35
+    private static final String LOG_TAG = "DirectoryManager";
36
+
37
+    /**
38
+     * Determine if a file or directory exists.
39
+     * @param name				The name of the file to check.
40
+     * @return					T=exists, F=not found
41
+     */
42
+    public static boolean testFileExists(String name) {
43
+        boolean status;
44
+
45
+        // If SD card exists
46
+        if ((testSaveLocationExists()) && (!name.equals(""))) {
47
+            File path = Environment.getExternalStorageDirectory();
48
+            File newPath = constructFilePaths(path.toString(), name);
49
+            status = newPath.exists();
50
+        }
51
+        // If no SD card
52
+        else {
53
+            status = false;
54
+        }
55
+        return status;
56
+    }
57
+
58
+    /**
59
+     * Get the free space in external storage
60
+     *
61
+     * @return 		Size in KB or -1 if not available
62
+     */
63
+    public static long getFreeExternalStorageSpace() {
64
+        String status = Environment.getExternalStorageState();
65
+        long freeSpaceInBytes = 0;
66
+
67
+        // Check if external storage exists
68
+        if (status.equals(Environment.MEDIA_MOUNTED)) {
69
+            freeSpaceInBytes = getFreeSpaceInBytes(Environment.getExternalStorageDirectory().getPath());
70
+        } else {
71
+            // If no external storage then return -1
72
+            return -1;
73
+        }
74
+
75
+        return freeSpaceInBytes / 1024;
76
+    }
77
+
78
+    /**
79
+     * Given a path return the number of free bytes in the filesystem containing the path.
80
+     *
81
+     * @param path to the file system
82
+     * @return free space in bytes
83
+     */
84
+    public static long getFreeSpaceInBytes(String path) {
85
+        try {
86
+            StatFs stat = new StatFs(path);
87
+            long blockSize = stat.getBlockSize();
88
+            long availableBlocks = stat.getAvailableBlocks();
89
+            return availableBlocks * blockSize;
90
+        } catch (IllegalArgumentException e) {
91
+            // The path was invalid. Just return 0 free bytes.
92
+            return 0;
93
+        }
94
+    }
95
+
96
+    /**
97
+     * Determine if SD card exists.
98
+     *
99
+     * @return				T=exists, F=not found
100
+     */
101
+    public static boolean testSaveLocationExists() {
102
+        String sDCardStatus = Environment.getExternalStorageState();
103
+        boolean status;
104
+
105
+        // If SD card is mounted
106
+        if (sDCardStatus.equals(Environment.MEDIA_MOUNTED)) {
107
+            status = true;
108
+        }
109
+
110
+        // If no SD card
111
+        else {
112
+            status = false;
113
+        }
114
+        return status;
115
+    }
116
+
117
+    /**
118
+     * Create a new file object from two file paths.
119
+     *
120
+     * @param file1			Base file path
121
+     * @param file2			Remaining file path
122
+     * @return				File object
123
+     */
124
+    private static File constructFilePaths (String file1, String file2) {
125
+        File newPath;
126
+        if (file2.startsWith(file1)) {
127
+            newPath = new File(file2);
128
+        }
129
+        else {
130
+            newPath = new File(file1 + "/" + file2);
131
+        }
132
+        return newPath;
133
+    }
134
+}

+ 29
- 0
node_modules/cordova-plugin-file/src/android/EncodingException.java Visa fil

@@ -0,0 +1,29 @@
1
+/*
2
+       Licensed to the Apache Software Foundation (ASF) under one
3
+       or more contributor license agreements.  See the NOTICE file
4
+       distributed with this work for additional information
5
+       regarding copyright ownership.  The ASF licenses this file
6
+       to you under the Apache License, Version 2.0 (the
7
+       "License"); you may not use this file except in compliance
8
+       with the License.  You may obtain a copy of the License at
9
+
10
+         http://www.apache.org/licenses/LICENSE-2.0
11
+
12
+       Unless required by applicable law or agreed to in writing,
13
+       software distributed under the License is distributed on an
14
+       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15
+       KIND, either express or implied.  See the License for the
16
+       specific language governing permissions and limitations
17
+       under the License.
18
+*/
19
+
20
+package org.apache.cordova.file;
21
+
22
+@SuppressWarnings("serial")
23
+public class EncodingException extends Exception {
24
+
25
+    public EncodingException(String message) {
26
+        super(message);
27
+    }
28
+
29
+}

+ 29
- 0
node_modules/cordova-plugin-file/src/android/FileExistsException.java Visa fil

@@ -0,0 +1,29 @@
1
+/*
2
+       Licensed to the Apache Software Foundation (ASF) under one
3
+       or more contributor license agreements.  See the NOTICE file
4
+       distributed with this work for additional information
5
+       regarding copyright ownership.  The ASF licenses this file
6
+       to you under the Apache License, Version 2.0 (the
7
+       "License"); you may not use this file except in compliance
8
+       with the License.  You may obtain a copy of the License at
9
+
10
+         http://www.apache.org/licenses/LICENSE-2.0
11
+
12
+       Unless required by applicable law or agreed to in writing,
13
+       software distributed under the License is distributed on an
14
+       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15
+       KIND, either express or implied.  See the License for the
16
+       specific language governing permissions and limitations
17
+       under the License.
18
+*/
19
+
20
+package org.apache.cordova.file;
21
+
22
+@SuppressWarnings("serial")
23
+public class FileExistsException extends Exception {
24
+
25
+    public FileExistsException(String msg) {
26
+        super(msg);
27
+    }
28
+
29
+}

+ 1225
- 0
node_modules/cordova-plugin-file/src/android/FileUtils.java
Filskillnaden har hållits tillbaka eftersom den är för stor
Visa fil


+ 331
- 0
node_modules/cordova-plugin-file/src/android/Filesystem.java Visa fil

@@ -0,0 +1,331 @@
1
+/*
2
+       Licensed to the Apache Software Foundation (ASF) under one
3
+       or more contributor license agreements.  See the NOTICE file
4
+       distributed with this work for additional information
5
+       regarding copyright ownership.  The ASF licenses this file
6
+       to you under the Apache License, Version 2.0 (the
7
+       "License"); you may not use this file except in compliance
8
+       with the License.  You may obtain a copy of the License at
9
+
10
+         http://www.apache.org/licenses/LICENSE-2.0
11
+
12
+       Unless required by applicable law or agreed to in writing,
13
+       software distributed under the License is distributed on an
14
+       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15
+       KIND, either express or implied.  See the License for the
16
+       specific language governing permissions and limitations
17
+       under the License.
18
+ */
19
+package org.apache.cordova.file;
20
+
21
+import android.net.Uri;
22
+
23
+import java.io.File;
24
+import java.io.FileNotFoundException;
25
+import java.io.FilterInputStream;
26
+import java.io.IOException;
27
+import java.io.InputStream;
28
+import java.io.OutputStream;
29
+import java.util.ArrayList;
30
+import java.util.Arrays;
31
+
32
+import org.apache.cordova.CordovaResourceApi;
33
+import org.json.JSONArray;
34
+import org.json.JSONException;
35
+import org.json.JSONObject;
36
+
37
+public abstract class Filesystem {
38
+
39
+    protected final Uri rootUri;
40
+    protected final CordovaResourceApi resourceApi;
41
+    public final String name;
42
+    private JSONObject rootEntry;
43
+
44
+    public Filesystem(Uri rootUri, String name, CordovaResourceApi resourceApi) {
45
+        this.rootUri = rootUri;
46
+        this.name = name;
47
+        this.resourceApi = resourceApi;
48
+    }
49
+
50
+    public interface ReadFileCallback {
51
+		public void handleData(InputStream inputStream, String contentType) throws IOException;
52
+	}
53
+
54
+    public static JSONObject makeEntryForURL(LocalFilesystemURL inputURL, Uri nativeURL) {
55
+        try {
56
+            String path = inputURL.path;
57
+            int end = path.endsWith("/") ? 1 : 0;
58
+            String[] parts = path.substring(0, path.length() - end).split("/+");
59
+            String fileName = parts[parts.length - 1];
60
+
61
+            JSONObject entry = new JSONObject();
62
+            entry.put("isFile", !inputURL.isDirectory);
63
+            entry.put("isDirectory", inputURL.isDirectory);
64
+            entry.put("name", fileName);
65
+            entry.put("fullPath", path);
66
+            // The file system can't be specified, as it would lead to an infinite loop,
67
+            // but the filesystem name can be.
68
+            entry.put("filesystemName", inputURL.fsName);
69
+            // Backwards compatibility
70
+            entry.put("filesystem", "temporary".equals(inputURL.fsName) ? 0 : 1);
71
+
72
+            String nativeUrlStr = nativeURL.toString();
73
+            if (inputURL.isDirectory && !nativeUrlStr.endsWith("/")) {
74
+                nativeUrlStr += "/";
75
+            }
76
+            entry.put("nativeURL", nativeUrlStr);
77
+            return entry;
78
+        } catch (JSONException e) {
79
+            e.printStackTrace();
80
+            throw new RuntimeException(e);
81
+        }
82
+    }
83
+
84
+    public JSONObject makeEntryForURL(LocalFilesystemURL inputURL) {
85
+        Uri nativeUri = toNativeUri(inputURL);
86
+        return nativeUri == null ? null : makeEntryForURL(inputURL, nativeUri);
87
+    }
88
+
89
+    public JSONObject makeEntryForNativeUri(Uri nativeUri) {
90
+        LocalFilesystemURL inputUrl = toLocalUri(nativeUri);
91
+        return inputUrl == null ? null : makeEntryForURL(inputUrl, nativeUri);
92
+    }
93
+
94
+    public JSONObject getEntryForLocalURL(LocalFilesystemURL inputURL) throws IOException {
95
+        return makeEntryForURL(inputURL);
96
+    }
97
+
98
+    public JSONObject makeEntryForFile(File file) {
99
+        return makeEntryForNativeUri(Uri.fromFile(file));
100
+    }
101
+
102
+    abstract JSONObject getFileForLocalURL(LocalFilesystemURL inputURL, String path,
103
+			JSONObject options, boolean directory) throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException;
104
+
105
+	abstract boolean removeFileAtLocalURL(LocalFilesystemURL inputURL) throws InvalidModificationException, NoModificationAllowedException;
106
+
107
+	abstract boolean recursiveRemoveFileAtLocalURL(LocalFilesystemURL inputURL) throws FileExistsException, NoModificationAllowedException;
108
+
109
+	abstract LocalFilesystemURL[] listChildren(LocalFilesystemURL inputURL) throws FileNotFoundException;
110
+
111
+    public final JSONArray readEntriesAtLocalURL(LocalFilesystemURL inputURL) throws FileNotFoundException {
112
+        LocalFilesystemURL[] children = listChildren(inputURL);
113
+        JSONArray entries = new JSONArray();
114
+        if (children != null) {
115
+            for (LocalFilesystemURL url : children) {
116
+                entries.put(makeEntryForURL(url));
117
+            }
118
+        }
119
+        return entries;
120
+    }
121
+
122
+	abstract JSONObject getFileMetadataForLocalURL(LocalFilesystemURL inputURL) throws FileNotFoundException;
123
+
124
+    public Uri getRootUri() {
125
+        return rootUri;
126
+    }
127
+
128
+    public boolean exists(LocalFilesystemURL inputURL) {
129
+        try {
130
+            getFileMetadataForLocalURL(inputURL);
131
+        } catch (FileNotFoundException e) {
132
+            return false;
133
+        }
134
+        return true;
135
+    }
136
+
137
+    public Uri nativeUriForFullPath(String fullPath) {
138
+        Uri ret = null;
139
+        if (fullPath != null) {
140
+            String encodedPath = Uri.fromFile(new File(fullPath)).getEncodedPath();
141
+            if (encodedPath.startsWith("/")) {
142
+                encodedPath = encodedPath.substring(1);
143
+            }
144
+            ret = rootUri.buildUpon().appendEncodedPath(encodedPath).build();
145
+        }
146
+        return ret;
147
+    }
148
+
149
+    public LocalFilesystemURL localUrlforFullPath(String fullPath) {
150
+        Uri nativeUri = nativeUriForFullPath(fullPath);
151
+        if (nativeUri != null) {
152
+            return toLocalUri(nativeUri);
153
+        }
154
+        return null;
155
+    }
156
+
157
+    /**
158
+     * Removes multiple repeated //s, and collapses processes ../s.
159
+     */
160
+    protected static String normalizePath(String rawPath) {
161
+        // If this is an absolute path, trim the leading "/" and replace it later
162
+        boolean isAbsolutePath = rawPath.startsWith("/");
163
+        if (isAbsolutePath) {
164
+            rawPath = rawPath.replaceFirst("/+", "");
165
+        }
166
+        ArrayList<String> components = new ArrayList<String>(Arrays.asList(rawPath.split("/+")));
167
+        for (int index = 0; index < components.size(); ++index) {
168
+            if (components.get(index).equals("..")) {
169
+                components.remove(index);
170
+                if (index > 0) {
171
+                    components.remove(index-1);
172
+                    --index;
173
+                }
174
+            }
175
+        }
176
+        StringBuilder normalizedPath = new StringBuilder();
177
+        for(String component: components) {
178
+            normalizedPath.append("/");
179
+            normalizedPath.append(component);
180
+        }
181
+        if (isAbsolutePath) {
182
+            return normalizedPath.toString();
183
+        } else {
184
+            return normalizedPath.toString().substring(1);
185
+        }
186
+    }
187
+
188
+    /**
189
+     * Gets the free space in bytes available on this filesystem.
190
+     * Subclasses may override this method to return nonzero free space.
191
+     */
192
+    public long getFreeSpaceInBytes() {
193
+        return 0;
194
+    }
195
+
196
+    public abstract Uri toNativeUri(LocalFilesystemURL inputURL);
197
+    public abstract LocalFilesystemURL toLocalUri(Uri inputURL);
198
+
199
+    public JSONObject getRootEntry() {
200
+        if (rootEntry == null) {
201
+            rootEntry = makeEntryForNativeUri(rootUri);
202
+        }
203
+        return rootEntry;
204
+    }
205
+
206
+	public JSONObject getParentForLocalURL(LocalFilesystemURL inputURL) throws IOException {
207
+        Uri parentUri = inputURL.uri;
208
+        String parentPath = new File(inputURL.uri.getPath()).getParent();
209
+        if (!"/".equals(parentPath)) {
210
+            parentUri = inputURL.uri.buildUpon().path(parentPath + '/').build();
211
+		}
212
+		return getEntryForLocalURL(LocalFilesystemURL.parse(parentUri));
213
+	}
214
+
215
+    protected LocalFilesystemURL makeDestinationURL(String newName, LocalFilesystemURL srcURL, LocalFilesystemURL destURL, boolean isDirectory) {
216
+        // I know this looks weird but it is to work around a JSON bug.
217
+        if ("null".equals(newName) || "".equals(newName)) {
218
+            newName = srcURL.uri.getLastPathSegment();;
219
+        }
220
+
221
+        String newDest = destURL.uri.toString();
222
+        if (newDest.endsWith("/")) {
223
+            newDest = newDest + newName;
224
+        } else {
225
+            newDest = newDest + "/" + newName;
226
+        }
227
+        if (isDirectory) {
228
+            newDest += '/';
229
+        }
230
+        return LocalFilesystemURL.parse(newDest);
231
+    }
232
+
233
+	/* Read a source URL (possibly from a different filesystem, srcFs,) and copy it to
234
+	 * the destination URL on this filesystem, optionally with a new filename.
235
+	 * If move is true, then this method should either perform an atomic move operation
236
+	 * or remove the source file when finished.
237
+	 */
238
+    public JSONObject copyFileToURL(LocalFilesystemURL destURL, String newName,
239
+            Filesystem srcFs, LocalFilesystemURL srcURL, boolean move) throws IOException, InvalidModificationException, JSONException, NoModificationAllowedException, FileExistsException {
240
+        // First, check to see that we can do it
241
+        if (move && !srcFs.canRemoveFileAtLocalURL(srcURL)) {
242
+            throw new NoModificationAllowedException("Cannot move file at source URL");
243
+        }
244
+        final LocalFilesystemURL destination = makeDestinationURL(newName, srcURL, destURL, srcURL.isDirectory);
245
+
246
+        Uri srcNativeUri = srcFs.toNativeUri(srcURL);
247
+
248
+        CordovaResourceApi.OpenForReadResult ofrr = resourceApi.openForRead(srcNativeUri);
249
+        OutputStream os = null;
250
+        try {
251
+            os = getOutputStreamForURL(destination);
252
+        } catch (IOException e) {
253
+            ofrr.inputStream.close();
254
+            throw e;
255
+        }
256
+        // Closes streams.
257
+        resourceApi.copyResource(ofrr, os);
258
+
259
+        if (move) {
260
+            srcFs.removeFileAtLocalURL(srcURL);
261
+        }
262
+        return getEntryForLocalURL(destination);
263
+    }
264
+
265
+    public OutputStream getOutputStreamForURL(LocalFilesystemURL inputURL) throws IOException {
266
+        return resourceApi.openOutputStream(toNativeUri(inputURL));
267
+    }
268
+
269
+    public void readFileAtURL(LocalFilesystemURL inputURL, long start, long end,
270
+                              ReadFileCallback readFileCallback) throws IOException {
271
+        CordovaResourceApi.OpenForReadResult ofrr = resourceApi.openForRead(toNativeUri(inputURL));
272
+        if (end < 0) {
273
+            end = ofrr.length;
274
+        }
275
+        long numBytesToRead = end - start;
276
+        try {
277
+            if (start > 0) {
278
+                ofrr.inputStream.skip(start);
279
+            }
280
+            InputStream inputStream = ofrr.inputStream;
281
+            if (end < ofrr.length) {
282
+                inputStream = new LimitedInputStream(inputStream, numBytesToRead);
283
+            }
284
+            readFileCallback.handleData(inputStream, ofrr.mimeType);
285
+        } finally {
286
+            ofrr.inputStream.close();
287
+        }
288
+    }
289
+
290
+	abstract long writeToFileAtURL(LocalFilesystemURL inputURL, String data, int offset,
291
+			boolean isBinary) throws NoModificationAllowedException, IOException;
292
+
293
+	abstract long truncateFileAtURL(LocalFilesystemURL inputURL, long size)
294
+			throws IOException, NoModificationAllowedException;
295
+
296
+	// This method should return null if filesystem urls cannot be mapped to paths
297
+	abstract String filesystemPathForURL(LocalFilesystemURL url);
298
+
299
+	abstract LocalFilesystemURL URLforFilesystemPath(String path);
300
+
301
+	abstract boolean canRemoveFileAtLocalURL(LocalFilesystemURL inputURL);
302
+
303
+    protected class LimitedInputStream extends FilterInputStream {
304
+        long numBytesToRead;
305
+        public LimitedInputStream(InputStream in, long numBytesToRead) {
306
+            super(in);
307
+            this.numBytesToRead = numBytesToRead;
308
+        }
309
+        @Override
310
+        public int read() throws IOException {
311
+            if (numBytesToRead <= 0) {
312
+                return -1;
313
+            }
314
+            numBytesToRead--;
315
+            return in.read();
316
+        }
317
+        @Override
318
+        public int read(byte[] buffer, int byteOffset, int byteCount) throws IOException {
319
+            if (numBytesToRead <= 0) {
320
+                return -1;
321
+            }
322
+            int bytesToRead = byteCount;
323
+            if (byteCount > numBytesToRead) {
324
+                bytesToRead = (int)numBytesToRead; // Cast okay; long is less than int here.
325
+            }
326
+            int numBytesRead = in.read(buffer, byteOffset, bytesToRead);
327
+            numBytesToRead -= numBytesRead;
328
+            return numBytesRead;
329
+        }
330
+    }
331
+}

+ 30
- 0
node_modules/cordova-plugin-file/src/android/InvalidModificationException.java Visa fil

@@ -0,0 +1,30 @@
1
+/*
2
+       Licensed to the Apache Software Foundation (ASF) under one
3
+       or more contributor license agreements.  See the NOTICE file
4
+       distributed with this work for additional information
5
+       regarding copyright ownership.  The ASF licenses this file
6
+       to you under the Apache License, Version 2.0 (the
7
+       "License"); you may not use this file except in compliance
8
+       with the License.  You may obtain a copy of the License at
9
+
10
+         http://www.apache.org/licenses/LICENSE-2.0
11
+
12
+       Unless required by applicable law or agreed to in writing,
13
+       software distributed under the License is distributed on an
14
+       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15
+       KIND, either express or implied.  See the License for the
16
+       specific language governing permissions and limitations
17
+       under the License.
18
+*/
19
+
20
+
21
+package org.apache.cordova.file;
22
+
23
+@SuppressWarnings("serial")
24
+public class InvalidModificationException extends Exception {
25
+
26
+    public InvalidModificationException(String message) {
27
+        super(message);
28
+    }
29
+
30
+}

+ 513
- 0
node_modules/cordova-plugin-file/src/android/LocalFilesystem.java Visa fil

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

+ 64
- 0
node_modules/cordova-plugin-file/src/android/LocalFilesystemURL.java Visa fil

@@ -0,0 +1,64 @@
1
+/*
2
+       Licensed to the Apache Software Foundation (ASF) under one
3
+       or more contributor license agreements.  See the NOTICE file
4
+       distributed with this work for additional information
5
+       regarding copyright ownership.  The ASF licenses this file
6
+       to you under the Apache License, Version 2.0 (the
7
+       "License"); you may not use this file except in compliance
8
+       with the License.  You may obtain a copy of the License at
9
+
10
+         http://www.apache.org/licenses/LICENSE-2.0
11
+
12
+       Unless required by applicable law or agreed to in writing,
13
+       software distributed under the License is distributed on an
14
+       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15
+       KIND, either express or implied.  See the License for the
16
+       specific language governing permissions and limitations
17
+       under the License.
18
+ */
19
+package org.apache.cordova.file;
20
+
21
+import android.net.Uri;
22
+
23
+public class LocalFilesystemURL {
24
+	
25
+	public static final String FILESYSTEM_PROTOCOL = "cdvfile";
26
+
27
+    public final Uri uri;
28
+    public final String fsName;
29
+    public final String path;
30
+    public final boolean isDirectory;
31
+
32
+	private LocalFilesystemURL(Uri uri, String fsName, String fsPath, boolean isDirectory) {
33
+		this.uri = uri;
34
+        this.fsName = fsName;
35
+        this.path = fsPath;
36
+        this.isDirectory = isDirectory;
37
+	}
38
+
39
+    public static LocalFilesystemURL parse(Uri uri) {
40
+        if (!FILESYSTEM_PROTOCOL.equals(uri.getScheme())) {
41
+            return null;
42
+        }
43
+        String path = uri.getPath();
44
+        if (path.length() < 1) {
45
+            return null;
46
+        }
47
+        int firstSlashIdx = path.indexOf('/', 1);
48
+        if (firstSlashIdx < 0) {
49
+            return null;
50
+        }
51
+        String fsName = path.substring(1, firstSlashIdx);
52
+        path = path.substring(firstSlashIdx);
53
+        boolean isDirectory = path.charAt(path.length() - 1) == '/';
54
+        return new LocalFilesystemURL(uri, fsName, path, isDirectory);
55
+    }
56
+
57
+    public static LocalFilesystemURL parse(String uri) {
58
+        return parse(Uri.parse(uri));
59
+    }
60
+
61
+    public String toString() {
62
+        return uri.toString();
63
+    }
64
+}

+ 29
- 0
node_modules/cordova-plugin-file/src/android/NoModificationAllowedException.java Visa fil

@@ -0,0 +1,29 @@
1
+/*
2
+       Licensed to the Apache Software Foundation (ASF) under one
3
+       or more contributor license agreements.  See the NOTICE file
4
+       distributed with this work for additional information
5
+       regarding copyright ownership.  The ASF licenses this file
6
+       to you under the Apache License, Version 2.0 (the
7
+       "License"); you may not use this file except in compliance
8
+       with the License.  You may obtain a copy of the License at
9
+
10
+         http://www.apache.org/licenses/LICENSE-2.0
11
+
12
+       Unless required by applicable law or agreed to in writing,
13
+       software distributed under the License is distributed on an
14
+       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15
+       KIND, either express or implied.  See the License for the
16
+       specific language governing permissions and limitations
17
+       under the License.
18
+*/
19
+
20
+package org.apache.cordova.file;
21
+
22
+@SuppressWarnings("serial")
23
+public class NoModificationAllowedException extends Exception {
24
+
25
+    public NoModificationAllowedException(String message) {
26
+        super(message);
27
+    }
28
+
29
+}

+ 94
- 0
node_modules/cordova-plugin-file/src/android/PendingRequests.java Visa fil

@@ -0,0 +1,94 @@
1
+/*
2
+       Licensed to the Apache Software Foundation (ASF) under one
3
+       or more contributor license agreements.  See the NOTICE file
4
+       distributed with this work for additional information
5
+       regarding copyright ownership.  The ASF licenses this file
6
+       to you under the Apache License, Version 2.0 (the
7
+       "License"); you may not use this file except in compliance
8
+       with the License.  You may obtain a copy of the License at
9
+
10
+         http://www.apache.org/licenses/LICENSE-2.0
11
+
12
+       Unless required by applicable law or agreed to in writing,
13
+       software distributed under the License is distributed on an
14
+       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15
+       KIND, either express or implied.  See the License for the
16
+       specific language governing permissions and limitations
17
+       under the License.
18
+*/
19
+package org.apache.cordova.file;
20
+
21
+import android.util.SparseArray;
22
+
23
+import org.apache.cordova.CallbackContext;
24
+
25
+/**
26
+ * Holds pending runtime permission requests
27
+ */
28
+class PendingRequests {
29
+    private int currentReqId = 0;
30
+    private SparseArray<Request> requests = new SparseArray<Request>();
31
+
32
+    /**
33
+     * Creates a request and adds it to the array of pending requests. Each created request gets a
34
+     * unique result code for use with requestPermission()
35
+     * @param rawArgs           The raw arguments passed to the plugin
36
+     * @param action            The action this request corresponds to (get file, etc.)
37
+     * @param callbackContext   The CallbackContext for this plugin call
38
+     * @return                  The request code that can be used to retrieve the Request object
39
+     */
40
+    public synchronized int createRequest(String rawArgs, int action, CallbackContext callbackContext)  {
41
+        Request req = new Request(rawArgs, action, callbackContext);
42
+        requests.put(req.requestCode, req);
43
+        return req.requestCode;
44
+    }
45
+
46
+    /**
47
+     * Gets the request corresponding to this request code and removes it from the pending requests
48
+     * @param requestCode   The request code for the desired request
49
+     * @return              The request corresponding to the given request code or null if such a
50
+     *                      request is not found
51
+     */
52
+    public synchronized Request getAndRemove(int requestCode) {
53
+        Request result = requests.get(requestCode);
54
+        requests.remove(requestCode);
55
+        return result;
56
+    }
57
+
58
+    /**
59
+     * Holds the options and CallbackContext for a call made to the plugin.
60
+     */
61
+    public class Request {
62
+
63
+        // Unique int used to identify this request in any Android permission callback
64
+        private int requestCode;
65
+
66
+        // Action to be performed after permission request result
67
+        private int action;
68
+
69
+        // Raw arguments passed to plugin
70
+        private String rawArgs;
71
+
72
+        // The callback context for this plugin request
73
+        private CallbackContext callbackContext;
74
+
75
+        private Request(String rawArgs, int action, CallbackContext callbackContext) {
76
+            this.rawArgs = rawArgs;
77
+            this.action = action;
78
+            this.callbackContext = callbackContext;
79
+            this.requestCode = currentReqId ++;
80
+        }
81
+
82
+        public int getAction() {
83
+            return this.action;
84
+        }
85
+
86
+        public String getRawArgs() {
87
+            return rawArgs;
88
+        }
89
+
90
+        public CallbackContext getCallbackContext() {
91
+            return callbackContext;
92
+        }
93
+    }
94
+}

+ 30
- 0
node_modules/cordova-plugin-file/src/android/TypeMismatchException.java Visa fil

@@ -0,0 +1,30 @@
1
+/*
2
+       Licensed to the Apache Software Foundation (ASF) under one
3
+       or more contributor license agreements.  See the NOTICE file
4
+       distributed with this work for additional information
5
+       regarding copyright ownership.  The ASF licenses this file
6
+       to you under the Apache License, Version 2.0 (the
7
+       "License"); you may not use this file except in compliance
8
+       with the License.  You may obtain a copy of the License at
9
+
10
+         http://www.apache.org/licenses/LICENSE-2.0
11
+
12
+       Unless required by applicable law or agreed to in writing,
13
+       software distributed under the License is distributed on an
14
+       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15
+       KIND, either express or implied.  See the License for the
16
+       specific language governing permissions and limitations
17
+       under the License.
18
+*/
19
+
20
+
21
+package org.apache.cordova.file;
22
+
23
+@SuppressWarnings("serial")
24
+public class TypeMismatchException extends Exception {
25
+
26
+    public TypeMismatchException(String message) {
27
+        super(message);
28
+    }
29
+
30
+}

+ 47
- 0
node_modules/cordova-plugin-file/src/android/build-extras.gradle Visa fil

@@ -0,0 +1,47 @@
1
+/*
2
+       Licensed to the Apache Software Foundation (ASF) under one
3
+       or more contributor license agreements.  See the NOTICE file
4
+       distributed with this work for additional information
5
+       regarding copyright ownership.  The ASF licenses this file
6
+       to you under the Apache License, Version 2.0 (the
7
+       "License"); you may not use this file except in compliance
8
+       with the License.  You may obtain a copy of the License at
9
+
10
+         http://www.apache.org/licenses/LICENSE-2.0
11
+
12
+       Unless required by applicable law or agreed to in writing,
13
+       software distributed under the License is distributed on an
14
+       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15
+       KIND, either express or implied.  See the License for the
16
+       specific language governing permissions and limitations
17
+       under the License.
18
+ */
19
+ext.postBuildExtras = {
20
+    def inAssetsDir = file("assets")
21
+    def outAssetsDir = inAssetsDir
22
+    def outFile = new File(outAssetsDir, "cdvasset.manifest")
23
+
24
+    def newTask = task("cdvCreateAssetManifest") << {
25
+        def contents = new HashMap()
26
+        def sizes = new HashMap()
27
+        contents[""] = inAssetsDir.list()
28
+        def tree = fileTree(dir: inAssetsDir)
29
+        tree.visit { fileDetails ->
30
+            if (fileDetails.isDirectory()) {
31
+                contents[fileDetails.relativePath.toString()] = fileDetails.file.list()
32
+            } else {
33
+                sizes[fileDetails.relativePath.toString()] = fileDetails.file.length()
34
+            }
35
+        }
36
+
37
+        outAssetsDir.mkdirs()
38
+        outFile.withObjectOutputStream { oos ->
39
+            oos.writeObject(contents)
40
+            oos.writeObject(sizes)
41
+        }
42
+    }
43
+    newTask.inputs.dir inAssetsDir
44
+    newTask.outputs.file outFile
45
+    def preBuildTask = tasks["preBuild"]
46
+    preBuildTask.dependsOn(newTask)
47
+}

+ 1059
- 0
node_modules/cordova-plugin-file/src/browser/FileProxy.js
Filskillnaden har hållits tillbaka eftersom den är för stor
Visa fil


+ 30
- 0
node_modules/cordova-plugin-file/src/ios/CDVAssetLibraryFilesystem.h Visa fil

@@ -0,0 +1,30 @@
1
+/*
2
+ Licensed to the Apache Software Foundation (ASF) under one
3
+ or more contributor license agreements.  See the NOTICE file
4
+ distributed with this work for additional information
5
+ regarding copyright ownership.  The ASF licenses this file
6
+ to you under the Apache License, Version 2.0 (the
7
+ "License"); you may not use this file except in compliance
8
+ with the License.  You may obtain a copy of the License at
9
+
10
+ http://www.apache.org/licenses/LICENSE-2.0
11
+
12
+ Unless required by applicable law or agreed to in writing,
13
+ software distributed under the License is distributed on an
14
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15
+ KIND, either express or implied.  See the License for the
16
+ specific language governing permissions and limitations
17
+ under the License.
18
+ */
19
+
20
+#import "CDVFile.h"
21
+
22
+extern NSString* const kCDVAssetsLibraryPrefix;
23
+extern NSString* const kCDVAssetsLibraryScheme;
24
+
25
+@interface CDVAssetLibraryFilesystem : NSObject<CDVFileSystem> {
26
+}
27
+
28
+- (id) initWithName:(NSString *)name;
29
+
30
+@end

+ 253
- 0
node_modules/cordova-plugin-file/src/ios/CDVAssetLibraryFilesystem.m Visa fil

@@ -0,0 +1,253 @@
1
+/*
2
+ Licensed to the Apache Software Foundation (ASF) under one
3
+ or more contributor license agreements.  See the NOTICE file
4
+ distributed with this work for additional information
5
+ regarding copyright ownership.  The ASF licenses this file
6
+ to you under the Apache License, Version 2.0 (the
7
+ "License"); you may not use this file except in compliance
8
+ with the License.  You may obtain a copy of the License at
9
+
10
+ http://www.apache.org/licenses/LICENSE-2.0
11
+
12
+ Unless required by applicable law or agreed to in writing,
13
+ software distributed under the License is distributed on an
14
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15
+ KIND, either express or implied.  See the License for the
16
+ specific language governing permissions and limitations
17
+ under the License.
18
+ */
19
+
20
+#import "CDVFile.h"
21
+#import "CDVAssetLibraryFilesystem.h"
22
+#import <Cordova/CDV.h>
23
+#import <AssetsLibrary/ALAsset.h>
24
+#import <AssetsLibrary/ALAssetRepresentation.h>
25
+#import <AssetsLibrary/ALAssetsLibrary.h>
26
+#import <MobileCoreServices/MobileCoreServices.h>
27
+
28
+NSString* const kCDVAssetsLibraryPrefix = @"assets-library://";
29
+NSString* const kCDVAssetsLibraryScheme = @"assets-library";
30
+
31
+@implementation CDVAssetLibraryFilesystem
32
+@synthesize name=_name, urlTransformer;
33
+
34
+
35
+/*
36
+ The CDVAssetLibraryFilesystem works with resources which are identified
37
+ by iOS as
38
+   asset-library://<path>
39
+ and represents them internally as URLs of the form
40
+   cdvfile://localhost/assets-library/<path>
41
+ */
42
+
43
+- (NSURL *)assetLibraryURLForLocalURL:(CDVFilesystemURL *)url
44
+{
45
+    if ([url.url.scheme isEqualToString:kCDVFilesystemURLPrefix]) {
46
+        NSString *path = [[url.url absoluteString] substringFromIndex:[@"cdvfile://localhost/assets-library" length]];
47
+        return [NSURL URLWithString:[NSString stringWithFormat:@"assets-library:/%@", path]];
48
+    }
49
+    return url.url;
50
+}
51
+
52
+- (CDVPluginResult *)entryForLocalURI:(CDVFilesystemURL *)url
53
+{
54
+    NSDictionary* entry = [self makeEntryForLocalURL:url];
55
+    return [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:entry];
56
+}
57
+
58
+- (NSDictionary *)makeEntryForLocalURL:(CDVFilesystemURL *)url {
59
+    return [self makeEntryForPath:url.fullPath isDirectory:NO];
60
+}
61
+
62
+- (NSDictionary*)makeEntryForPath:(NSString*)fullPath isDirectory:(BOOL)isDir
63
+{
64
+    NSMutableDictionary* dirEntry = [NSMutableDictionary dictionaryWithCapacity:5];
65
+    NSString* lastPart = [fullPath lastPathComponent];
66
+    if (isDir && ![fullPath hasSuffix:@"/"]) {
67
+        fullPath = [fullPath stringByAppendingString:@"/"];
68
+    }
69
+    [dirEntry setObject:[NSNumber numberWithBool:!isDir]  forKey:@"isFile"];
70
+    [dirEntry setObject:[NSNumber numberWithBool:isDir]  forKey:@"isDirectory"];
71
+    [dirEntry setObject:fullPath forKey:@"fullPath"];
72
+    [dirEntry setObject:lastPart forKey:@"name"];
73
+    [dirEntry setObject:self.name forKey: @"filesystemName"];
74
+
75
+    NSURL* nativeURL = [NSURL URLWithString:[NSString stringWithFormat:@"assets-library:/%@",fullPath]];
76
+    if (self.urlTransformer) {
77
+        nativeURL = self.urlTransformer(nativeURL);
78
+    }
79
+    dirEntry[@"nativeURL"] = [nativeURL absoluteString];
80
+
81
+    return dirEntry;
82
+}
83
+
84
+/* helper function to get the mimeType from the file extension
85
+ * IN:
86
+ *	NSString* fullPath - filename (may include path)
87
+ * OUT:
88
+ *	NSString* the mime type as type/subtype.  nil if not able to determine
89
+ */
90
++ (NSString*)getMimeTypeFromPath:(NSString*)fullPath
91
+{
92
+    NSString* mimeType = nil;
93
+
94
+    if (fullPath) {
95
+        CFStringRef typeId = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)[fullPath pathExtension], NULL);
96
+        if (typeId) {
97
+            mimeType = (__bridge_transfer NSString*)UTTypeCopyPreferredTagWithClass(typeId, kUTTagClassMIMEType);
98
+            if (!mimeType) {
99
+                // special case for m4a
100
+                if ([(__bridge NSString*)typeId rangeOfString : @"m4a-audio"].location != NSNotFound) {
101
+                    mimeType = @"audio/mp4";
102
+                } else if ([[fullPath pathExtension] rangeOfString:@"wav"].location != NSNotFound) {
103
+                    mimeType = @"audio/wav";
104
+                } else if ([[fullPath pathExtension] rangeOfString:@"css"].location != NSNotFound) {
105
+                    mimeType = @"text/css";
106
+                }
107
+            }
108
+            CFRelease(typeId);
109
+        }
110
+    }
111
+    return mimeType;
112
+}
113
+
114
+- (id)initWithName:(NSString *)name
115
+{
116
+    if (self) {
117
+        self.name = name;
118
+    }
119
+    return self;
120
+}
121
+
122
+- (CDVPluginResult *)getFileForURL:(CDVFilesystemURL *)baseURI requestedPath:(NSString *)requestedPath options:(NSDictionary *)options
123
+{
124
+    // return unsupported result for assets-library URLs
125
+   return [CDVPluginResult resultWithStatus:CDVCommandStatus_MALFORMED_URL_EXCEPTION messageAsString:@"getFile not supported for assets-library URLs."];
126
+}
127
+
128
+- (CDVPluginResult*)getParentForURL:(CDVFilesystemURL *)localURI
129
+{
130
+    // we don't (yet?) support getting the parent of an asset
131
+    return [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NOT_READABLE_ERR];
132
+}
133
+
134
+- (CDVPluginResult*)setMetadataForURL:(CDVFilesystemURL *)localURI withObject:(NSDictionary *)options
135
+{
136
+    // setMetadata doesn't make sense for asset library files
137
+    return [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR];
138
+}
139
+
140
+- (CDVPluginResult *)removeFileAtURL:(CDVFilesystemURL *)localURI
141
+{
142
+    // return error for assets-library URLs
143
+    return [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:INVALID_MODIFICATION_ERR];
144
+}
145
+
146
+- (CDVPluginResult *)recursiveRemoveFileAtURL:(CDVFilesystemURL *)localURI
147
+{
148
+    // return error for assets-library URLs
149
+    return [CDVPluginResult resultWithStatus:CDVCommandStatus_MALFORMED_URL_EXCEPTION messageAsString:@"removeRecursively not supported for assets-library URLs."];
150
+}
151
+
152
+- (CDVPluginResult *)readEntriesAtURL:(CDVFilesystemURL *)localURI
153
+{
154
+    // return unsupported result for assets-library URLs
155
+    return [CDVPluginResult resultWithStatus:CDVCommandStatus_MALFORMED_URL_EXCEPTION messageAsString:@"readEntries not supported for assets-library URLs."];
156
+}
157
+
158
+- (CDVPluginResult *)truncateFileAtURL:(CDVFilesystemURL *)localURI atPosition:(unsigned long long)pos
159
+{
160
+    // assets-library files can't be truncated
161
+    return [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NO_MODIFICATION_ALLOWED_ERR];
162
+}
163
+
164
+- (CDVPluginResult *)writeToFileAtURL:(CDVFilesystemURL *)localURL withData:(NSData*)encData append:(BOOL)shouldAppend
165
+{
166
+    // text can't be written into assets-library files
167
+    return [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NO_MODIFICATION_ALLOWED_ERR];
168
+}
169
+
170
+- (void)copyFileToURL:(CDVFilesystemURL *)destURL withName:(NSString *)newName fromFileSystem:(NSObject<CDVFileSystem> *)srcFs atURL:(CDVFilesystemURL *)srcURL copy:(BOOL)bCopy callback:(void (^)(CDVPluginResult *))callback
171
+{
172
+    // Copying to an assets library file is not doable, since we can't write it.
173
+    CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:INVALID_MODIFICATION_ERR];
174
+    callback(result);
175
+}
176
+
177
+- (NSString *)filesystemPathForURL:(CDVFilesystemURL *)url
178
+{
179
+    NSString *path = nil;
180
+    if ([[url.url scheme] isEqualToString:kCDVAssetsLibraryScheme]) {
181
+        path = [url.url path];
182
+    } else {
183
+       path = url.fullPath;
184
+    }
185
+    if ([path hasSuffix:@"/"]) {
186
+      path = [path substringToIndex:([path length]-1)];
187
+    }
188
+    return path;
189
+}
190
+
191
+- (void)readFileAtURL:(CDVFilesystemURL *)localURL start:(NSInteger)start end:(NSInteger)end callback:(void (^)(NSData*, NSString* mimeType, CDVFileError))callback
192
+{
193
+    ALAssetsLibraryAssetForURLResultBlock resultBlock = ^(ALAsset* asset) {
194
+        if (asset) {
195
+            // We have the asset!  Get the data and send it off.
196
+            ALAssetRepresentation* assetRepresentation = [asset defaultRepresentation];
197
+            NSUInteger size = (end > start) ? (end - start) : [assetRepresentation size];
198
+            Byte* buffer = (Byte*)malloc(size);
199
+            NSUInteger bufferSize = [assetRepresentation getBytes:buffer fromOffset:start length:size error:nil];
200
+            NSData* data = [NSData dataWithBytesNoCopy:buffer length:bufferSize freeWhenDone:YES];
201
+            NSString* MIMEType = (__bridge_transfer NSString*)UTTypeCopyPreferredTagWithClass((__bridge CFStringRef)[assetRepresentation UTI], kUTTagClassMIMEType);
202
+
203
+            callback(data, MIMEType, NO_ERROR);
204
+        } else {
205
+            callback(nil, nil, NOT_FOUND_ERR);
206
+        }
207
+    };
208
+
209
+    ALAssetsLibraryAccessFailureBlock failureBlock = ^(NSError* error) {
210
+        // Retrieving the asset failed for some reason.  Send the appropriate error.
211
+        NSLog(@"Error: %@", error);
212
+        callback(nil, nil, SECURITY_ERR);
213
+    };
214
+
215
+    ALAssetsLibrary* assetsLibrary = [[ALAssetsLibrary alloc] init];
216
+    [assetsLibrary assetForURL:[self assetLibraryURLForLocalURL:localURL] resultBlock:resultBlock failureBlock:failureBlock];
217
+}
218
+
219
+- (void)getFileMetadataForURL:(CDVFilesystemURL *)localURL callback:(void (^)(CDVPluginResult *))callback
220
+{
221
+    // In this case, we need to use an asynchronous method to retrieve the file.
222
+    // Because of this, we can't just assign to `result` and send it at the end of the method.
223
+    // Instead, we return after calling the asynchronous method and send `result` in each of the blocks.
224
+    ALAssetsLibraryAssetForURLResultBlock resultBlock = ^(ALAsset* asset) {
225
+        if (asset) {
226
+            // We have the asset!  Populate the dictionary and send it off.
227
+            NSMutableDictionary* fileInfo = [NSMutableDictionary dictionaryWithCapacity:5];
228
+            ALAssetRepresentation* assetRepresentation = [asset defaultRepresentation];
229
+            [fileInfo setObject:[NSNumber numberWithUnsignedLongLong:[assetRepresentation size]] forKey:@"size"];
230
+            [fileInfo setObject:localURL.fullPath forKey:@"fullPath"];
231
+            NSString* filename = [assetRepresentation filename];
232
+            [fileInfo setObject:filename forKey:@"name"];
233
+            [fileInfo setObject:[CDVAssetLibraryFilesystem getMimeTypeFromPath:filename] forKey:@"type"];
234
+            NSDate* creationDate = [asset valueForProperty:ALAssetPropertyDate];
235
+            NSNumber* msDate = [NSNumber numberWithDouble:[creationDate timeIntervalSince1970] * 1000];
236
+            [fileInfo setObject:msDate forKey:@"lastModifiedDate"];
237
+
238
+            callback([CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:fileInfo]);
239
+        } else {
240
+            // We couldn't find the asset.  Send the appropriate error.
241
+            callback([CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NOT_FOUND_ERR]);
242
+        }
243
+    };
244
+    ALAssetsLibraryAccessFailureBlock failureBlock = ^(NSError* error) {
245
+        // Retrieving the asset failed for some reason.  Send the appropriate error.
246
+        callback([CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsString:[error localizedDescription]]);
247
+    };
248
+
249
+    ALAssetsLibrary* assetsLibrary = [[ALAssetsLibrary alloc] init];
250
+    [assetsLibrary assetForURL:[self assetLibraryURLForLocalURL:localURL] resultBlock:resultBlock failureBlock:failureBlock];
251
+    return;
252
+}
253
+@end

+ 157
- 0
node_modules/cordova-plugin-file/src/ios/CDVFile.h Visa fil

@@ -0,0 +1,157 @@
1
+/*
2
+ Licensed to the Apache Software Foundation (ASF) under one
3
+ or more contributor license agreements.  See the NOTICE file
4
+ distributed with this work for additional information
5
+ regarding copyright ownership.  The ASF licenses this file
6
+ to you under the Apache License, Version 2.0 (the
7
+ "License"); you may not use this file except in compliance
8
+ with the License.  You may obtain a copy of the License at
9
+
10
+ http://www.apache.org/licenses/LICENSE-2.0
11
+
12
+ Unless required by applicable law or agreed to in writing,
13
+ software distributed under the License is distributed on an
14
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15
+ KIND, either express or implied.  See the License for the
16
+ specific language governing permissions and limitations
17
+ under the License.
18
+ */
19
+
20
+#import <Foundation/Foundation.h>
21
+#import <Cordova/CDVPlugin.h>
22
+
23
+extern NSString* const kCDVAssetsLibraryPrefix;
24
+extern NSString* const kCDVFilesystemURLPrefix;
25
+
26
+enum CDVFileError {
27
+    NO_ERROR = 0,
28
+    NOT_FOUND_ERR = 1,
29
+    SECURITY_ERR = 2,
30
+    ABORT_ERR = 3,
31
+    NOT_READABLE_ERR = 4,
32
+    ENCODING_ERR = 5,
33
+    NO_MODIFICATION_ALLOWED_ERR = 6,
34
+    INVALID_STATE_ERR = 7,
35
+    SYNTAX_ERR = 8,
36
+    INVALID_MODIFICATION_ERR = 9,
37
+    QUOTA_EXCEEDED_ERR = 10,
38
+    TYPE_MISMATCH_ERR = 11,
39
+    PATH_EXISTS_ERR = 12
40
+};
41
+typedef int CDVFileError;
42
+
43
+@interface CDVFilesystemURL : NSObject  {
44
+    NSURL *_url;
45
+    NSString *_fileSystemName;
46
+    NSString *_fullPath;
47
+}
48
+
49
+- (id) initWithString:(NSString*)strURL;
50
+- (id) initWithURL:(NSURL*)URL;
51
++ (CDVFilesystemURL *)fileSystemURLWithString:(NSString *)strURL;
52
++ (CDVFilesystemURL *)fileSystemURLWithURL:(NSURL *)URL;
53
+
54
+- (NSString *)absoluteURL;
55
+
56
+@property (atomic) NSURL *url;
57
+@property (atomic) NSString *fileSystemName;
58
+@property (atomic) NSString *fullPath;
59
+
60
+@end
61
+
62
+@interface CDVFilesystemURLProtocol : NSURLProtocol
63
+@end
64
+
65
+@protocol CDVFileSystem
66
+- (CDVPluginResult *)entryForLocalURI:(CDVFilesystemURL *)url;
67
+- (CDVPluginResult *)getFileForURL:(CDVFilesystemURL *)baseURI requestedPath:(NSString *)requestedPath options:(NSDictionary *)options;
68
+- (CDVPluginResult *)getParentForURL:(CDVFilesystemURL *)localURI;
69
+- (CDVPluginResult *)setMetadataForURL:(CDVFilesystemURL *)localURI withObject:(NSDictionary *)options;
70
+- (CDVPluginResult *)removeFileAtURL:(CDVFilesystemURL *)localURI;
71
+- (CDVPluginResult *)recursiveRemoveFileAtURL:(CDVFilesystemURL *)localURI;
72
+- (CDVPluginResult *)readEntriesAtURL:(CDVFilesystemURL *)localURI;
73
+- (CDVPluginResult *)truncateFileAtURL:(CDVFilesystemURL *)localURI atPosition:(unsigned long long)pos;
74
+- (CDVPluginResult *)writeToFileAtURL:(CDVFilesystemURL *)localURL withData:(NSData*)encData append:(BOOL)shouldAppend;
75
+- (void)copyFileToURL:(CDVFilesystemURL *)destURL withName:(NSString *)newName fromFileSystem:(NSObject<CDVFileSystem> *)srcFs atURL:(CDVFilesystemURL *)srcURL copy:(BOOL)bCopy callback:(void (^)(CDVPluginResult *))callback;
76
+- (void)readFileAtURL:(CDVFilesystemURL *)localURL start:(NSInteger)start end:(NSInteger)end callback:(void (^)(NSData*, NSString* mimeType, CDVFileError))callback;
77
+- (void)getFileMetadataForURL:(CDVFilesystemURL *)localURL callback:(void (^)(CDVPluginResult *))callback;
78
+
79
+- (NSDictionary *)makeEntryForLocalURL:(CDVFilesystemURL *)url;
80
+- (NSDictionary*)makeEntryForPath:(NSString*)fullPath isDirectory:(BOOL)isDir;
81
+
82
+@property (nonatomic,strong) NSString *name;
83
+@property (nonatomic, copy) NSURL*(^urlTransformer)(NSURL*);
84
+
85
+@optional
86
+- (NSString *)filesystemPathForURL:(CDVFilesystemURL *)localURI;
87
+- (CDVFilesystemURL *)URLforFilesystemPath:(NSString *)path;
88
+
89
+@end
90
+
91
+@interface CDVFile : CDVPlugin {
92
+    NSString* rootDocsPath;
93
+    NSString* appDocsPath;
94
+    NSString* appLibraryPath;
95
+    NSString* appTempPath;
96
+
97
+    NSMutableArray* fileSystems_;
98
+    BOOL userHasAllowed;
99
+}
100
+
101
+- (NSNumber*)checkFreeDiskSpace:(NSString*)appPath;
102
+- (NSDictionary*)makeEntryForPath:(NSString*)fullPath fileSystemName:(NSString *)fsName isDirectory:(BOOL)isDir;
103
+- (NSDictionary *)makeEntryForURL:(NSURL *)URL;
104
+- (CDVFilesystemURL *)fileSystemURLforLocalPath:(NSString *)localPath;
105
+
106
+- (NSObject<CDVFileSystem> *)filesystemForURL:(CDVFilesystemURL *)localURL;
107
+
108
+/* Native Registration API */
109
+- (void)registerFilesystem:(NSObject<CDVFileSystem> *)fs;
110
+- (NSObject<CDVFileSystem> *)fileSystemByName:(NSString *)fsName;
111
+
112
+/* Exec API */
113
+- (void)requestFileSystem:(CDVInvokedUrlCommand*)command;
114
+- (void)resolveLocalFileSystemURI:(CDVInvokedUrlCommand*)command;
115
+- (void)getDirectory:(CDVInvokedUrlCommand*)command;
116
+- (void)getFile:(CDVInvokedUrlCommand*)command;
117
+- (void)getParent:(CDVInvokedUrlCommand*)command;
118
+- (void)removeRecursively:(CDVInvokedUrlCommand*)command;
119
+- (void)remove:(CDVInvokedUrlCommand*)command;
120
+- (void)copyTo:(CDVInvokedUrlCommand*)command;
121
+- (void)moveTo:(CDVInvokedUrlCommand*)command;
122
+- (void)getFileMetadata:(CDVInvokedUrlCommand*)command;
123
+- (void)readEntries:(CDVInvokedUrlCommand*)command;
124
+- (void)readAsText:(CDVInvokedUrlCommand*)command;
125
+- (void)readAsDataURL:(CDVInvokedUrlCommand*)command;
126
+- (void)readAsArrayBuffer:(CDVInvokedUrlCommand*)command;
127
+- (void)write:(CDVInvokedUrlCommand*)command;
128
+- (void)testFileExists:(CDVInvokedUrlCommand*)command;
129
+- (void)testDirectoryExists:(CDVInvokedUrlCommand*)command;
130
+- (void)getFreeDiskSpace:(CDVInvokedUrlCommand*)command;
131
+- (void)truncate:(CDVInvokedUrlCommand*)command;
132
+- (void)doCopyMove:(CDVInvokedUrlCommand*)command isCopy:(BOOL)bCopy;
133
+
134
+/* Compatibilty with older File API */
135
+- (NSString*)getMimeTypeFromPath:(NSString*)fullPath;
136
+- (NSDictionary *)getDirectoryEntry:(NSString *)target isDirectory:(BOOL)bDirRequest;
137
+
138
+/* Conversion between filesystem paths and URLs */
139
+- (NSString *)filesystemPathForURL:(CDVFilesystemURL *)URL;
140
+
141
+/* Internal methods for testing */
142
+- (void)_getLocalFilesystemPath:(CDVInvokedUrlCommand*)command;
143
+
144
+@property (nonatomic, strong) NSString* rootDocsPath;
145
+@property (nonatomic, strong) NSString* appDocsPath;
146
+@property (nonatomic, strong) NSString* appLibraryPath;
147
+@property (nonatomic, strong) NSString* appTempPath;
148
+@property (nonatomic, strong) NSString* persistentPath;
149
+@property (nonatomic, strong) NSString* temporaryPath;
150
+@property (nonatomic, strong) NSMutableArray* fileSystems;
151
+
152
+@property BOOL userHasAllowed;
153
+
154
+@end
155
+
156
+#define kW3FileTemporary @"temporary"
157
+#define kW3FilePersistent @"persistent"

+ 1119
- 0
node_modules/cordova-plugin-file/src/ios/CDVFile.m
Filskillnaden har hållits tillbaka eftersom den är för stor
Visa fil


+ 32
- 0
node_modules/cordova-plugin-file/src/ios/CDVLocalFilesystem.h Visa fil

@@ -0,0 +1,32 @@
1
+/*
2
+ Licensed to the Apache Software Foundation (ASF) under one
3
+ or more contributor license agreements.  See the NOTICE file
4
+ distributed with this work for additional information
5
+ regarding copyright ownership.  The ASF licenses this file
6
+ to you under the Apache License, Version 2.0 (the
7
+ "License"); you may not use this file except in compliance
8
+ with the License.  You may obtain a copy of the License at
9
+
10
+ http://www.apache.org/licenses/LICENSE-2.0
11
+
12
+ Unless required by applicable law or agreed to in writing,
13
+ software distributed under the License is distributed on an
14
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15
+ KIND, either express or implied.  See the License for the
16
+ specific language governing permissions and limitations
17
+ under the License.
18
+ */
19
+
20
+#import "CDVFile.h"
21
+
22
+@interface CDVLocalFilesystem : NSObject<CDVFileSystem> {
23
+    NSString *_name;
24
+    NSString *_fsRoot;
25
+}
26
+
27
+- (id) initWithName:(NSString *)name root:(NSString *)fsRoot;
28
++ (NSString*)getMimeTypeFromPath:(NSString*)fullPath;
29
+
30
+@property (nonatomic,strong) NSString *fsRoot;
31
+
32
+@end

+ 0
- 0
node_modules/cordova-plugin-file/src/ios/CDVLocalFilesystem.m Visa fil


Vissa filer visades inte eftersom för många filer har ändrats