diff options
Diffstat (limited to 'plugins/com.synconset.cordovaHTTP')
36 files changed, 0 insertions, 12618 deletions
diff --git a/plugins/com.synconset.cordovaHTTP/LICENSE b/plugins/com.synconset.cordovaHTTP/LICENSE deleted file mode 100644 index 30c6eb5a..00000000 --- a/plugins/com.synconset.cordovaHTTP/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Wymsee, Inc - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE.
\ No newline at end of file diff --git a/plugins/com.synconset.cordovaHTTP/README.md b/plugins/com.synconset.cordovaHTTP/README.md deleted file mode 100644 index dc5a3927..00000000 --- a/plugins/com.synconset.cordovaHTTP/README.md +++ /dev/null @@ -1,191 +0,0 @@ -cordovaHTTP -================== - -Cordova / Phonegap plugin for communicating with HTTP servers. Supports iOS and Android. - -## Advantages over Javascript requests - - - Background threading - all requests are done in a background thread. - - SSL Pinning - read more at [LumberBlog](http://blog.lumberlabs.com/2012/04/why-app-developers-should-care-about.html). - -## Installation - -The plugin conforms to the Cordova plugin specification, it can be installed -using the Cordova / Phonegap command line interface. - - phonegap plugin add https://github.com/wymsee/cordova-HTTP.git - - cordova plugin add https://github.com/wymsee/cordova-HTTP.git - -## Usage - -### AngularJS - -This plugin creates a cordovaHTTP service inside of a cordovaHTTP module. You must load the module when you create your app's module. - - var app = angular.module('myApp', ['ngRoute', 'ngAnimate', 'cordovaHTTP']); - -You can then inject the cordovaHTTP service into your controllers. The functions can then be used identically to the examples shown below except that instead of accepting success and failure callback functions, each function returns a promise. For more information on promises in AngularJS read the [AngularJS docs](http://docs.angularjs.org/api/ng/service/$q). For more info on promises in general check out this article on [html5rocks](http://www.html5rocks.com/en/tutorials/es6/promises/). Make sure that you load cordova.js or phonegap.js after AngularJS is loaded. - -### Not AngularJS - -This plugin registers a `cordovaHTTP` global on window - - -## Functions - -All available functions are documented below. Every function takes a success and error callback function as the last 2 arguments. - -### useBasicAuth -This sets up all future requests to use Basic HTTP authentication with the given username and password. - - cordovaHTTP.useBasicAuth("user", "password", function() { - console.log('success!'); - }, function() { - console.log('error :('); - }); - -### setHeader -Set a header for all future requests. Takes a header and a value. - - cordovaHTTP.setHeader("Header", "Value", function() { - console.log('success!'); - }, function() { - console.log('error :('); - }); - -### enableSSLPinning -Enable or disable SSL pinning. 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. For ios include your certificate in the root level of your bundle (just add the .cer file to your project/target at the root level). For android include your certificate in your project's platforms/android/assets folder. In both cases all .cer files found will be loaded automatically. If you only have a .pem certificate see this [stackoverflow answer](http://stackoverflow.com/a/16583429/3182729). You want to convert it to a DER encoded certificate with a .cer extension. - -As an alternative, you can store your .cer files in the www/certificates folder. - - cordovaHTTP.enableSSLPinning(true, function() { - console.log('success!'); - }, function() { - console.log('error :('); - }); - -### acceptAllCerts -Accept all SSL certificates. Or disable accepting all certificates. - - cordovaHTTP.acceptAllCerts(true, function() { - console.log('success!'); - }, function() { - console.log('error :('); - }); - -### post<a name="post"></a> -Execute a POST request. Takes a URL, parameters, and headers. - -#### success -The success function receives a response object with 2 properties: status and data. Status is the HTTP response code and data is the response from the server as a string. Here's a quick example: - - { - status: 200, - data: "{'id': 12, 'message': 'test'}" - } - -Most apis will return JSON meaning you'll want to parse the data like in the example below: - - cordovaHTTP.post("https://google.com/, { - id: 12, - message: "test" - }, { Authorization: "OAuth2: token" }, function(response) { - // prints 200 - console.log(response.status); - try { - response.data = JSON.parse(response.data); - // prints test - console.log(response.data.message); - } catch(e) { - console.error("JSON parsing error"); - } - }, function(response) { - // prints 403 - console.log(response.status); - - //prints Permission denied - console.log(response.error); - }); - - -#### failure -The error function receives a response object with 2 properties: status and error. Status is the HTTP response code. Error is the error response from the server as a string. Here's a quick example: - - { - status: 403, - error: "Permission denied" - } - -### get -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. - - cordovaHTTP.get("https://google.com/, { - id: 12, - message: "test" - }, { Authorization: "OAuth2: token" }, function(response) { - console.log(response.status); - }, function(response) { - console.error(response.error); - }); - -### uploadFile -Uploads a file saved on the device. Takes a URL, parameters, headers, filePath, and the name of the parameter to pass the file along as. See the [post](#post) documentation for details on what is returned on success and failure. - - cordovaHTTP.uploadFile("https://google.com/, { - id: 12, - message: "test" - }, { Authorization: "OAuth2: token" }, "file:///somepicture.jpg", "picture", function(response) { - console.log(response.status); - }, function(response) { - console.error(response.error); - }); - -### downloadFile -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). - - cordovaHTTP.downloadFile("https://google.com/, { - id: 12, - message: "test" - }, { Authorization: "OAuth2: token" }, "file:///somepicture.jpg", function(entry) { - // prints the filename - console.log(entry.name); - - // prints the filePath - console.log(entry.fullPath); - }, function(response) { - console.error(response.error); - }); - - -## Libraries - -This plugin utilizes some awesome open source networking libraries. These are both MIT licensed: - - - iOS - [AFNetworking](https://github.com/AFNetworking/AFNetworking) - - Android - [http-request](https://github.com/kevinsawicki/http-request) - -We made a few modifications to http-request. They can be found in a separate repo here: https://github.com/wymsee/http-request - -## Limitations - -This plugin isn't equivalent to using XMLHttpRequest or Ajax calls in Javascript. -For instance, the following features are currently not supported: - -- cookies support (a cookie set by a request isn't sent in subsequent requests) -- read content of error responses (only the HTTP status code and message are returned) -- read returned HTTP headers (e.g. in case security tokens are returned as headers) - -Take this into account when using this plugin into your application. - -## License - -The MIT License - -Copyright (c) 2014 Wymsee, Inc - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/plugins/com.synconset.cordovaHTTP/plugin.xml b/plugins/com.synconset.cordovaHTTP/plugin.xml deleted file mode 100644 index 1b220ef8..00000000 --- a/plugins/com.synconset.cordovaHTTP/plugin.xml +++ /dev/null @@ -1,89 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<plugin xmlns="http://www.phonegap.com/ns/plugins/1.0" - xmlns:android="http://schemas.android.com/apk/res/android" - id="com.synconset.cordovaHTTP" - version="0.1.4"> - - <name>SSL Pinning</name> - - <description> - Cordova / Phonegap plugin for communicating with HTTP servers using SSL pinning - </description> - - <engines> - <engine name="cordova" version=">=3.0.0" /> - </engines> - - <dependency id="org.apache.cordova.file" url="https://github.com/apache/cordova-plugin-file" commit="r0.2.5" /> - - <js-module src="www/cordovaHTTP.js" name="CordovaHttpPlugin"> - <clobbers target="plugins.CordovaHttpPlugin" /> - </js-module> - - <!-- ios --> - <platform name="ios"> - <config-file target="config.xml" parent="/*"> - <feature name="CordovaHttpPlugin"> - <param name="ios-package" value="CordovaHttpPlugin"/> - </feature> - </config-file> - - <header-file src="src/ios/CordovaHttpPlugin.h" /> - <source-file src="src/ios/CordovaHttpPlugin.m" /> - - <header-file src="src/ios/HTTPManager.h" /> - <source-file src="src/ios/HTTPManager.m" /> - - <header-file src="src/ios/TextResponseSerializer.h" /> - <source-file src="src/ios/TextResponseSerializer.m" /> - - <header-file src="src/ios/AFNetworking/AFHTTPRequestOperation.h" /> - <source-file src="src/ios/AFNetworking/AFHTTPRequestOperation.m" /> - - <header-file src="src/ios/AFNetworking/AFHTTPRequestOperationManager.h" /> - <source-file src="src/ios/AFNetworking/AFHTTPRequestOperationManager.m" /> - - <header-file src="src/ios/AFNetworking/AFHTTPSessionManager.h" /> - <source-file src="src/ios/AFNetworking/AFHTTPSessionManager.m" /> - - <header-file src="src/ios/AFNetworking/AFNetworking.h" /> - - <header-file src="src/ios/AFNetworking/AFNetworkReachabilityManager.h" /> - <source-file src="src/ios/AFNetworking/AFNetworkReachabilityManager.m" /> - - <header-file src="src/ios/AFNetworking/AFSecurityPolicy.h" /> - <source-file src="src/ios/AFNetworking/AFSecurityPolicy.m" /> - - <header-file src="src/ios/AFNetworking/AFURLConnectionOperation.h" /> - <source-file src="src/ios/AFNetworking/AFURLConnectionOperation.m" /> - - <header-file src="src/ios/AFNetworking/AFURLRequestSerialization.h" /> - <source-file src="src/ios/AFNetworking/AFURLRequestSerialization.m" /> - - <header-file src="src/ios/AFNetworking/AFURLResponseSerialization.h" /> - <source-file src="src/ios/AFNetworking/AFURLResponseSerialization.m" /> - - <header-file src="src/ios/AFNetworking/AFURLSessionManager.h" /> - <source-file src="src/ios/AFNetworking/AFURLSessionManager.m" /> - - <framework src="Security.framework" /> - <framework src="SystemConfiguration.framework" /> - </platform> - - <!--android --> - <platform name="android"> - <config-file target="res/xml/config.xml" parent="/*"> - <feature name="CordovaHttpPlugin"> - <param name="android-package" value="com.synconset.CordovaHttpPlugin"/> - </feature> - </config-file> - - <source-file src="src/android/com/synconset/CordovaHTTP/CordovaHttp.java" target-dir="src/com/synconset" /> - <source-file src="src/android/com/synconset/CordovaHTTP/CordovaHttpGet.java" target-dir="src/com/synconset" /> - <source-file src="src/android/com/synconset/CordovaHTTP/CordovaHttpPost.java" target-dir="src/com/synconset" /> - <source-file src="src/android/com/synconset/CordovaHTTP/CordovaHttpUpload.java" target-dir="src/com/synconset" /> - <source-file src="src/android/com/synconset/CordovaHTTP/CordovaHttpDownload.java" target-dir="src/com/synconset" /> - <source-file src="src/android/com/synconset/CordovaHTTP/CordovaHttpPlugin.java" target-dir="src/com/synconset" /> - <source-file src="src/android/com/synconset/CordovaHTTP/HttpRequest.java" target-dir="src/com/github/kevinsawicki/http" /> - </platform> -</plugin> diff --git a/plugins/com.synconset.cordovaHTTP/src/android/com/synconset/CordovaHTTP/CordovaHttp.java b/plugins/com.synconset.cordovaHTTP/src/android/com/synconset/CordovaHTTP/CordovaHttp.java deleted file mode 100644 index afb85a06..00000000 --- a/plugins/com.synconset.cordovaHTTP/src/android/com/synconset/CordovaHTTP/CordovaHttp.java +++ /dev/null @@ -1,106 +0,0 @@ -/** - * A HTTP plugin for Cordova / Phonegap - */ -package com.synconset; - -import org.apache.cordova.CallbackContext; - -import org.json.JSONException; -import org.json.JSONObject; - -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.BufferedReader; -import java.util.Map; -import java.util.concurrent.atomic.AtomicBoolean; - -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLConnection; - -import javax.net.ssl.HttpsURLConnection; -import javax.net.ssl.SSLContext; -import javax.net.ssl.HostnameVerifier; - -import java.util.Iterator; - -import android.util.Log; - -import com.github.kevinsawicki.http.HttpRequest; - -public abstract class CordovaHttp { - protected static final String TAG = "CordovaHTTP"; - protected static final String CHARSET = "UTF-8"; - - private static AtomicBoolean sslPinning = new AtomicBoolean(false); - private static AtomicBoolean acceptAllCerts = new AtomicBoolean(false); - - private String urlString; - private Map<?, ?> params; - private Map<String, String> headers; - private CallbackContext callbackContext; - - public CordovaHttp(String urlString, Map<?, ?> params, Map<String, String> headers, CallbackContext callbackContext) { - this.urlString = urlString; - this.params = params; - this.headers = headers; - this.callbackContext = callbackContext; - } - - public static void enableSSLPinning(boolean enable) { - sslPinning.set(enable); - if (enable) { - acceptAllCerts.set(false); - } - } - - public static void acceptAllCerts(boolean accept) { - acceptAllCerts.set(accept); - if (accept) { - sslPinning.set(false); - } - } - - protected String getUrlString() { - return this.urlString; - } - - protected Map<?, ?> getParams() { - return this.params; - } - - protected Map<String, String> getHeaders() { - return this.headers; - } - - protected CallbackContext getCallbackContext() { - return this.callbackContext; - } - - protected HttpRequest setupSecurity(HttpRequest request) { - if (acceptAllCerts.get()) { - request.trustAllCerts(); - request.trustAllHosts(); - } - if (sslPinning.get()) { - request.pinToCerts(); - } - return request; - } - - protected void respondWithError(int status, String msg) { - try { - JSONObject response = new JSONObject(); - response.put("status", status); - response.put("error", msg); - this.callbackContext.error(response); - } catch (JSONException e) { - this.callbackContext.error(msg); - } - } - - protected void respondWithError(String msg) { - this.respondWithError(500, msg); - } -} diff --git a/plugins/com.synconset.cordovaHTTP/src/android/com/synconset/CordovaHTTP/CordovaHttpDownload.java b/plugins/com.synconset.cordovaHTTP/src/android/com/synconset/CordovaHTTP/CordovaHttpDownload.java deleted file mode 100644 index a1b78963..00000000 --- a/plugins/com.synconset.cordovaHTTP/src/android/com/synconset/CordovaHTTP/CordovaHttpDownload.java +++ /dev/null @@ -1,69 +0,0 @@ -/** - * A HTTP plugin for Cordova / Phonegap - */ -package com.synconset; - -import android.util.Log; - -import com.github.kevinsawicki.http.HttpRequest; -import com.github.kevinsawicki.http.HttpRequest.HttpRequestException; - -import java.io.File; -import java.net.UnknownHostException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Map; - -import javax.net.ssl.SSLHandshakeException; - -import org.apache.cordova.CallbackContext; -import org.apache.cordova.file.FileUtils; - -import org.json.JSONException; -import org.json.JSONObject; - -public class CordovaHttpDownload extends CordovaHttp implements Runnable { - private String filePath; - - public CordovaHttpDownload(String urlString, Map<?, ?> params, Map<String, String> headers, CallbackContext callbackContext, String filePath) { - super(urlString, params, headers, callbackContext); - this.filePath = filePath; - } - - @Override - public void run() { - try { - HttpRequest request = HttpRequest.get(this.getUrlString(), this.getParams(), true); - this.setupSecurity(request); - request.acceptCharset(CHARSET); - request.headers(this.getHeaders()); - int code = request.code(); - - JSONObject response = new JSONObject(); - response.put("status", code); - if (code >= 200 && code < 300) { - URI uri = new URI(filePath); - File file = new File(uri); - request.receive(file); - JSONObject fileEntry = FileUtils.getEntry(file); - response.put("file", fileEntry); - this.getCallbackContext().success(response); - } else { - response.put("error", "There was an error downloading the file"); - this.getCallbackContext().error(response); - } - } catch(URISyntaxException e) { - this.respondWithError("There was an error with the given filePath"); - } catch (JSONException e) { - this.respondWithError("There was an error generating the response"); - } catch (HttpRequestException e) { - if (e.getCause() instanceof UnknownHostException) { - this.respondWithError(0, "The host could not be resolved"); - } else if (e.getCause() instanceof SSLHandshakeException) { - this.respondWithError("SSL handshake failed"); - } else { - this.respondWithError("There was an error with the request"); - } - } - } -} diff --git a/plugins/com.synconset.cordovaHTTP/src/android/com/synconset/CordovaHTTP/CordovaHttpGet.java b/plugins/com.synconset.cordovaHTTP/src/android/com/synconset/CordovaHTTP/CordovaHttpGet.java deleted file mode 100644 index 1b37bf8c..00000000 --- a/plugins/com.synconset.cordovaHTTP/src/android/com/synconset/CordovaHTTP/CordovaHttpGet.java +++ /dev/null @@ -1,63 +0,0 @@ -/** - * A HTTP plugin for Cordova / Phonegap - */ -package com.synconset; - -import java.io.IOException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.UnknownHostException; -import java.util.Map; - -import javax.net.ssl.HttpsURLConnection; -import javax.net.ssl.SSLContext; -import javax.net.ssl.HostnameVerifier; - -import javax.net.ssl.SSLHandshakeException; - -import org.apache.cordova.CallbackContext; -import org.json.JSONException; -import org.json.JSONObject; - -import android.util.Log; - -import com.github.kevinsawicki.http.HttpRequest; -import com.github.kevinsawicki.http.HttpRequest.HttpRequestException; - -public class CordovaHttpGet extends CordovaHttp implements Runnable { - public CordovaHttpGet(String urlString, Map<?, ?> params, Map<String, String> headers, CallbackContext callbackContext) { - super(urlString, params, headers, callbackContext); - } - - @Override - public void run() { - try { - HttpRequest request = HttpRequest.get(this.getUrlString(), this.getParams(), true); - this.setupSecurity(request); - request.acceptCharset(CHARSET); - request.headers(this.getHeaders()); - int code = request.code(); - String body = request.body(CHARSET); - JSONObject response = new JSONObject(); - response.put("status", code); - if (code >= 200 && code < 300) { - response.put("data", body); - this.getCallbackContext().success(response); - } else { - response.put("error", body); - this.getCallbackContext().error(response); - } - } catch (JSONException e) { - this.respondWithError("There was an error generating the response"); - } catch (HttpRequestException e) { - if (e.getCause() instanceof UnknownHostException) { - this.respondWithError(0, "The host could not be resolved"); - } else if (e.getCause() instanceof SSLHandshakeException) { - this.respondWithError("SSL handshake failed"); - } else { - this.respondWithError("There was an error with the request"); - } - } - } -} diff --git a/plugins/com.synconset.cordovaHTTP/src/android/com/synconset/CordovaHTTP/CordovaHttpPlugin.java b/plugins/com.synconset.cordovaHTTP/src/android/com/synconset/CordovaHTTP/CordovaHttpPlugin.java deleted file mode 100644 index b2cf398f..00000000 --- a/plugins/com.synconset.cordovaHTTP/src/android/com/synconset/CordovaHTTP/CordovaHttpPlugin.java +++ /dev/null @@ -1,184 +0,0 @@ -/** - * A HTTP plugin for Cordova / Phonegap - */ -package com.synconset; - -import java.io.BufferedInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.HttpURLConnection; -import java.security.GeneralSecurityException; -import java.security.KeyStore; -import java.security.cert.Certificate; -import java.security.cert.CertificateException; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; -import java.util.Iterator; -import java.util.ArrayList; -import java.util.HashMap; - -import javax.net.ssl.HttpsURLConnection; -import javax.net.ssl.SSLContext; -import javax.net.ssl.TrustManagerFactory; -import javax.net.ssl.TrustManager; -import javax.net.ssl.HostnameVerifier; - -import org.apache.cordova.CallbackContext; -import org.apache.cordova.CordovaInterface; -import org.apache.cordova.CordovaPlugin; -import org.apache.cordova.CordovaWebView; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import android.content.res.AssetManager; -import android.util.Base64; -import android.util.Log; - -import com.github.kevinsawicki.http.HttpRequest; - -public class CordovaHttpPlugin extends CordovaPlugin { - private static final String TAG = "CordovaHTTP"; - - private HashMap<String, String> globalHeaders; - - @Override - public void initialize(CordovaInterface cordova, CordovaWebView webView) { - super.initialize(cordova, webView); - this.globalHeaders = new HashMap<String, String>(); - } - - @Override - public boolean execute(String action, final JSONArray args, final CallbackContext callbackContext) throws JSONException { - if (action.equals("get")) { - String urlString = args.getString(0); - JSONObject params = args.getJSONObject(1); - JSONObject headers = args.getJSONObject(2); - HashMap<?, ?> paramsMap = this.getMapFromJSONObject(params); - HashMap<String, String> headersMap = this.addToMap(this.globalHeaders, headers); - CordovaHttpGet get = new CordovaHttpGet(urlString, paramsMap, headersMap, callbackContext); - cordova.getThreadPool().execute(get); - } else if (action.equals("post")) { - String urlString = args.getString(0); - JSONObject params = args.getJSONObject(1); - JSONObject headers = args.getJSONObject(2); - HashMap<?, ?> paramsMap = this.getMapFromJSONObject(params); - HashMap<String, String> headersMap = this.addToMap(this.globalHeaders, headers); - CordovaHttpPost post = new CordovaHttpPost(urlString, paramsMap, headersMap, callbackContext); - cordova.getThreadPool().execute(post); - } else if (action.equals("useBasicAuth")) { - String username = args.getString(0); - String password = args.getString(1); - this.useBasicAuth(username, password); - callbackContext.success(); - } else if (action.equals("enableSSLPinning")) { - try { - boolean enable = args.getBoolean(0); - this.enableSSLPinning(enable); - callbackContext.success(); - } catch(Exception e) { - e.printStackTrace(); - callbackContext.error("There was an error setting up ssl pinning"); - } - } else if (action.equals("acceptAllCerts")) { - boolean accept = args.getBoolean(0); - CordovaHttp.acceptAllCerts(accept); - } else if (action.equals("setHeader")) { - String header = args.getString(0); - String value = args.getString(1); - this.setHeader(header, value); - callbackContext.success(); - } else if (action.equals("uploadFile")) { - String urlString = args.getString(0); - JSONObject params = args.getJSONObject(1); - JSONObject headers = args.getJSONObject(2); - HashMap<?, ?> paramsMap = this.getMapFromJSONObject(params); - HashMap<String, String> headersMap = this.addToMap(this.globalHeaders, headers); - String filePath = args.getString(3); - String name = args.getString(4); - CordovaHttpUpload upload = new CordovaHttpUpload(urlString, paramsMap, headersMap, callbackContext, filePath, name); - cordova.getThreadPool().execute(upload); - } else if (action.equals("downloadFile")) { - String urlString = args.getString(0); - JSONObject params = args.getJSONObject(1); - JSONObject headers = args.getJSONObject(2); - HashMap<?, ?> paramsMap = this.getMapFromJSONObject(params); - HashMap<String, String> headersMap = this.addToMap(this.globalHeaders, headers); - String filePath = args.getString(3); - CordovaHttpDownload download = new CordovaHttpDownload(urlString, paramsMap, headersMap, callbackContext, filePath); - cordova.getThreadPool().execute(download); - } else { - return false; - } - return true; - } - - private void useBasicAuth(String username, String password) { - String loginInfo = username + ":" + password; - loginInfo = "Basic " + Base64.encodeToString(loginInfo.getBytes(), Base64.NO_WRAP); - this.globalHeaders.put("Authorization", loginInfo); - } - - private void setHeader(String header, String value) { - this.globalHeaders.put(header, value); - } - - private void enableSSLPinning(boolean enable) throws GeneralSecurityException, IOException { - if (enable) { - AssetManager assetManager = cordova.getActivity().getAssets(); - String[] files = assetManager.list(""); - int index; - ArrayList<String> cerFiles = new ArrayList<String>(); - for (int i = 0; i < files.length; i++) { - index = files[i].lastIndexOf('.'); - if (index != -1) { - if (files[i].substring(index).equals(".cer")) { - cerFiles.add(files[i]); - } - } - } - - // scan the www/certificates folder for .cer files as well - files = assetManager.list("www/certificates"); - for (int i = 0; i < files.length; i++) { - index = files[i].lastIndexOf('.'); - if (index != -1) { - if (files[i].substring(index).equals(".cer")) { - cerFiles.add("www/certificates/" + files[i]); - } - } - } - - for (int i = 0; i < cerFiles.size(); i++) { - InputStream in = cordova.getActivity().getAssets().open(cerFiles.get(i)); - InputStream caInput = new BufferedInputStream(in); - HttpRequest.addCert(caInput); - } - CordovaHttp.enableSSLPinning(true); - } else { - CordovaHttp.enableSSLPinning(false); - } - } - - private HashMap<String, String> addToMap(HashMap<String, String> map, JSONObject object) throws JSONException { - HashMap<String, String> newMap = (HashMap<String, String>)map.clone(); - Iterator<?> i = object.keys(); - - while (i.hasNext()) { - String key = (String)i.next(); - newMap.put(key, object.getString(key)); - } - return newMap; - } - - private HashMap<String, Object> getMapFromJSONObject(JSONObject object) throws JSONException { - HashMap<String, Object> map = new HashMap<String, Object>(); - Iterator<?> i = object.keys(); - - while(i.hasNext()) { - String key = (String)i.next(); - map.put(key, object.get(key)); - } - return map; - } -} diff --git a/plugins/com.synconset.cordovaHTTP/src/android/com/synconset/CordovaHTTP/CordovaHttpPost.java b/plugins/com.synconset.cordovaHTTP/src/android/com/synconset/CordovaHTTP/CordovaHttpPost.java deleted file mode 100644 index c0ae17f3..00000000 --- a/plugins/com.synconset.cordovaHTTP/src/android/com/synconset/CordovaHTTP/CordovaHttpPost.java +++ /dev/null @@ -1,56 +0,0 @@ -/** - * A HTTP plugin for Cordova / Phonegap - */ -package com.synconset; - -import java.net.UnknownHostException; -import java.util.Map; - -import org.apache.cordova.CallbackContext; -import org.json.JSONException; -import org.json.JSONObject; - -import javax.net.ssl.SSLHandshakeException; - -import android.util.Log; - -import com.github.kevinsawicki.http.HttpRequest; -import com.github.kevinsawicki.http.HttpRequest.HttpRequestException; - -public class CordovaHttpPost extends CordovaHttp implements Runnable { - public CordovaHttpPost(String urlString, Map<?, ?> params, Map<String, String> headers, CallbackContext callbackContext) { - super(urlString, params, headers, callbackContext); - } - - @Override - public void run() { - try { - HttpRequest request = HttpRequest.post(this.getUrlString()); - this.setupSecurity(request); - request.acceptCharset(CHARSET); - request.headers(this.getHeaders()); - request.form(this.getParams()); - int code = request.code(); - String body = request.body(CHARSET); - JSONObject response = new JSONObject(); - response.put("status", code); - if (code >= 200 && code < 300) { - response.put("data", body); - this.getCallbackContext().success(response); - } else { - response.put("error", body); - this.getCallbackContext().error(response); - } - } catch (JSONException e) { - this.respondWithError("There was an error generating the response"); - } catch (HttpRequestException e) { - if (e.getCause() instanceof UnknownHostException) { - this.respondWithError(0, "The host could not be resolved"); - } else if (e.getCause() instanceof SSLHandshakeException) { - this.respondWithError("SSL handshake failed"); - } else { - this.respondWithError("There was an error with the request"); - } - } - } -} diff --git a/plugins/com.synconset.cordovaHTTP/src/android/com/synconset/CordovaHTTP/CordovaHttpUpload.java b/plugins/com.synconset.cordovaHTTP/src/android/com/synconset/CordovaHTTP/CordovaHttpUpload.java deleted file mode 100644 index 622a52a5..00000000 --- a/plugins/com.synconset.cordovaHTTP/src/android/com/synconset/CordovaHTTP/CordovaHttpUpload.java +++ /dev/null @@ -1,95 +0,0 @@ -/** - * A HTTP plugin for Cordova / Phonegap - */ -package com.synconset; - -import java.io.File; -import java.net.UnknownHostException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Iterator; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - -import org.apache.cordova.CallbackContext; -import org.json.JSONException; -import org.json.JSONObject; - -import javax.net.ssl.SSLHandshakeException; - -import android.util.Log; -import android.webkit.MimeTypeMap; - -import com.github.kevinsawicki.http.HttpRequest; -import com.github.kevinsawicki.http.HttpRequest.HttpRequestException; - -public class CordovaHttpUpload extends CordovaHttp implements Runnable { - private String filePath; - private String name; - - public CordovaHttpUpload(String urlString, Map<?, ?> params, Map<String, String> headers, CallbackContext callbackContext, String filePath, String name) { - super(urlString, params, headers, callbackContext); - this.filePath = filePath; - this.name = name; - } - - @Override - public void run() { - try { - HttpRequest request = HttpRequest.post(this.getUrlString()); - this.setupSecurity(request); - request.acceptCharset(CHARSET); - request.headers(this.getHeaders()); - URI uri = new URI(filePath); - int index = filePath.lastIndexOf('/'); - String filename = filePath.substring(index + 1); - index = filePath.lastIndexOf('.'); - String ext = filePath.substring(index + 1); - MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton(); - String mimeType = mimeTypeMap.getMimeTypeFromExtension(ext); - request.part(this.name, filename, mimeType, new File(uri)); - - Set<?> set = (Set<?>)this.getParams().entrySet(); - Iterator<?> i = set.iterator(); - while (i.hasNext()) { - Entry<?, ?> e = (Entry<?, ?>)i.next(); - String key = (String)e.getKey(); - Object value = e.getValue(); - if (value instanceof Number) { - request.part(key, (Number)value); - } else if (value instanceof String) { - request.part(key, (String)value); - } else { - this.respondWithError("All parameters must be Numbers or Strings"); - return; - } - } - - int code = request.code(); - String body = request.body(CHARSET); - - JSONObject response = new JSONObject(); - response.put("status", code); - if (code >= 200 && code < 300) { - response.put("data", body); - this.getCallbackContext().success(response); - } else { - response.put("error", body); - this.getCallbackContext().error(response); - } - } catch (URISyntaxException e) { - this.respondWithError("There was an error loading the file"); - } catch (JSONException e) { - this.respondWithError("There was an error generating the response"); - } catch (HttpRequestException e) { - if (e.getCause() instanceof UnknownHostException) { - this.respondWithError(0, "The host could not be resolved"); - } else if (e.getCause() instanceof SSLHandshakeException) { - this.respondWithError("SSL handshake failed"); - } else { - this.respondWithError("There was an error with the request"); - } - } - } -} diff --git a/plugins/com.synconset.cordovaHTTP/src/android/com/synconset/CordovaHTTP/HttpRequest.java b/plugins/com.synconset.cordovaHTTP/src/android/com/synconset/CordovaHTTP/HttpRequest.java deleted file mode 100644 index f8dcf68c..00000000 --- a/plugins/com.synconset.cordovaHTTP/src/android/com/synconset/CordovaHTTP/HttpRequest.java +++ /dev/null @@ -1,3309 +0,0 @@ -/* - * Copyright (c) 2014 Kevin Sawicki <kevinsawicki@gmail.com> - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to - * deal in the Software without restriction, including without limitation the - * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or - * sell copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS - * IN THE SOFTWARE. - */ -package com.github.kevinsawicki.http; - -import static java.net.HttpURLConnection.HTTP_BAD_REQUEST; -import static java.net.HttpURLConnection.HTTP_CREATED; -import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR; -import static java.net.HttpURLConnection.HTTP_NO_CONTENT; -import static java.net.HttpURLConnection.HTTP_NOT_FOUND; -import static java.net.HttpURLConnection.HTTP_NOT_MODIFIED; -import static java.net.HttpURLConnection.HTTP_OK; -import static java.net.Proxy.Type.HTTP; - -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.Closeable; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.Flushable; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.PrintStream; -import java.io.Reader; -import java.io.UnsupportedEncodingException; -import java.io.Writer; -import java.net.HttpURLConnection; -import java.net.InetSocketAddress; -import java.net.MalformedURLException; -import java.net.Proxy; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; -import java.net.URLEncoder; -import java.nio.ByteBuffer; -import java.nio.CharBuffer; -import java.nio.charset.Charset; -import java.nio.charset.CharsetEncoder; -import java.security.AccessController; -import java.security.GeneralSecurityException; -import java.security.KeyStore; -import java.security.PrivilegedAction; -import java.security.SecureRandom; -import java.security.cert.Certificate; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.concurrent.Callable; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicReference; -import java.util.zip.GZIPInputStream; - -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.HttpsURLConnection; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSession; -import javax.net.ssl.SSLSocketFactory; -import javax.net.ssl.TrustManager; -import javax.net.ssl.TrustManagerFactory; -import javax.net.ssl.X509TrustManager; - -/** - * A fluid interface for making HTTP requests using an underlying - * {@link HttpURLConnection} (or sub-class). - * <p> - * Each instance supports making a single request and cannot be reused for - * further requests. - */ -public class HttpRequest { - - /** - * 'UTF-8' charset name - */ - public static final String CHARSET_UTF8 = "UTF-8"; - - /** - * 'application/x-www-form-urlencoded' content type header value - */ - public static final String CONTENT_TYPE_FORM = "application/x-www-form-urlencoded"; - - /** - * 'application/json' content type header value - */ - public static final String CONTENT_TYPE_JSON = "application/json"; - - /** - * 'gzip' encoding header value - */ - public static final String ENCODING_GZIP = "gzip"; - - /** - * 'Accept' header name - */ - public static final String HEADER_ACCEPT = "Accept"; - - /** - * 'Accept-Charset' header name - */ - public static final String HEADER_ACCEPT_CHARSET = "Accept-Charset"; - - /** - * 'Accept-Encoding' header name - */ - public static final String HEADER_ACCEPT_ENCODING = "Accept-Encoding"; - - /** - * 'Authorization' header name - */ - public static final String HEADER_AUTHORIZATION = "Authorization"; - - /** - * 'Cache-Control' header name - */ - public static final String HEADER_CACHE_CONTROL = "Cache-Control"; - - /** - * 'Content-Encoding' header name - */ - public static final String HEADER_CONTENT_ENCODING = "Content-Encoding"; - - /** - * 'Content-Length' header name - */ - public static final String HEADER_CONTENT_LENGTH = "Content-Length"; - - /** - * 'Content-Type' header name - */ - public static final String HEADER_CONTENT_TYPE = "Content-Type"; - - /** - * 'Date' header name - */ - public static final String HEADER_DATE = "Date"; - - /** - * 'ETag' header name - */ - public static final String HEADER_ETAG = "ETag"; - - /** - * 'Expires' header name - */ - public static final String HEADER_EXPIRES = "Expires"; - - /** - * 'If-None-Match' header name - */ - public static final String HEADER_IF_NONE_MATCH = "If-None-Match"; - - /** - * 'Last-Modified' header name - */ - public static final String HEADER_LAST_MODIFIED = "Last-Modified"; - - /** - * 'Location' header name - */ - public static final String HEADER_LOCATION = "Location"; - - /** - * 'Proxy-Authorization' header name - */ - public static final String HEADER_PROXY_AUTHORIZATION = "Proxy-Authorization"; - - /** - * 'Referer' header name - */ - public static final String HEADER_REFERER = "Referer"; - - /** - * 'Server' header name - */ - public static final String HEADER_SERVER = "Server"; - - /** - * 'User-Agent' header name - */ - public static final String HEADER_USER_AGENT = "User-Agent"; - - /** - * 'DELETE' request method - */ - public static final String METHOD_DELETE = "DELETE"; - - /** - * 'GET' request method - */ - public static final String METHOD_GET = "GET"; - - /** - * 'HEAD' request method - */ - public static final String METHOD_HEAD = "HEAD"; - - /** - * 'OPTIONS' options method - */ - public static final String METHOD_OPTIONS = "OPTIONS"; - - /** - * 'POST' request method - */ - public static final String METHOD_POST = "POST"; - - /** - * 'PUT' request method - */ - public static final String METHOD_PUT = "PUT"; - - /** - * 'TRACE' request method - */ - public static final String METHOD_TRACE = "TRACE"; - - /** - * 'charset' header value parameter - */ - public static final String PARAM_CHARSET = "charset"; - - private static final String BOUNDARY = "00content0boundary00"; - - private static final String CONTENT_TYPE_MULTIPART = "multipart/form-data; boundary=" - + BOUNDARY; - - private static final String CRLF = "\r\n"; - - private static final String[] EMPTY_STRINGS = new String[0]; - - private static SSLSocketFactory PINNED_FACTORY; - - private static SSLSocketFactory TRUSTED_FACTORY; - - private static ArrayList<Certificate> PINNED_CERTS; - - private static HostnameVerifier TRUSTED_VERIFIER; - - private static String getValidCharset(final String charset) { - if (charset != null && charset.length() > 0) - return charset; - else - return CHARSET_UTF8; - } - - private static SSLSocketFactory getPinnedFactory() - throws HttpRequestException { - if (PINNED_FACTORY != null) { - return PINNED_FACTORY; - } else { - IOException e = new IOException("You must add at least 1 certificate in order to pin to certificates"); - throw new HttpRequestException(e); - } - } - - private static SSLSocketFactory getTrustedFactory() - throws HttpRequestException { - if (TRUSTED_FACTORY == null) { - final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { - - public X509Certificate[] getAcceptedIssuers() { - return new X509Certificate[0]; - } - - public void checkClientTrusted(X509Certificate[] chain, String authType) { - // Intentionally left blank - } - - public void checkServerTrusted(X509Certificate[] chain, String authType) { - // Intentionally left blank - } - } }; - try { - SSLContext context = SSLContext.getInstance("TLS"); - context.init(null, trustAllCerts, new SecureRandom()); - TRUSTED_FACTORY = context.getSocketFactory(); - } catch (GeneralSecurityException e) { - IOException ioException = new IOException( - "Security exception configuring SSL context"); - ioException.initCause(e); - throw new HttpRequestException(ioException); - } - } - - return TRUSTED_FACTORY; - } - - private static HostnameVerifier getTrustedVerifier() { - if (TRUSTED_VERIFIER == null) - TRUSTED_VERIFIER = new HostnameVerifier() { - - public boolean verify(String hostname, SSLSession session) { - return true; - } - }; - - return TRUSTED_VERIFIER; - } - - private static StringBuilder addPathSeparator(final String baseUrl, - final StringBuilder result) { - // Add trailing slash if the base URL doesn't have any path segments. - // - // The following test is checking for the last slash not being part of - // the protocol to host separator: '://'. - if (baseUrl.indexOf(':') + 2 == baseUrl.lastIndexOf('/')) - result.append('/'); - return result; - } - - private static StringBuilder addParamPrefix(final String baseUrl, - final StringBuilder result) { - // Add '?' if missing and add '&' if params already exist in base url - final int queryStart = baseUrl.indexOf('?'); - final int lastChar = result.length() - 1; - if (queryStart == -1) - result.append('?'); - else if (queryStart < lastChar && baseUrl.charAt(lastChar) != '&') - result.append('&'); - return result; - } - - /** - * Creates {@link HttpURLConnection HTTP connections} for - * {@link URL urls}. - */ - public interface ConnectionFactory { - /** - * Open an {@link HttpURLConnection} for the specified {@link URL}. - * - * @throws IOException - */ - HttpURLConnection create(URL url) throws IOException; - - /** - * Open an {@link HttpURLConnection} for the specified {@link URL} - * and {@link Proxy}. - * - * @throws IOException - */ - HttpURLConnection create(URL url, Proxy proxy) throws IOException; - - /** - * A {@link ConnectionFactory} which uses the built-in - * {@link URL#openConnection()} - */ - ConnectionFactory DEFAULT = new ConnectionFactory() { - public HttpURLConnection create(URL url) throws IOException { - return (HttpURLConnection) url.openConnection(); - } - - public HttpURLConnection create(URL url, Proxy proxy) throws IOException { - return (HttpURLConnection) url.openConnection(proxy); - } - }; - } - - private static ConnectionFactory CONNECTION_FACTORY = ConnectionFactory.DEFAULT; - - /** - * Specify the {@link ConnectionFactory} used to create new requests. - */ - public static void setConnectionFactory(final ConnectionFactory connectionFactory) { - if (connectionFactory == null) - CONNECTION_FACTORY = ConnectionFactory.DEFAULT; - else - CONNECTION_FACTORY = connectionFactory; - } - - - /** - * Add a certificate to test against when using ssl pinning. - * - * @param ca - * The Certificate to add - * @throws GeneralSecurityException - * @throws IOException - */ - public static void addCert(Certificate ca) throws GeneralSecurityException, IOException { - if (PINNED_CERTS == null) { - PINNED_CERTS = new ArrayList<Certificate>(); - } - PINNED_CERTS.add(ca); - String keyStoreType = KeyStore.getDefaultType(); - KeyStore keyStore = KeyStore.getInstance(keyStoreType); - keyStore.load(null, null); - - for (int i = 0; i < PINNED_CERTS.size(); i++) { - keyStore.setCertificateEntry("CA" + i, PINNED_CERTS.get(i)); - } - - // Create a TrustManager that trusts the CAs in our KeyStore - String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); - TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); - tmf.init(keyStore); - - // Create an SSLContext that uses our TrustManager - SSLContext sslContext = SSLContext.getInstance("TLS"); - sslContext.init(null, tmf.getTrustManagers(), null); - PINNED_FACTORY = sslContext.getSocketFactory(); - } - - /** - * Add a certificate to test against when using ssl pinning. - * - * @param in - * An InputStream to read a certificate from - * @throws GeneralSecurityException - * @throws IOException - */ - public static void addCert(InputStream in) throws GeneralSecurityException, IOException { - CertificateFactory cf = CertificateFactory.getInstance("X.509"); - Certificate ca; - try { - ca = cf.generateCertificate(in); - addCert(ca); - } finally { - in.close(); - } - } - - /** - * Callback interface for reporting upload progress for a request. - */ - public interface UploadProgress { - /** - * Callback invoked as data is uploaded by the request. - * - * @param uploaded The number of bytes already uploaded - * @param total The total number of bytes that will be uploaded or -1 if - * the length is unknown. - */ - void onUpload(long uploaded, long total); - - UploadProgress DEFAULT = new UploadProgress() { - public void onUpload(long uploaded, long total) { - } - }; - } - - /** - * <p> - * Encodes and decodes to and from Base64 notation. - * </p> - * <p> - * I am placing this code in the Public Domain. Do with it as you will. This - * software comes with no guarantees or warranties but with plenty of - * well-wishing instead! Please visit <a - * href="http://iharder.net/base64">http://iharder.net/base64</a> periodically - * to check for updates or to contribute improvements. - * </p> - * - * @author Robert Harder - * @author rob@iharder.net - * @version 2.3.7 - */ - public static class Base64 { - - /** The equals sign (=) as a byte. */ - private final static byte EQUALS_SIGN = (byte) '='; - - /** Preferred encoding. */ - private final static String PREFERRED_ENCODING = "US-ASCII"; - - /** The 64 valid Base64 values. */ - private final static byte[] _STANDARD_ALPHABET = { (byte) 'A', (byte) 'B', - (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', (byte) 'H', - (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', - (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', - (byte) 'U', (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', - (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', - (byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', - (byte) 'm', (byte) 'n', (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', - (byte) 's', (byte) 't', (byte) 'u', (byte) 'v', (byte) 'w', (byte) 'x', - (byte) 'y', (byte) 'z', (byte) '0', (byte) '1', (byte) '2', (byte) '3', - (byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', - (byte) '+', (byte) '/' }; - - /** Defeats instantiation. */ - private Base64() { - } - - /** - * <p> - * Encodes up to three bytes of the array <var>source</var> and writes the - * resulting four Base64 bytes to <var>destination</var>. The source and - * destination arrays can be manipulated anywhere along their length by - * specifying <var>srcOffset</var> and <var>destOffset</var>. This method - * does not check to make sure your arrays are large enough to accomodate - * <var>srcOffset</var> + 3 for the <var>source</var> array or - * <var>destOffset</var> + 4 for the <var>destination</var> array. The - * actual number of significant bytes in your array is given by - * <var>numSigBytes</var>. - * </p> - * <p> - * This is the lowest level of the encoding methods with all possible - * parameters. - * </p> - * - * @param source - * the array to convert - * @param srcOffset - * the index where conversion begins - * @param numSigBytes - * the number of significant bytes in your array - * @param destination - * the array to hold the conversion - * @param destOffset - * the index where output will be put - * @return the <var>destination</var> array - * @since 1.3 - */ - private static byte[] encode3to4(byte[] source, int srcOffset, - int numSigBytes, byte[] destination, int destOffset) { - - byte[] ALPHABET = _STANDARD_ALPHABET; - - int inBuff = (numSigBytes > 0 ? ((source[srcOffset] << 24) >>> 8) : 0) - | (numSigBytes > 1 ? ((source[srcOffset + 1] << 24) >>> 16) : 0) - | (numSigBytes > 2 ? ((source[srcOffset + 2] << 24) >>> 24) : 0); - - switch (numSigBytes) { - case 3: - destination[destOffset] = ALPHABET[(inBuff >>> 18)]; - destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f]; - destination[destOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3f]; - destination[destOffset + 3] = ALPHABET[(inBuff) & 0x3f]; - return destination; - - case 2: - destination[destOffset] = ALPHABET[(inBuff >>> 18)]; - destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f]; - destination[destOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3f]; - destination[destOffset + 3] = EQUALS_SIGN; - return destination; - - case 1: - destination[destOffset] = ALPHABET[(inBuff >>> 18)]; - destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f]; - destination[destOffset + 2] = EQUALS_SIGN; - destination[destOffset + 3] = EQUALS_SIGN; - return destination; - - default: - return destination; - } - } - - /** - * Encode string as a byte array in Base64 annotation. - * - * @param string - * @return The Base64-encoded data as a string - */ - public static String encode(String string) { - byte[] bytes; - try { - bytes = string.getBytes(PREFERRED_ENCODING); - } catch (UnsupportedEncodingException e) { - bytes = string.getBytes(); - } - return encodeBytes(bytes); - } - - /** - * Encodes a byte array into Base64 notation. - * - * @param source - * The data to convert - * @return The Base64-encoded data as a String - * @throws NullPointerException - * if source array is null - * @throws IllegalArgumentException - * if source array, offset, or length are invalid - * @since 2.0 - */ - public static String encodeBytes(byte[] source) { - return encodeBytes(source, 0, source.length); - } - - /** - * Encodes a byte array into Base64 notation. - * - * @param source - * The data to convert - * @param off - * Offset in array where conversion should begin - * @param len - * Length of data to convert - * @return The Base64-encoded data as a String - * @throws NullPointerException - * if source array is null - * @throws IllegalArgumentException - * if source array, offset, or length are invalid - * @since 2.0 - */ - public static String encodeBytes(byte[] source, int off, int len) { - byte[] encoded = encodeBytesToBytes(source, off, len); - try { - return new String(encoded, PREFERRED_ENCODING); - } catch (UnsupportedEncodingException uue) { - return new String(encoded); - } - } - - /** - * Similar to {@link #encodeBytes(byte[], int, int)} but returns a byte - * array instead of instantiating a String. This is more efficient if you're - * working with I/O streams and have large data sets to encode. - * - * - * @param source - * The data to convert - * @param off - * Offset in array where conversion should begin - * @param len - * Length of data to convert - * @return The Base64-encoded data as a String if there is an error - * @throws NullPointerException - * if source array is null - * @throws IllegalArgumentException - * if source array, offset, or length are invalid - * @since 2.3.1 - */ - public static byte[] encodeBytesToBytes(byte[] source, int off, int len) { - - if (source == null) - throw new NullPointerException("Cannot serialize a null array."); - - if (off < 0) - throw new IllegalArgumentException("Cannot have negative offset: " - + off); - - if (len < 0) - throw new IllegalArgumentException("Cannot have length offset: " + len); - - if (off + len > source.length) - throw new IllegalArgumentException( - String - .format( - "Cannot have offset of %d and length of %d with array of length %d", - off, len, source.length)); - - // Bytes needed for actual encoding - int encLen = (len / 3) * 4 + (len % 3 > 0 ? 4 : 0); - - byte[] outBuff = new byte[encLen]; - - int d = 0; - int e = 0; - int len2 = len - 2; - for (; d < len2; d += 3, e += 4) - encode3to4(source, d + off, 3, outBuff, e); - - if (d < len) { - encode3to4(source, d + off, len - d, outBuff, e); - e += 4; - } - - if (e <= outBuff.length - 1) { - byte[] finalOut = new byte[e]; - System.arraycopy(outBuff, 0, finalOut, 0, e); - return finalOut; - } else - return outBuff; - } - } - - /** - * HTTP request exception whose cause is always an {@link IOException} - */ - public static class HttpRequestException extends RuntimeException { - - private static final long serialVersionUID = -1170466989781746231L; - - /** - * Create a new HttpRequestException with the given cause - * - * @param cause - */ - public HttpRequestException(final IOException cause) { - super(cause); - } - - /** - * Get {@link IOException} that triggered this request exception - * - * @return {@link IOException} cause - */ - @Override - public IOException getCause() { - return (IOException) super.getCause(); - } - } - - /** - * Operation that handles executing a callback once complete and handling - * nested exceptions - * - * @param <V> - */ - protected static abstract class Operation<V> implements Callable<V> { - - /** - * Run operation - * - * @return result - * @throws HttpRequestException - * @throws IOException - */ - protected abstract V run() throws HttpRequestException, IOException; - - /** - * Operation complete callback - * - * @throws IOException - */ - protected abstract void done() throws IOException; - - public V call() throws HttpRequestException { - boolean thrown = false; - try { - return run(); - } catch (HttpRequestException e) { - thrown = true; - throw e; - } catch (IOException e) { - thrown = true; - throw new HttpRequestException(e); - } finally { - try { - done(); - } catch (IOException e) { - if (!thrown) - throw new HttpRequestException(e); - } - } - } - } - - /** - * Class that ensures a {@link Closeable} gets closed with proper exception - * handling. - * - * @param <V> - */ - protected static abstract class CloseOperation<V> extends Operation<V> { - - private final Closeable closeable; - - private final boolean ignoreCloseExceptions; - - /** - * Create closer for operation - * - * @param closeable - * @param ignoreCloseExceptions - */ - protected CloseOperation(final Closeable closeable, - final boolean ignoreCloseExceptions) { - this.closeable = closeable; - this.ignoreCloseExceptions = ignoreCloseExceptions; - } - - @Override - protected void done() throws IOException { - if (closeable instanceof Flushable) - ((Flushable) closeable).flush(); - if (ignoreCloseExceptions) - try { - closeable.close(); - } catch (IOException e) { - // Ignored - } - else - closeable.close(); - } - } - - /** - * Class that and ensures a {@link Flushable} gets flushed with proper - * exception handling. - * - * @param <V> - */ - protected static abstract class FlushOperation<V> extends Operation<V> { - - private final Flushable flushable; - - /** - * Create flush operation - * - * @param flushable - */ - protected FlushOperation(final Flushable flushable) { - this.flushable = flushable; - } - - @Override - protected void done() throws IOException { - flushable.flush(); - } - } - - /** - * Request output stream - */ - public static class RequestOutputStream extends BufferedOutputStream { - - private final CharsetEncoder encoder; - - /** - * Create request output stream - * - * @param stream - * @param charset - * @param bufferSize - */ - public RequestOutputStream(final OutputStream stream, final String charset, - final int bufferSize) { - super(stream, bufferSize); - - encoder = Charset.forName(getValidCharset(charset)).newEncoder(); - } - - /** - * Write string to stream - * - * @param value - * @return this stream - * @throws IOException - */ - public RequestOutputStream write(final String value) throws IOException { - final ByteBuffer bytes = encoder.encode(CharBuffer.wrap(value)); - - super.write(bytes.array(), 0, bytes.limit()); - - return this; - } - } - - /** - * Encode the given URL as an ASCII {@link String} - * <p> - * This method ensures the path and query segments of the URL are properly - * encoded such as ' ' characters being encoded to '%20' or any UTF-8 - * characters that are non-ASCII. No encoding of URLs is done by default by - * the {@link HttpRequest} constructors and so if URL encoding is needed this - * method should be called before calling the {@link HttpRequest} constructor. - * - * @param url - * @return encoded URL - * @throws HttpRequestException - */ - public static String encode(final CharSequence url) - throws HttpRequestException { - URL parsed; - try { - parsed = new URL(url.toString()); - } catch (IOException e) { - throw new HttpRequestException(e); - } - - String host = parsed.getHost(); - int port = parsed.getPort(); - if (port != -1) - host = host + ':' + Integer.toString(port); - - try { - String encoded = new URI(parsed.getProtocol(), host, parsed.getPath(), - parsed.getQuery(), null).toASCIIString(); - int paramsStart = encoded.indexOf('?'); - if (paramsStart > 0 && paramsStart + 1 < encoded.length()) - encoded = encoded.substring(0, paramsStart + 1) - + encoded.substring(paramsStart + 1).replace("+", "%2B"); - return encoded; - } catch (URISyntaxException e) { - IOException io = new IOException("Parsing URI failed"); - io.initCause(e); - throw new HttpRequestException(io); - } - } - - /** - * Append given map as query parameters to the base URL - * <p> - * Each map entry's key will be a parameter name and the value's - * {@link Object#toString()} will be the parameter value. - * - * @param url - * @param params - * @return URL with appended query params - */ - public static String append(final CharSequence url, final Map<?, ?> params) { - final String baseUrl = url.toString(); - if (params == null || params.isEmpty()) - return baseUrl; - - final StringBuilder result = new StringBuilder(baseUrl); - - addPathSeparator(baseUrl, result); - addParamPrefix(baseUrl, result); - - Entry<?, ?> entry; - Object value; - Iterator<?> iterator = params.entrySet().iterator(); - entry = (Entry<?, ?>) iterator.next(); - result.append(entry.getKey().toString()); - result.append('='); - value = entry.getValue(); - if (value != null) - result.append(value); - - while (iterator.hasNext()) { - result.append('&'); - entry = (Entry<?, ?>) iterator.next(); - result.append(entry.getKey().toString()); - result.append('='); - value = entry.getValue(); - if (value != null) - result.append(value); - } - - return result.toString(); - } - - /** - * Append given name/value pairs as query parameters to the base URL - * <p> - * The params argument is interpreted as a sequence of name/value pairs so the - * given number of params must be divisible by 2. - * - * @param url - * @param params - * name/value pairs - * @return URL with appended query params - */ - public static String append(final CharSequence url, final Object... params) { - final String baseUrl = url.toString(); - if (params == null || params.length == 0) - return baseUrl; - - if (params.length % 2 != 0) - throw new IllegalArgumentException( - "Must specify an even number of parameter names/values"); - - final StringBuilder result = new StringBuilder(baseUrl); - - addPathSeparator(baseUrl, result); - addParamPrefix(baseUrl, result); - - Object value; - result.append(params[0]); - result.append('='); - value = params[1]; - if (value != null) - result.append(value); - - for (int i = 2; i < params.length; i += 2) { - result.append('&'); - result.append(params[i]); - result.append('='); - value = params[i + 1]; - if (value != null) - result.append(value); - } - - return result.toString(); - } - - /** - * Start a 'GET' request to the given URL - * - * @param url - * @return request - * @throws HttpRequestException - */ - public static HttpRequest get(final CharSequence url) - throws HttpRequestException { - return new HttpRequest(url, METHOD_GET); - } - - /** - * Start a 'GET' request to the given URL - * - * @param url - * @return request - * @throws HttpRequestException - */ - public static HttpRequest get(final URL url) throws HttpRequestException { - return new HttpRequest(url, METHOD_GET); - } - - /** - * Start a 'GET' request to the given URL along with the query params - * - * @param baseUrl - * @param params - * The query parameters to include as part of the baseUrl - * @param encode - * true to encode the full URL - * - * @see #append(CharSequence, Map) - * @see #encode(CharSequence) - * - * @return request - */ - public static HttpRequest get(final CharSequence baseUrl, - final Map<?, ?> params, final boolean encode) { - String url = append(baseUrl, params); - return get(encode ? encode(url) : url); - } - - /** - * Start a 'GET' request to the given URL along with the query params - * - * @param baseUrl - * @param encode - * true to encode the full URL - * @param params - * the name/value query parameter pairs to include as part of the - * baseUrl - * - * @see #append(CharSequence, String...) - * @see #encode(CharSequence) - * - * @return request - */ - public static HttpRequest get(final CharSequence baseUrl, - final boolean encode, final Object... params) { - String url = append(baseUrl, params); - return get(encode ? encode(url) : url); - } - - /** - * Start a 'POST' request to the given URL - * - * @param url - * @return request - * @throws HttpRequestException - */ - public static HttpRequest post(final CharSequence url) - throws HttpRequestException { - return new HttpRequest(url, METHOD_POST); - } - - /** - * Start a 'POST' request to the given URL - * - * @param url - * @return request - * @throws HttpRequestException - */ - public static HttpRequest post(final URL url) throws HttpRequestException { - return new HttpRequest(url, METHOD_POST); - } - - /** - * Start a 'POST' request to the given URL along with the query params - * - * @param baseUrl - * @param params - * the query parameters to include as part of the baseUrl - * @param encode - * true to encode the full URL - * - * @see #append(CharSequence, Map) - * @see #encode(CharSequence) - * - * @return request - */ - public static HttpRequest post(final CharSequence baseUrl, - final Map<?, ?> params, final boolean encode) { - String url = append(baseUrl, params); - return post(encode ? encode(url) : url); - } - - /** - * Start a 'POST' request to the given URL along with the query params - * - * @param baseUrl - * @param encode - * true to encode the full URL - * @param params - * the name/value query parameter pairs to include as part of the - * baseUrl - * - * @see #append(CharSequence, String...) - * @see #encode(CharSequence) - * - * @return request - */ - public static HttpRequest post(final CharSequence baseUrl, - final boolean encode, final Object... params) { - String url = append(baseUrl, params); - return post(encode ? encode(url) : url); - } - - /** - * Start a 'PUT' request to the given URL - * - * @param url - * @return request - * @throws HttpRequestException - */ - public static HttpRequest put(final CharSequence url) - throws HttpRequestException { - return new HttpRequest(url, METHOD_PUT); - } - - /** - * Start a 'PUT' request to the given URL - * - * @param url - * @return request - * @throws HttpRequestException - */ - public static HttpRequest put(final URL url) throws HttpRequestException { - return new HttpRequest(url, METHOD_PUT); - } - - /** - * Start a 'PUT' request to the given URL along with the query params - * - * @param baseUrl - * @param params - * the query parameters to include as part of the baseUrl - * @param encode - * true to encode the full URL - * - * @see #append(CharSequence, Map) - * @see #encode(CharSequence) - * - * @return request - */ - public static HttpRequest put(final CharSequence baseUrl, - final Map<?, ?> params, final boolean encode) { - String url = append(baseUrl, params); - return put(encode ? encode(url) : url); - } - - /** - * Start a 'PUT' request to the given URL along with the query params - * - * @param baseUrl - * @param encode - * true to encode the full URL - * @param params - * the name/value query parameter pairs to include as part of the - * baseUrl - * - * @see #append(CharSequence, String...) - * @see #encode(CharSequence) - * - * @return request - */ - public static HttpRequest put(final CharSequence baseUrl, - final boolean encode, final Object... params) { - String url = append(baseUrl, params); - return put(encode ? encode(url) : url); - } - - /** - * Start a 'DELETE' request to the given URL - * - * @param url - * @return request - * @throws HttpRequestException - */ - public static HttpRequest delete(final CharSequence url) - throws HttpRequestException { - return new HttpRequest(url, METHOD_DELETE); - } - - /** - * Start a 'DELETE' request to the given URL - * - * @param url - * @return request - * @throws HttpRequestException - */ - public static HttpRequest delete(final URL url) throws HttpRequestException { - return new HttpRequest(url, METHOD_DELETE); - } - - /** - * Start a 'DELETE' request to the given URL along with the query params - * - * @param baseUrl - * @param params - * The query parameters to include as part of the baseUrl - * @param encode - * true to encode the full URL - * - * @see #append(CharSequence, Map) - * @see #encode(CharSequence) - * - * @return request - */ - public static HttpRequest delete(final CharSequence baseUrl, - final Map<?, ?> params, final boolean encode) { - String url = append(baseUrl, params); - return delete(encode ? encode(url) : url); - } - - /** - * Start a 'DELETE' request to the given URL along with the query params - * - * @param baseUrl - * @param encode - * true to encode the full URL - * @param params - * the name/value query parameter pairs to include as part of the - * baseUrl - * - * @see #append(CharSequence, String...) - * @see #encode(CharSequence) - * - * @return request - */ - public static HttpRequest delete(final CharSequence baseUrl, - final boolean encode, final Object... params) { - String url = append(baseUrl, params); - return delete(encode ? encode(url) : url); - } - - /** - * Start a 'HEAD' request to the given URL - * - * @param url - * @return request - * @throws HttpRequestException - */ - public static HttpRequest head(final CharSequence url) - throws HttpRequestException { - return new HttpRequest(url, METHOD_HEAD); - } - - /** - * Start a 'HEAD' request to the given URL - * - * @param url - * @return request - * @throws HttpRequestException - */ - public static HttpRequest head(final URL url) throws HttpRequestException { - return new HttpRequest(url, METHOD_HEAD); - } - - /** - * Start a 'HEAD' request to the given URL along with the query params - * - * @param baseUrl - * @param params - * The query parameters to include as part of the baseUrl - * @param encode - * true to encode the full URL - * - * @see #append(CharSequence, Map) - * @see #encode(CharSequence) - * - * @return request - */ - public static HttpRequest head(final CharSequence baseUrl, - final Map<?, ?> params, final boolean encode) { - String url = append(baseUrl, params); - return head(encode ? encode(url) : url); - } - - /** - * Start a 'GET' request to the given URL along with the query params - * - * @param baseUrl - * @param encode - * true to encode the full URL - * @param params - * the name/value query parameter pairs to include as part of the - * baseUrl - * - * @see #append(CharSequence, String...) - * @see #encode(CharSequence) - * - * @return request - */ - public static HttpRequest head(final CharSequence baseUrl, - final boolean encode, final Object... params) { - String url = append(baseUrl, params); - return head(encode ? encode(url) : url); - } - - /** - * Start an 'OPTIONS' request to the given URL - * - * @param url - * @return request - * @throws HttpRequestException - */ - public static HttpRequest options(final CharSequence url) - throws HttpRequestException { - return new HttpRequest(url, METHOD_OPTIONS); - } - - /** - * Start an 'OPTIONS' request to the given URL - * - * @param url - * @return request - * @throws HttpRequestException - */ - public static HttpRequest options(final URL url) throws HttpRequestException { - return new HttpRequest(url, METHOD_OPTIONS); - } - - /** - * Start a 'TRACE' request to the given URL - * - * @param url - * @return request - * @throws HttpRequestException - */ - public static HttpRequest trace(final CharSequence url) - throws HttpRequestException { - return new HttpRequest(url, METHOD_TRACE); - } - - /** - * Start a 'TRACE' request to the given URL - * - * @param url - * @return request - * @throws HttpRequestException - */ - public static HttpRequest trace(final URL url) throws HttpRequestException { - return new HttpRequest(url, METHOD_TRACE); - } - - /** - * Set the 'http.keepAlive' property to the given value. - * <p> - * This setting will apply to all requests. - * - * @param keepAlive - */ - public static void keepAlive(final boolean keepAlive) { - setProperty("http.keepAlive", Boolean.toString(keepAlive)); - } - - /** - * Set the 'http.maxConnections' property to the given value. - * <p> - * This setting will apply to all requests. - * - * @param maxConnections - */ - public static void maxConnections(final int maxConnections) { - setProperty("http.maxConnections", Integer.toString(maxConnections)); - } - - /** - * Set the 'http.proxyHost' & 'https.proxyHost' properties to the given host - * value. - * <p> - * This setting will apply to all requests. - * - * @param host - */ - public static void proxyHost(final String host) { - setProperty("http.proxyHost", host); - setProperty("https.proxyHost", host); - } - - /** - * Set the 'http.proxyPort' & 'https.proxyPort' properties to the given port - * number. - * <p> - * This setting will apply to all requests. - * - * @param port - */ - public static void proxyPort(final int port) { - final String portValue = Integer.toString(port); - setProperty("http.proxyPort", portValue); - setProperty("https.proxyPort", portValue); - } - - /** - * Set the 'http.nonProxyHosts' property to the given host values. - * <p> - * Hosts will be separated by a '|' character. - * <p> - * This setting will apply to all requests. - * - * @param hosts - */ - public static void nonProxyHosts(final String... hosts) { - if (hosts != null && hosts.length > 0) { - StringBuilder separated = new StringBuilder(); - int last = hosts.length - 1; - for (int i = 0; i < last; i++) - separated.append(hosts[i]).append('|'); - separated.append(hosts[last]); - setProperty("http.nonProxyHosts", separated.toString()); - } else - setProperty("http.nonProxyHosts", null); - } - - /** - * Set property to given value. - * <p> - * Specifying a null value will cause the property to be cleared - * - * @param name - * @param value - * @return previous value - */ - private static String setProperty(final String name, final String value) { - final PrivilegedAction<String> action; - if (value != null) - action = new PrivilegedAction<String>() { - - public String run() { - return System.setProperty(name, value); - } - }; - else - action = new PrivilegedAction<String>() { - - public String run() { - return System.clearProperty(name); - } - }; - return AccessController.doPrivileged(action); - } - - private HttpURLConnection connection = null; - - private final URL url; - - private final String requestMethod; - - private RequestOutputStream output; - - private boolean multipart; - - private boolean form; - - private boolean ignoreCloseExceptions = true; - - private boolean uncompress = false; - - private int bufferSize = 8192; - - private long totalSize = -1; - - private long totalWritten = 0; - - private String httpProxyHost; - - private int httpProxyPort; - - private UploadProgress progress = UploadProgress.DEFAULT; - - /** - * Create HTTP connection wrapper - * - * @param url Remote resource URL. - * @param method HTTP request method (e.g., "GET", "POST"). - * @throws HttpRequestException - */ - public HttpRequest(final CharSequence url, final String method) - throws HttpRequestException { - try { - this.url = new URL(url.toString()); - } catch (MalformedURLException e) { - throw new HttpRequestException(e); - } - this.requestMethod = method; - } - - /** - * Create HTTP connection wrapper - * - * @param url Remote resource URL. - * @param method HTTP request method (e.g., "GET", "POST"). - * @throws HttpRequestException - */ - public HttpRequest(final URL url, final String method) - throws HttpRequestException { - this.url = url; - this.requestMethod = method; - } - - private Proxy createProxy() { - return new Proxy(HTTP, new InetSocketAddress(httpProxyHost, httpProxyPort)); - } - - private HttpURLConnection createConnection() { - try { - final HttpURLConnection connection; - if (httpProxyHost != null) - connection = CONNECTION_FACTORY.create(url, createProxy()); - else - connection = CONNECTION_FACTORY.create(url); - connection.setRequestMethod(requestMethod); - return connection; - } catch (IOException e) { - throw new HttpRequestException(e); - } - } - - @Override - public String toString() { - return method() + ' ' + url(); - } - - /** - * Get underlying connection - * - * @return connection - */ - public HttpURLConnection getConnection() { - if (connection == null) - connection = createConnection(); - return connection; - } - - /** - * Set whether or not to ignore exceptions that occur from calling - * {@link Closeable#close()} - * <p> - * The default value of this setting is <code>true</code> - * - * @param ignore - * @return this request - */ - public HttpRequest ignoreCloseExceptions(final boolean ignore) { - ignoreCloseExceptions = ignore; - return this; - } - - /** - * Get whether or not exceptions thrown by {@link Closeable#close()} are - * ignored - * - * @return true if ignoring, false if throwing - */ - public boolean ignoreCloseExceptions() { - return ignoreCloseExceptions; - } - - /** - * Get the status code of the response - * - * @return the response code - * @throws HttpRequestException - */ - public int code() throws HttpRequestException { - try { - closeOutput(); - return getConnection().getResponseCode(); - } catch (IOException e) { - throw new HttpRequestException(e); - } - } - - /** - * Set the value of the given {@link AtomicInteger} to the status code of the - * response - * - * @param output - * @return this request - * @throws HttpRequestException - */ - public HttpRequest code(final AtomicInteger output) - throws HttpRequestException { - output.set(code()); - return this; - } - - /** - * Is the response code a 200 OK? - * - * @return true if 200, false otherwise - * @throws HttpRequestException - */ - public boolean ok() throws HttpRequestException { - return HTTP_OK == code(); - } - - /** - * Is the response code a 201 Created? - * - * @return true if 201, false otherwise - * @throws HttpRequestException - */ - public boolean created() throws HttpRequestException { - return HTTP_CREATED == code(); - } - - /** - * Is the response code a 204 No Content? - * - * @return true if 204, false otherwise - * @throws HttpRequestException - */ - public boolean noContent() throws HttpRequestException { - return HTTP_NO_CONTENT == code(); - } - - /** - * Is the response code a 500 Internal Server Error? - * - * @return true if 500, false otherwise - * @throws HttpRequestException - */ - public boolean serverError() throws HttpRequestException { - return HTTP_INTERNAL_ERROR == code(); - } - - /** - * Is the response code a 400 Bad Request? - * - * @return true if 400, false otherwise - * @throws HttpRequestException - */ - public boolean badRequest() throws HttpRequestException { - return HTTP_BAD_REQUEST == code(); - } - - /** - * Is the response code a 404 Not Found? - * - * @return true if 404, false otherwise - * @throws HttpRequestException - */ - public boolean notFound() throws HttpRequestException { - return HTTP_NOT_FOUND == code(); - } - - /** - * Is the response code a 304 Not Modified? - * - * @return true if 304, false otherwise - * @throws HttpRequestException - */ - public boolean notModified() throws HttpRequestException { - return HTTP_NOT_MODIFIED == code(); - } - - /** - * Get status message of the response - * - * @return message - * @throws HttpRequestException - */ - public String message() throws HttpRequestException { - try { - closeOutput(); - return getConnection().getResponseMessage(); - } catch (IOException e) { - throw new HttpRequestException(e); - } - } - - /** - * Disconnect the connection - * - * @return this request - */ - public HttpRequest disconnect() { - getConnection().disconnect(); - return this; - } - - /** - * Set chunked streaming mode to the given size - * - * @param size - * @return this request - */ - public HttpRequest chunk(final int size) { - getConnection().setChunkedStreamingMode(size); - return this; - } - - /** - * Set the size used when buffering and copying between streams - * <p> - * This size is also used for send and receive buffers created for both char - * and byte arrays - * <p> - * The default buffer size is 8,192 bytes - * - * @param size - * @return this request - */ - public HttpRequest bufferSize(final int size) { - if (size < 1) - throw new IllegalArgumentException("Size must be greater than zero"); - bufferSize = size; - return this; - } - - /** - * Get the configured buffer size - * <p> - * The default buffer size is 8,192 bytes - * - * @return buffer size - */ - public int bufferSize() { - return bufferSize; - } - - /** - * Set whether or not the response body should be automatically uncompressed - * when read from. - * <p> - * This will only affect requests that have the 'Content-Encoding' response - * header set to 'gzip'. - * <p> - * This causes all receive methods to use a {@link GZIPInputStream} when - * applicable so that higher level streams and readers can read the data - * uncompressed. - * <p> - * Setting this option does not cause any request headers to be set - * automatically so {@link #acceptGzipEncoding()} should be used in - * conjunction with this setting to tell the server to gzip the response. - * - * @param uncompress - * @return this request - */ - public HttpRequest uncompress(final boolean uncompress) { - this.uncompress = uncompress; - return this; - } - - /** - * Create byte array output stream - * - * @return stream - */ - protected ByteArrayOutputStream byteStream() { - final int size = contentLength(); - if (size > 0) - return new ByteArrayOutputStream(size); - else - return new ByteArrayOutputStream(); - } - - /** - * Get response as {@link String} in given character set - * <p> - * This will fall back to using the UTF-8 character set if the given charset - * is null - * - * @param charset - * @return string - * @throws HttpRequestException - */ - public String body(final String charset) throws HttpRequestException { - final ByteArrayOutputStream output = byteStream(); - try { - copy(buffer(), output); - return output.toString(getValidCharset(charset)); - } catch (IOException e) { - throw new HttpRequestException(e); - } - } - - /** - * Get response as {@link String} using character set returned from - * {@link #charset()} - * - * @return string - * @throws HttpRequestException - */ - public String body() throws HttpRequestException { - return body(charset()); - } - - /** - * Get the response body as a {@link String} and set it as the value of the - * given reference. - * - * @param output - * @return this request - * @throws HttpRequestException - */ - public HttpRequest body(final AtomicReference<String> output) throws HttpRequestException { - output.set(body()); - return this; - } - - /** - * Get the response body as a {@link String} and set it as the value of the - * given reference. - * - * @param output - * @param charset - * @return this request - * @throws HttpRequestException - */ - public HttpRequest body(final AtomicReference<String> output, final String charset) throws HttpRequestException { - output.set(body(charset)); - return this; - } - - - /** - * Is the response body empty? - * - * @return true if the Content-Length response header is 0, false otherwise - * @throws HttpRequestException - */ - public boolean isBodyEmpty() throws HttpRequestException { - return contentLength() == 0; - } - - /** - * Get response as byte array - * - * @return byte array - * @throws HttpRequestException - */ - public byte[] bytes() throws HttpRequestException { - final ByteArrayOutputStream output = byteStream(); - try { - copy(buffer(), output); - } catch (IOException e) { - throw new HttpRequestException(e); - } - return output.toByteArray(); - } - - /** - * Get response in a buffered stream - * - * @see #bufferSize(int) - * @return stream - * @throws HttpRequestException - */ - public BufferedInputStream buffer() throws HttpRequestException { - return new BufferedInputStream(stream(), bufferSize); - } - - /** - * Get stream to response body - * - * @return stream - * @throws HttpRequestException - */ - public InputStream stream() throws HttpRequestException { - InputStream stream; - if (code() < HTTP_BAD_REQUEST) - try { - stream = getConnection().getInputStream(); - } catch (IOException e) { - throw new HttpRequestException(e); - } - else { - stream = getConnection().getErrorStream(); - if (stream == null) - try { - stream = getConnection().getInputStream(); - } catch (IOException e) { - if (contentLength() > 0) - throw new HttpRequestException(e); - else - stream = new ByteArrayInputStream(new byte[0]); - } - } - - if (!uncompress || !ENCODING_GZIP.equals(contentEncoding())) - return stream; - else - try { - return new GZIPInputStream(stream); - } catch (IOException e) { - throw new HttpRequestException(e); - } - } - - /** - * Get reader to response body using given character set. - * <p> - * This will fall back to using the UTF-8 character set if the given charset - * is null - * - * @param charset - * @return reader - * @throws HttpRequestException - */ - public InputStreamReader reader(final String charset) - throws HttpRequestException { - try { - return new InputStreamReader(stream(), getValidCharset(charset)); - } catch (UnsupportedEncodingException e) { - throw new HttpRequestException(e); - } - } - - /** - * Get reader to response body using the character set returned from - * {@link #charset()} - * - * @return reader - * @throws HttpRequestException - */ - public InputStreamReader reader() throws HttpRequestException { - return reader(charset()); - } - - /** - * Get buffered reader to response body using the given character set r and - * the configured buffer size - * - * - * @see #bufferSize(int) - * @param charset - * @return reader - * @throws HttpRequestException - */ - public BufferedReader bufferedReader(final String charset) - throws HttpRequestException { - return new BufferedReader(reader(charset), bufferSize); - } - - /** - * Get buffered reader to response body using the character set returned from - * {@link #charset()} and the configured buffer size - * - * @see #bufferSize(int) - * @return reader - * @throws HttpRequestException - */ - public BufferedReader bufferedReader() throws HttpRequestException { - return bufferedReader(charset()); - } - - /** - * Stream response body to file - * - * @param file - * @return this request - * @throws HttpRequestException - */ - public HttpRequest receive(final File file) throws HttpRequestException { - final OutputStream output; - try { - output = new BufferedOutputStream(new FileOutputStream(file), bufferSize); - } catch (FileNotFoundException e) { - throw new HttpRequestException(e); - } - return new CloseOperation<HttpRequest>(output, ignoreCloseExceptions) { - - @Override - protected HttpRequest run() throws HttpRequestException, IOException { - return receive(output); - } - }.call(); - } - - /** - * Stream response to given output stream - * - * @param output - * @return this request - * @throws HttpRequestException - */ - public HttpRequest receive(final OutputStream output) - throws HttpRequestException { - try { - return copy(buffer(), output); - } catch (IOException e) { - throw new HttpRequestException(e); - } - } - - /** - * Stream response to given print stream - * - * @param output - * @return this request - * @throws HttpRequestException - */ - public HttpRequest receive(final PrintStream output) - throws HttpRequestException { - return receive((OutputStream) output); - } - - /** - * Receive response into the given appendable - * - * @param appendable - * @return this request - * @throws HttpRequestException - */ - public HttpRequest receive(final Appendable appendable) - throws HttpRequestException { - final BufferedReader reader = bufferedReader(); - return new CloseOperation<HttpRequest>(reader, ignoreCloseExceptions) { - - @Override - public HttpRequest run() throws IOException { - final CharBuffer buffer = CharBuffer.allocate(bufferSize); - int read; - while ((read = reader.read(buffer)) != -1) { - buffer.rewind(); - appendable.append(buffer, 0, read); - buffer.rewind(); - } - return HttpRequest.this; - } - }.call(); - } - - /** - * Receive response into the given writer - * - * @param writer - * @return this request - * @throws HttpRequestException - */ - public HttpRequest receive(final Writer writer) throws HttpRequestException { - final BufferedReader reader = bufferedReader(); - return new CloseOperation<HttpRequest>(reader, ignoreCloseExceptions) { - - @Override - public HttpRequest run() throws IOException { - return copy(reader, writer); - } - }.call(); - } - - /** - * Set read timeout on connection to given value - * - * @param timeout - * @return this request - */ - public HttpRequest readTimeout(final int timeout) { - getConnection().setReadTimeout(timeout); - return this; - } - - /** - * Set connect timeout on connection to given value - * - * @param timeout - * @return this request - */ - public HttpRequest connectTimeout(final int timeout) { - getConnection().setConnectTimeout(timeout); - return this; - } - - /** - * Set header name to given value - * - * @param name - * @param value - * @return this request - */ - public HttpRequest header(final String name, final String value) { - getConnection().setRequestProperty(name, value); - return this; - } - - /** - * Set header name to given value - * - * @param name - * @param value - * @return this request - */ - public HttpRequest header(final String name, final Number value) { - return header(name, value != null ? value.toString() : null); - } - - /** - * Set all headers found in given map where the keys are the header names and - * the values are the header values - * - * @param headers - * @return this request - */ - public HttpRequest headers(final Map<String, String> headers) { - if (!headers.isEmpty()) - for (Entry<String, String> header : headers.entrySet()) - header(header); - return this; - } - - /** - * Set header to have given entry's key as the name and value as the value - * - * @param header - * @return this request - */ - public HttpRequest header(final Entry<String, String> header) { - return header(header.getKey(), header.getValue()); - } - - /** - * Get a response header - * - * @param name - * @return response header - * @throws HttpRequestException - */ - public String header(final String name) throws HttpRequestException { - closeOutputQuietly(); - return getConnection().getHeaderField(name); - } - - /** - * Get all the response headers - * - * @return map of response header names to their value(s) - * @throws HttpRequestException - */ - public Map<String, List<String>> headers() throws HttpRequestException { - closeOutputQuietly(); - return getConnection().getHeaderFields(); - } - - /** - * Get a date header from the response falling back to returning -1 if the - * header is missing or parsing fails - * - * @param name - * @return date, -1 on failures - * @throws HttpRequestException - */ - public long dateHeader(final String name) throws HttpRequestException { - return dateHeader(name, -1L); - } - - /** - * Get a date header from the response falling back to returning the given - * default value if the header is missing or parsing fails - * - * @param name - * @param defaultValue - * @return date, default value on failures - * @throws HttpRequestException - */ - public long dateHeader(final String name, final long defaultValue) - throws HttpRequestException { - closeOutputQuietly(); - return getConnection().getHeaderFieldDate(name, defaultValue); - } - - /** - * Get an integer header from the response falling back to returning -1 if the - * header is missing or parsing fails - * - * @param name - * @return header value as an integer, -1 when missing or parsing fails - * @throws HttpRequestException - */ - public int intHeader(final String name) throws HttpRequestException { - return intHeader(name, -1); - } - - /** - * Get an integer header value from the response falling back to the given - * default value if the header is missing or if parsing fails - * - * @param name - * @param defaultValue - * @return header value as an integer, default value when missing or parsing - * fails - * @throws HttpRequestException - */ - public int intHeader(final String name, final int defaultValue) - throws HttpRequestException { - closeOutputQuietly(); - return getConnection().getHeaderFieldInt(name, defaultValue); - } - - /** - * Get all values of the given header from the response - * - * @param name - * @return non-null but possibly empty array of {@link String} header values - */ - public String[] headers(final String name) { - final Map<String, List<String>> headers = headers(); - if (headers == null || headers.isEmpty()) - return EMPTY_STRINGS; - - final List<String> values = headers.get(name); - if (values != null && !values.isEmpty()) - return values.toArray(new String[values.size()]); - else - return EMPTY_STRINGS; - } - - /** - * Get parameter with given name from header value in response - * - * @param headerName - * @param paramName - * @return parameter value or null if missing - */ - public String parameter(final String headerName, final String paramName) { - return getParam(header(headerName), paramName); - } - - /** - * Get all parameters from header value in response - * <p> - * This will be all key=value pairs after the first ';' that are separated by - * a ';' - * - * @param headerName - * @return non-null but possibly empty map of parameter headers - */ - public Map<String, String> parameters(final String headerName) { - return getParams(header(headerName)); - } - - /** - * Get parameter values from header value - * - * @param header - * @return parameter value or null if none - */ - protected Map<String, String> getParams(final String header) { - if (header == null || header.length() == 0) - return Collections.emptyMap(); - - final int headerLength = header.length(); - int start = header.indexOf(';') + 1; - if (start == 0 || start == headerLength) - return Collections.emptyMap(); - - int end = header.indexOf(';', start); - if (end == -1) - end = headerLength; - - Map<String, String> params = new LinkedHashMap<String, String>(); - while (start < end) { - int nameEnd = header.indexOf('=', start); - if (nameEnd != -1 && nameEnd < end) { - String name = header.substring(start, nameEnd).trim(); - if (name.length() > 0) { - String value = header.substring(nameEnd + 1, end).trim(); - int length = value.length(); - if (length != 0) - if (length > 2 && '"' == value.charAt(0) - && '"' == value.charAt(length - 1)) - params.put(name, value.substring(1, length - 1)); - else - params.put(name, value); - } - } - - start = end + 1; - end = header.indexOf(';', start); - if (end == -1) - end = headerLength; - } - - return params; - } - - /** - * Get parameter value from header value - * - * @param value - * @param paramName - * @return parameter value or null if none - */ - protected String getParam(final String value, final String paramName) { - if (value == null || value.length() == 0) - return null; - - final int length = value.length(); - int start = value.indexOf(';') + 1; - if (start == 0 || start == length) - return null; - - int end = value.indexOf(';', start); - if (end == -1) - end = length; - - while (start < end) { - int nameEnd = value.indexOf('=', start); - if (nameEnd != -1 && nameEnd < end - && paramName.equals(value.substring(start, nameEnd).trim())) { - String paramValue = value.substring(nameEnd + 1, end).trim(); - int valueLength = paramValue.length(); - if (valueLength != 0) - if (valueLength > 2 && '"' == paramValue.charAt(0) - && '"' == paramValue.charAt(valueLength - 1)) - return paramValue.substring(1, valueLength - 1); - else - return paramValue; - } - - start = end + 1; - end = value.indexOf(';', start); - if (end == -1) - end = length; - } - - return null; - } - - /** - * Get 'charset' parameter from 'Content-Type' response header - * - * @return charset or null if none - */ - public String charset() { - return parameter(HEADER_CONTENT_TYPE, PARAM_CHARSET); - } - - /** - * Set the 'User-Agent' header to given value - * - * @param userAgent - * @return this request - */ - public HttpRequest userAgent(final String userAgent) { - return header(HEADER_USER_AGENT, userAgent); - } - - /** - * Set the 'Referer' header to given value - * - * @param referer - * @return this request - */ - public HttpRequest referer(final String referer) { - return header(HEADER_REFERER, referer); - } - - /** - * Set value of {@link HttpURLConnection#setUseCaches(boolean)} - * - * @param useCaches - * @return this request - */ - public HttpRequest useCaches(final boolean useCaches) { - getConnection().setUseCaches(useCaches); - return this; - } - - /** - * Set the 'Accept-Encoding' header to given value - * - * @param acceptEncoding - * @return this request - */ - public HttpRequest acceptEncoding(final String acceptEncoding) { - return header(HEADER_ACCEPT_ENCODING, acceptEncoding); - } - - /** - * Set the 'Accept-Encoding' header to 'gzip' - * - * @see #uncompress(boolean) - * @return this request - */ - public HttpRequest acceptGzipEncoding() { - return acceptEncoding(ENCODING_GZIP); - } - - /** - * Set the 'Accept-Charset' header to given value - * - * @param acceptCharset - * @return this request - */ - public HttpRequest acceptCharset(final String acceptCharset) { - return header(HEADER_ACCEPT_CHARSET, acceptCharset); - } - - /** - * Get the 'Content-Encoding' header from the response - * - * @return this request - */ - public String contentEncoding() { - return header(HEADER_CONTENT_ENCODING); - } - - /** - * Get the 'Server' header from the response - * - * @return server - */ - public String server() { - return header(HEADER_SERVER); - } - - /** - * Get the 'Date' header from the response - * - * @return date value, -1 on failures - */ - public long date() { - return dateHeader(HEADER_DATE); - } - - /** - * Get the 'Cache-Control' header from the response - * - * @return cache control - */ - public String cacheControl() { - return header(HEADER_CACHE_CONTROL); - } - - /** - * Get the 'ETag' header from the response - * - * @return entity tag - */ - public String eTag() { - return header(HEADER_ETAG); - } - - /** - * Get the 'Expires' header from the response - * - * @return expires value, -1 on failures - */ - public long expires() { - return dateHeader(HEADER_EXPIRES); - } - - /** - * Get the 'Last-Modified' header from the response - * - * @return last modified value, -1 on failures - */ - public long lastModified() { - return dateHeader(HEADER_LAST_MODIFIED); - } - - /** - * Get the 'Location' header from the response - * - * @return location - */ - public String location() { - return header(HEADER_LOCATION); - } - - /** - * Set the 'Authorization' header to given value - * - * @param authorization - * @return this request - */ - public HttpRequest authorization(final String authorization) { - return header(HEADER_AUTHORIZATION, authorization); - } - - /** - * Set the 'Proxy-Authorization' header to given value - * - * @param proxyAuthorization - * @return this request - */ - public HttpRequest proxyAuthorization(final String proxyAuthorization) { - return header(HEADER_PROXY_AUTHORIZATION, proxyAuthorization); - } - - /** - * Set the 'Authorization' header to given values in Basic authentication - * format - * - * @param name - * @param password - * @return this request - */ - public HttpRequest basic(final String name, final String password) { - return authorization("Basic " + Base64.encode(name + ':' + password)); - } - - /** - * Set the 'Proxy-Authorization' header to given values in Basic authentication - * format - * - * @param name - * @param password - * @return this request - */ - public HttpRequest proxyBasic(final String name, final String password) { - return proxyAuthorization("Basic " + Base64.encode(name + ':' + password)); - } - - /** - * Set the 'If-Modified-Since' request header to the given value - * - * @param ifModifiedSince - * @return this request - */ - public HttpRequest ifModifiedSince(final long ifModifiedSince) { - getConnection().setIfModifiedSince(ifModifiedSince); - return this; - } - - /** - * Set the 'If-None-Match' request header to the given value - * - * @param ifNoneMatch - * @return this request - */ - public HttpRequest ifNoneMatch(final String ifNoneMatch) { - return header(HEADER_IF_NONE_MATCH, ifNoneMatch); - } - - /** - * Set the 'Content-Type' request header to the given value - * - * @param contentType - * @return this request - */ - public HttpRequest contentType(final String contentType) { - return contentType(contentType, null); - } - - /** - * Set the 'Content-Type' request header to the given value and charset - * - * @param contentType - * @param charset - * @return this request - */ - public HttpRequest contentType(final String contentType, final String charset) { - if (charset != null && charset.length() > 0) { - final String separator = "; " + PARAM_CHARSET + '='; - return header(HEADER_CONTENT_TYPE, contentType + separator + charset); - } else - return header(HEADER_CONTENT_TYPE, contentType); - } - - /** - * Get the 'Content-Type' header from the response - * - * @return response header value - */ - public String contentType() { - return header(HEADER_CONTENT_TYPE); - } - - /** - * Get the 'Content-Length' header from the response - * - * @return response header value - */ - public int contentLength() { - return intHeader(HEADER_CONTENT_LENGTH); - } - - /** - * Set the 'Content-Length' request header to the given value - * - * @param contentLength - * @return this request - */ - public HttpRequest contentLength(final String contentLength) { - return contentLength(Integer.parseInt(contentLength)); - } - - /** - * Set the 'Content-Length' request header to the given value - * - * @param contentLength - * @return this request - */ - public HttpRequest contentLength(final int contentLength) { - getConnection().setFixedLengthStreamingMode(contentLength); - return this; - } - - /** - * Set the 'Accept' header to given value - * - * @param accept - * @return this request - */ - public HttpRequest accept(final String accept) { - return header(HEADER_ACCEPT, accept); - } - - /** - * Set the 'Accept' header to 'application/json' - * - * @return this request - */ - public HttpRequest acceptJson() { - return accept(CONTENT_TYPE_JSON); - } - - /** - * Copy from input stream to output stream - * - * @param input - * @param output - * @return this request - * @throws IOException - */ - protected HttpRequest copy(final InputStream input, final OutputStream output) - throws IOException { - return new CloseOperation<HttpRequest>(input, ignoreCloseExceptions) { - - @Override - public HttpRequest run() throws IOException { - final byte[] buffer = new byte[bufferSize]; - int read; - while ((read = input.read(buffer)) != -1) { - output.write(buffer, 0, read); - totalWritten += read; - progress.onUpload(totalWritten, totalSize); - } - return HttpRequest.this; - } - }.call(); - } - - /** - * Copy from reader to writer - * - * @param input - * @param output - * @return this request - * @throws IOException - */ - protected HttpRequest copy(final Reader input, final Writer output) - throws IOException { - return new CloseOperation<HttpRequest>(input, ignoreCloseExceptions) { - - @Override - public HttpRequest run() throws IOException { - final char[] buffer = new char[bufferSize]; - int read; - while ((read = input.read(buffer)) != -1) { - output.write(buffer, 0, read); - totalWritten += read; - progress.onUpload(totalWritten, -1); - } - return HttpRequest.this; - } - }.call(); - } - - /** - * Set the UploadProgress callback for this request - * - * @param callback - * @return this request - */ - public HttpRequest progress(final UploadProgress callback) { - if (callback == null) - progress = UploadProgress.DEFAULT; - else - progress = callback; - return this; - } - - private HttpRequest incrementTotalSize(final long size) { - if (totalSize == -1) - totalSize = 0; - totalSize += size; - return this; - } - - /** - * Close output stream - * - * @return this request - * @throws HttpRequestException - * @throws IOException - */ - protected HttpRequest closeOutput() throws IOException { - progress(null); - if (output == null) - return this; - if (multipart) - output.write(CRLF + "--" + BOUNDARY + "--" + CRLF); - if (ignoreCloseExceptions) - try { - output.close(); - } catch (IOException ignored) { - // Ignored - } - else - output.close(); - output = null; - return this; - } - - /** - * Call {@link #closeOutput()} and re-throw a caught {@link IOException}s as - * an {@link HttpRequestException} - * - * @return this request - * @throws HttpRequestException - */ - protected HttpRequest closeOutputQuietly() throws HttpRequestException { - try { - return closeOutput(); - } catch (IOException e) { - throw new HttpRequestException(e); - } - } - - /** - * Open output stream - * - * @return this request - * @throws IOException - */ - protected HttpRequest openOutput() throws IOException { - if (output != null) - return this; - getConnection().setDoOutput(true); - final String charset = getParam( - getConnection().getRequestProperty(HEADER_CONTENT_TYPE), PARAM_CHARSET); - output = new RequestOutputStream(getConnection().getOutputStream(), charset, - bufferSize); - return this; - } - - /** - * Start part of a multipart - * - * @return this request - * @throws IOException - */ - protected HttpRequest startPart() throws IOException { - if (!multipart) { - multipart = true; - contentType(CONTENT_TYPE_MULTIPART).openOutput(); - output.write("--" + BOUNDARY + CRLF); - } else - output.write(CRLF + "--" + BOUNDARY + CRLF); - return this; - } - - /** - * Write part header - * - * @param name - * @param filename - * @return this request - * @throws IOException - */ - protected HttpRequest writePartHeader(final String name, final String filename) - throws IOException { - return writePartHeader(name, filename, null); - } - - /** - * Write part header - * - * @param name - * @param filename - * @param contentType - * @return this request - * @throws IOException - */ - protected HttpRequest writePartHeader(final String name, - final String filename, final String contentType) throws IOException { - final StringBuilder partBuffer = new StringBuilder(); - partBuffer.append("form-data; name=\"").append(name); - if (filename != null) - partBuffer.append("\"; filename=\"").append(filename); - partBuffer.append('"'); - partHeader("Content-Disposition", partBuffer.toString()); - if (contentType != null) - partHeader(HEADER_CONTENT_TYPE, contentType); - return send(CRLF); - } - - /** - * Write part of a multipart request to the request body - * - * @param name - * @param part - * @return this request - */ - public HttpRequest part(final String name, final String part) { - return part(name, null, part); - } - - /** - * Write part of a multipart request to the request body - * - * @param name - * @param filename - * @param part - * @return this request - * @throws HttpRequestException - */ - public HttpRequest part(final String name, final String filename, - final String part) throws HttpRequestException { - return part(name, filename, null, part); - } - - /** - * Write part of a multipart request to the request body - * - * @param name - * @param filename - * @param contentType - * value of the Content-Type part header - * @param part - * @return this request - * @throws HttpRequestException - */ - public HttpRequest part(final String name, final String filename, - final String contentType, final String part) throws HttpRequestException { - try { - startPart(); - writePartHeader(name, filename, contentType); - output.write(part); - } catch (IOException e) { - throw new HttpRequestException(e); - } - return this; - } - - /** - * Write part of a multipart request to the request body - * - * @param name - * @param part - * @return this request - * @throws HttpRequestException - */ - public HttpRequest part(final String name, final Number part) - throws HttpRequestException { - return part(name, null, part); - } - - /** - * Write part of a multipart request to the request body - * - * @param name - * @param filename - * @param part - * @return this request - * @throws HttpRequestException - */ - public HttpRequest part(final String name, final String filename, - final Number part) throws HttpRequestException { - return part(name, filename, part != null ? part.toString() : null); - } - - /** - * Write part of a multipart request to the request body - * - * @param name - * @param part - * @return this request - * @throws HttpRequestException - */ - public HttpRequest part(final String name, final File part) - throws HttpRequestException { - return part(name, null, part); - } - - /** - * Write part of a multipart request to the request body - * - * @param name - * @param filename - * @param part - * @return this request - * @throws HttpRequestException - */ - public HttpRequest part(final String name, final String filename, - final File part) throws HttpRequestException { - return part(name, filename, null, part); - } - - /** - * Write part of a multipart request to the request body - * - * @param name - * @param filename - * @param contentType - * value of the Content-Type part header - * @param part - * @return this request - * @throws HttpRequestException - */ - public HttpRequest part(final String name, final String filename, - final String contentType, final File part) throws HttpRequestException { - final InputStream stream; - try { - stream = new BufferedInputStream(new FileInputStream(part)); - incrementTotalSize(part.length()); - } catch (IOException e) { - throw new HttpRequestException(e); - } - return part(name, filename, contentType, stream); - } - - /** - * Write part of a multipart request to the request body - * - * @param name - * @param part - * @return this request - * @throws HttpRequestException - */ - public HttpRequest part(final String name, final InputStream part) - throws HttpRequestException { - return part(name, null, null, part); - } - - /** - * Write part of a multipart request to the request body - * - * @param name - * @param filename - * @param contentType - * value of the Content-Type part header - * @param part - * @return this request - * @throws HttpRequestException - */ - public HttpRequest part(final String name, final String filename, - final String contentType, final InputStream part) - throws HttpRequestException { - try { - startPart(); - writePartHeader(name, filename, contentType); - copy(part, output); - } catch (IOException e) { - throw new HttpRequestException(e); - } - return this; - } - - /** - * Write a multipart header to the response body - * - * @param name - * @param value - * @return this request - * @throws HttpRequestException - */ - public HttpRequest partHeader(final String name, final String value) - throws HttpRequestException { - return send(name).send(": ").send(value).send(CRLF); - } - - /** - * Write contents of file to request body - * - * @param input - * @return this request - * @throws HttpRequestException - */ - public HttpRequest send(final File input) throws HttpRequestException { - final InputStream stream; - try { - stream = new BufferedInputStream(new FileInputStream(input)); - incrementTotalSize(input.length()); - } catch (FileNotFoundException e) { - throw new HttpRequestException(e); - } - return send(stream); - } - - /** - * Write byte array to request body - * - * @param input - * @return this request - * @throws HttpRequestException - */ - public HttpRequest send(final byte[] input) throws HttpRequestException { - if (input != null) - incrementTotalSize(input.length); - return send(new ByteArrayInputStream(input)); - } - - /** - * Write stream to request body - * <p> - * The given stream will be closed once sending completes - * - * @param input - * @return this request - * @throws HttpRequestException - */ - public HttpRequest send(final InputStream input) throws HttpRequestException { - try { - openOutput(); - copy(input, output); - } catch (IOException e) { - throw new HttpRequestException(e); - } - return this; - } - - /** - * Write reader to request body - * <p> - * The given reader will be closed once sending completes - * - * @param input - * @return this request - * @throws HttpRequestException - */ - public HttpRequest send(final Reader input) throws HttpRequestException { - try { - openOutput(); - } catch (IOException e) { - throw new HttpRequestException(e); - } - final Writer writer = new OutputStreamWriter(output, - output.encoder.charset()); - return new FlushOperation<HttpRequest>(writer) { - - @Override - protected HttpRequest run() throws IOException { - return copy(input, writer); - } - }.call(); - } - - /** - * Write char sequence to request body - * <p> - * The charset configured via {@link #contentType(String)} will be used and - * UTF-8 will be used if it is unset. - * - * @param value - * @return this request - * @throws HttpRequestException - */ - public HttpRequest send(final CharSequence value) throws HttpRequestException { - try { - openOutput(); - output.write(value.toString()); - } catch (IOException e) { - throw new HttpRequestException(e); - } - return this; - } - - /** - * Create writer to request output stream - * - * @return writer - * @throws HttpRequestException - */ - public OutputStreamWriter writer() throws HttpRequestException { - try { - openOutput(); - return new OutputStreamWriter(output, output.encoder.charset()); - } catch (IOException e) { - throw new HttpRequestException(e); - } - } - - /** - * Write the values in the map as form data to the request body - * <p> - * The pairs specified will be URL-encoded in UTF-8 and sent with the - * 'application/x-www-form-urlencoded' content-type - * - * @param values - * @return this request - * @throws HttpRequestException - */ - public HttpRequest form(final Map<?, ?> values) throws HttpRequestException { - return form(values, CHARSET_UTF8); - } - - /** - * Write the key and value in the entry as form data to the request body - * <p> - * The pair specified will be URL-encoded in UTF-8 and sent with the - * 'application/x-www-form-urlencoded' content-type - * - * @param entry - * @return this request - * @throws HttpRequestException - */ - public HttpRequest form(final Entry<?, ?> entry) throws HttpRequestException { - return form(entry, CHARSET_UTF8); - } - - /** - * Write the key and value in the entry as form data to the request body - * <p> - * The pair specified will be URL-encoded and sent with the - * 'application/x-www-form-urlencoded' content-type - * - * @param entry - * @param charset - * @return this request - * @throws HttpRequestException - */ - public HttpRequest form(final Entry<?, ?> entry, final String charset) - throws HttpRequestException { - return form(entry.getKey(), entry.getValue(), charset); - } - - /** - * Write the name/value pair as form data to the request body - * <p> - * The pair specified will be URL-encoded in UTF-8 and sent with the - * 'application/x-www-form-urlencoded' content-type - * - * @param name - * @param value - * @return this request - * @throws HttpRequestException - */ - public HttpRequest form(final Object name, final Object value) - throws HttpRequestException { - return form(name, value, CHARSET_UTF8); - } - - /** - * Write the name/value pair as form data to the request body - * <p> - * The values specified will be URL-encoded and sent with the - * 'application/x-www-form-urlencoded' content-type - * - * @param name - * @param value - * @param charset - * @return this request - * @throws HttpRequestException - */ - public HttpRequest form(final Object name, final Object value, String charset) - throws HttpRequestException { - final boolean first = !form; - if (first) { - contentType(CONTENT_TYPE_FORM, charset); - form = true; - } - charset = getValidCharset(charset); - try { - openOutput(); - if (!first) - output.write('&'); - output.write(URLEncoder.encode(name.toString(), charset)); - output.write('='); - if (value != null) - output.write(URLEncoder.encode(value.toString(), charset)); - } catch (IOException e) { - throw new HttpRequestException(e); - } - return this; - } - - /** - * Write the values in the map as encoded form data to the request body - * - * @param values - * @param charset - * @return this request - * @throws HttpRequestException - */ - public HttpRequest form(final Map<?, ?> values, final String charset) - throws HttpRequestException { - if (!values.isEmpty()) - for (Entry<?, ?> entry : values.entrySet()) - form(entry, charset); - return this; - } - - /** - * Configure HTTPS connection to trust only certain certificates - * <p> - * This method throws an exception if the current request is not a HTTPS request - * - * @return this request - * @throws HttpRequestException - */ - public HttpRequest pinToCerts() throws HttpRequestException { - final HttpURLConnection connection = getConnection(); - if (connection instanceof HttpsURLConnection) { - ((HttpsURLConnection) connection).setSSLSocketFactory(getPinnedFactory()); - } else { - IOException e = new IOException("You must use a https url to use ssl pinning"); - throw new HttpRequestException(e); - } - return this; - } - - /** - * Configure HTTPS connection to trust all certificates - * <p> - * This method does nothing if the current request is not a HTTPS request - * - * @return this request - * @throws HttpRequestException - */ - public HttpRequest trustAllCerts() throws HttpRequestException { - final HttpURLConnection connection = getConnection(); - if (connection instanceof HttpsURLConnection) - ((HttpsURLConnection) connection) - .setSSLSocketFactory(getTrustedFactory()); - return this; - } - - /** - * Configure HTTPS connection to trust all hosts using a custom - * {@link HostnameVerifier} that always returns <code>true</code> for each - * host verified - * <p> - * This method does nothing if the current request is not a HTTPS request - * - * @return this request - */ - public HttpRequest trustAllHosts() { - final HttpURLConnection connection = getConnection(); - if (connection instanceof HttpsURLConnection) - ((HttpsURLConnection) connection) - .setHostnameVerifier(getTrustedVerifier()); - return this; - } - - /** - * Get the {@link URL} of this request's connection - * - * @return request URL - */ - public URL url() { - return getConnection().getURL(); - } - - /** - * Get the HTTP method of this request - * - * @return method - */ - public String method() { - return getConnection().getRequestMethod(); - } - - /** - * Configure an HTTP proxy on this connection. Use {{@link #proxyBasic(String, String)} if - * this proxy requires basic authentication. - * - * @param proxyHost - * @param proxyPort - * @return this request - */ - public HttpRequest useProxy(final String proxyHost, final int proxyPort) { - if (connection != null) - throw new IllegalStateException("The connection has already been created. This method must be called before reading or writing to the request."); - - this.httpProxyHost = proxyHost; - this.httpProxyPort = proxyPort; - return this; - } - - /** - * Set whether or not the underlying connection should follow redirects in - * the response. - * - * @param followRedirects - true fo follow redirects, false to not. - * @return this request - */ - public HttpRequest followRedirects(final boolean followRedirects) { - getConnection().setInstanceFollowRedirects(followRedirects); - return this; - } -} diff --git a/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFHTTPRequestOperation.h b/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFHTTPRequestOperation.h deleted file mode 100644 index 6da166eb..00000000 --- a/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFHTTPRequestOperation.h +++ /dev/null @@ -1,67 +0,0 @@ -// AFHTTPRequestOperation.h -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import <Foundation/Foundation.h> -#import "AFURLConnectionOperation.h" - -/** - `AFHTTPRequestOperation` is a subclass of `AFURLConnectionOperation` for requests using the HTTP or HTTPS protocols. It encapsulates the concept of acceptable status codes and content types, which determine the success or failure of a request. - */ -@interface AFHTTPRequestOperation : AFURLConnectionOperation - -///------------------------------------------------ -/// @name Getting HTTP URL Connection Information -///------------------------------------------------ - -/** - The last HTTP response received by the operation's connection. - */ -@property (readonly, nonatomic, strong) NSHTTPURLResponse *response; - -/** - 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 AFHTTPResponse serializer, which uses the raw data as its response object. The serializer validates the status code to be in the `2XX` range, denoting success. If the response serializer generates an error in `-responseObjectForResponse:data:error:`, the `failure` callback of the session task or request operation will be executed; otherwise, the `success` callback will be executed. - - @warning `responseSerializer` must not be `nil`. Setting a response serializer will clear out any cached value - */ -@property (nonatomic, strong) AFHTTPResponseSerializer <AFURLResponseSerialization> * responseSerializer; - -/** - An object constructed by the `responseSerializer` from the response and response data. Returns `nil` unless the operation `isFinished`, has a `response`, and has `responseData` with non-zero content length. If an error occurs during serialization, `nil` will be returned, and the `error` property will be populated with the serialization error. - */ -@property (readonly, nonatomic, strong) id responseObject; - -///----------------------------------------------------------- -/// @name Setting Completion Block Success / Failure Callbacks -///----------------------------------------------------------- - -/** - Sets the `completionBlock` property with a block that executes either the specified success or failure block, depending on the state of the request on completion. If `error` returns a value, which can be caused by an unacceptable status code or content type, then `failure` is executed. Otherwise, `success` is executed. - - This method should be overridden in subclasses in order to specify the response object passed into the success block. - - @param success The block to be executed on the completion of a successful request. This block has no return value and takes two arguments: the receiver operation and the object constructed from the response data of the request. - @param failure The block to be executed on the completion of an unsuccessful request. This block has no return value and takes two arguments: the receiver operation and the error that occurred during the request. - */ -- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; - -@end diff --git a/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFHTTPRequestOperation.m b/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFHTTPRequestOperation.m deleted file mode 100644 index 1de5812c..00000000 --- a/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFHTTPRequestOperation.m +++ /dev/null @@ -1,206 +0,0 @@ -// AFHTTPRequestOperation.m -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import "AFHTTPRequestOperation.h" - -static dispatch_queue_t http_request_operation_processing_queue() { - static dispatch_queue_t af_http_request_operation_processing_queue; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - af_http_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.http-request.processing", DISPATCH_QUEUE_CONCURRENT); - }); - - return af_http_request_operation_processing_queue; -} - -static dispatch_group_t http_request_operation_completion_group() { - static dispatch_group_t af_http_request_operation_completion_group; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - af_http_request_operation_completion_group = dispatch_group_create(); - }); - - return af_http_request_operation_completion_group; -} - -#pragma mark - - -@interface AFURLConnectionOperation () -@property (readwrite, nonatomic, strong) NSURLRequest *request; -@property (readwrite, nonatomic, strong) NSURLResponse *response; -@end - -@interface AFHTTPRequestOperation () -@property (readwrite, nonatomic, strong) NSHTTPURLResponse *response; -@property (readwrite, nonatomic, strong) id responseObject; -@property (readwrite, nonatomic, strong) NSError *responseSerializationError; -@property (readwrite, nonatomic, strong) NSRecursiveLock *lock; -@end - -@implementation AFHTTPRequestOperation -@dynamic lock; - -- (instancetype)initWithRequest:(NSURLRequest *)urlRequest { - self = [super initWithRequest:urlRequest]; - if (!self) { - return nil; - } - - self.responseSerializer = [AFHTTPResponseSerializer serializer]; - - return self; -} - -- (void)setResponseSerializer:(AFHTTPResponseSerializer <AFURLResponseSerialization> *)responseSerializer { - NSParameterAssert(responseSerializer); - - [self.lock lock]; - _responseSerializer = responseSerializer; - self.responseObject = nil; - self.responseSerializationError = nil; - [self.lock unlock]; -} - -- (id)responseObject { - [self.lock lock]; - if (!_responseObject && [self isFinished] && !self.error) { - NSError *error = nil; - self.responseObject = [self.responseSerializer responseObjectForResponse:self.response data:self.responseData error:&error]; - if (error) { - self.responseSerializationError = error; - } - } - [self.lock unlock]; - - return _responseObject; -} - -- (NSError *)error { - if (_responseSerializationError) { - return _responseSerializationError; - } else { - return [super error]; - } -} - -#pragma mark - AFHTTPRequestOperation - -- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure -{ - // completionBlock is manually nilled out in AFURLConnectionOperation to break the retain cycle. -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Warc-retain-cycles" -#pragma clang diagnostic ignored "-Wgnu" - self.completionBlock = ^{ - if (self.completionGroup) { - dispatch_group_enter(self.completionGroup); - } - - dispatch_async(http_request_operation_processing_queue(), ^{ - if (self.error) { - if (failure) { - dispatch_group_async(self.completionGroup ?: http_request_operation_completion_group(), self.completionQueue ?: dispatch_get_main_queue(), ^{ - failure(self, self.error); - }); - } - } else { - id responseObject = self.responseObject; - if (self.error) { - if (failure) { - dispatch_group_async(self.completionGroup ?: http_request_operation_completion_group(), self.completionQueue ?: dispatch_get_main_queue(), ^{ - failure(self, self.error); - }); - } - } else { - if (success) { - dispatch_group_async(self.completionGroup ?: http_request_operation_completion_group(), self.completionQueue ?: dispatch_get_main_queue(), ^{ - success(self, responseObject); - }); - } - } - } - - if (self.completionGroup) { - dispatch_group_leave(self.completionGroup); - } - }); - }; -#pragma clang diagnostic pop -} - -#pragma mark - AFURLRequestOperation - -- (void)pause { - [super pause]; - - u_int64_t offset = 0; - if ([self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey]) { - offset = [(NSNumber *)[self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey] unsignedLongLongValue]; - } else { - offset = [(NSData *)[self.outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey] length]; - } - - NSMutableURLRequest *mutableURLRequest = [self.request mutableCopy]; - if ([self.response respondsToSelector:@selector(allHeaderFields)] && [[self.response allHeaderFields] valueForKey:@"ETag"]) { - [mutableURLRequest setValue:[[self.response allHeaderFields] valueForKey:@"ETag"] forHTTPHeaderField:@"If-Range"]; - } - [mutableURLRequest setValue:[NSString stringWithFormat:@"bytes=%llu-", offset] forHTTPHeaderField:@"Range"]; - self.request = mutableURLRequest; -} - -#pragma mark - NSSecureCoding - -+ (BOOL)supportsSecureCoding { - return YES; -} - -- (id)initWithCoder:(NSCoder *)decoder { - self = [super initWithCoder:decoder]; - if (!self) { - return nil; - } - - self.responseSerializer = [decoder decodeObjectOfClass:[AFHTTPResponseSerializer class] forKey:NSStringFromSelector(@selector(responseSerializer))]; - - return self; -} - -- (void)encodeWithCoder:(NSCoder *)coder { - [super encodeWithCoder:coder]; - - [coder encodeObject:self.responseSerializer forKey:NSStringFromSelector(@selector(responseSerializer))]; -} - -#pragma mark - NSCopying - -- (id)copyWithZone:(NSZone *)zone { - AFHTTPRequestOperation *operation = [super copyWithZone:zone]; - - operation.responseSerializer = [self.responseSerializer copyWithZone:zone]; - operation.completionQueue = self.completionQueue; - operation.completionGroup = self.completionGroup; - - return operation; -} - -@end diff --git a/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFHTTPRequestOperationManager.h b/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFHTTPRequestOperationManager.h deleted file mode 100644 index 71b40646..00000000 --- a/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFHTTPRequestOperationManager.h +++ /dev/null @@ -1,308 +0,0 @@ -// AFHTTPRequestOperationManager.h -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import <Foundation/Foundation.h> -#import <SystemConfiguration/SystemConfiguration.h> -#import <Availability.h> - -#if __IPHONE_OS_VERSION_MIN_REQUIRED -#import <MobileCoreServices/MobileCoreServices.h> -#else -#import <CoreServices/CoreServices.h> -#endif - -#import "AFHTTPRequestOperation.h" -#import "AFURLResponseSerialization.h" -#import "AFURLRequestSerialization.h" -#import "AFSecurityPolicy.h" -#import "AFNetworkReachabilityManager.h" - -/** - `AFHTTPRequestOperationManager` encapsulates the common patterns of communicating with a web application over HTTP, including request creation, response serialization, network reachability monitoring, and security, as well as request operation management. - - ## Subclassing Notes - - 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. - - For developers targeting iOS 6 or Mac OS X 10.8 or earlier, `AFHTTPRequestOperationManager` may be used to similar effect. - - ## Methods to Override - - To change the behavior of all request operation construction for an `AFHTTPRequestOperationManager` subclass, override `HTTPRequestOperationWithRequest:success:failure`. - - ## Serialization - - 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>`. - - Responses received from the server are automatically validated and serialized by the `responseSerializers` property, which is an object conforming to `<AFURLResponseSerialization>` - - ## URL Construction Using Relative Paths - - 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:`. - - Below are a few examples of how `baseURL` and relative paths interact: - - NSURL *baseURL = [NSURL URLWithString:@"http://example.com/v1/"]; - [NSURL URLWithString:@"foo" relativeToURL:baseURL]; // http://example.com/v1/foo - [NSURL URLWithString:@"foo?bar=baz" relativeToURL:baseURL]; // http://example.com/v1/foo?bar=baz - [NSURL URLWithString:@"/foo" relativeToURL:baseURL]; // http://example.com/foo - [NSURL URLWithString:@"foo/" relativeToURL:baseURL]; // http://example.com/v1/foo - [NSURL URLWithString:@"/foo/" relativeToURL:baseURL]; // http://example.com/foo/ - [NSURL URLWithString:@"http://example2.com/" relativeToURL:baseURL]; // http://example2.com/ - - 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. - - ## Network Reachability Monitoring - - 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. - - ## NSSecureCoding & NSCopying Caveats - - `AFHTTPRequestOperationManager` conforms to the `NSSecureCoding` and `NSCopying` protocols, allowing operations to be archived to disk, and copied in memory, respectively. There are a few minor caveats to keep in mind, however: - - - Archives and copies of HTTP clients will be initialized with an empty operation queue. - - NSSecureCoding cannot serialize / deserialize block properties, so an archive of an HTTP client will not include any reachability callback block that may be set. - */ -@interface AFHTTPRequestOperationManager : NSObject <NSSecureCoding, NSCopying> - -/** - The URL used to monitor reachability, and construct requests from relative paths in methods like `requestWithMethod:URLString:parameters:`, and the `GET` / `POST` / et al. convenience methods. - */ -@property (readonly, nonatomic, strong) NSURL *baseURL; - -/** - 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. - - @warning `requestSerializer` must not be `nil`. - */ -@property (nonatomic, strong) AFHTTPRequestSerializer <AFURLRequestSerialization> * requestSerializer; - -/** - 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 a JSON serializer, which serializes data from responses with a `application/json` MIME type, and falls back to the raw data object. The serializer validates the status code to be in the `2XX` range, denoting success. If the response serializer generates an error in `-responseObjectForResponse:data:error:`, the `failure` callback of the session task or request operation will be executed; otherwise, the `success` callback will be executed. - - @warning `responseSerializer` must not be `nil`. - */ -@property (nonatomic, strong) AFHTTPResponseSerializer <AFURLResponseSerialization> * responseSerializer; - -/** - The operation queue on which request operations are scheduled and run. - */ -@property (nonatomic, strong) NSOperationQueue *operationQueue; - -///------------------------------- -/// @name Managing URL Credentials -///------------------------------- - -/** - Whether request operations should consult the credential storage for authenticating the connection. `YES` by default. - - @see AFURLConnectionOperation -shouldUseCredentialStorage - */ -@property (nonatomic, assign) BOOL shouldUseCredentialStorage; - -/** - The credential used by request operations for authentication challenges. - - @see AFURLConnectionOperation -credential - */ -@property (nonatomic, strong) NSURLCredential *credential; - -///------------------------------- -/// @name Managing Security Policy -///------------------------------- - -/** - The security policy used by created request operations to evaluate server trust for secure connections. `AFHTTPRequestOperationManager` uses the `defaultPolicy` unless otherwise specified. - */ -@property (nonatomic, strong) AFSecurityPolicy *securityPolicy; - -///------------------------------------ -/// @name Managing Network Reachability -///------------------------------------ - -/** - The network reachability manager. `AFHTTPRequestOperationManager` uses the `sharedManager` by default. - */ -@property (readwrite, nonatomic, strong) AFNetworkReachabilityManager *reachabilityManager; - -///------------------------------- -/// @name Managing Callback Queues -///------------------------------- - -/** - The dispatch queue for the `completionBlock` of request operations. If `NULL` (default), the main queue is used. - */ -@property (nonatomic, strong) dispatch_queue_t completionQueue; - -/** - The dispatch group for the `completionBlock` of request operations. If `NULL` (default), a private dispatch group is used. - */ -@property (nonatomic, strong) dispatch_group_t completionGroup; - -///--------------------------------------------- -/// @name Creating and Initializing HTTP Clients -///--------------------------------------------- - -/** - Creates and returns an `AFHTTPRequestOperationManager` object. - */ -+ (instancetype)manager; - -/** - Initializes an `AFHTTPRequestOperationManager` object with the specified base URL. - - This is the designated initializer. - - @param url The base URL for the HTTP client. - - @return The newly-initialized HTTP client - */ -- (instancetype)initWithBaseURL:(NSURL *)url; - -///--------------------------------------- -/// @name Managing HTTP Request Operations -///--------------------------------------- - -/** - Creates an `AFHTTPRequestOperation`, and sets the response serializers to that of the HTTP client. - - @param request The request object to be loaded asynchronously during execution of the operation. - @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request. - @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments:, the created request operation and the `NSError` object describing the network or parsing error that occurred. - */ -- (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)request - success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; - -///--------------------------- -/// @name Making HTTP Requests -///--------------------------- - -/** - Creates and runs an `AFHTTPRequestOperation` with a `GET` request. - - @param URLString The URL string used to create the request URL. - @param parameters The parameters to be encoded according to the client request serializer. - @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the request operation, and the response object created by the client response serializer. - @param failure A block object to be executed when the request operation 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 request operation and the error describing the network or parsing error that occurred. - - @see -HTTPRequestOperationWithRequest:success:failure: - */ -- (AFHTTPRequestOperation *)GET:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; - -/** - Creates and runs an `AFHTTPRequestOperation` with a `HEAD` request. - - @param URLString The URL string used to create the request URL. - @param parameters The parameters to be encoded according to the client request serializer. - @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes a single arguments: the request operation. - @param failure A block object to be executed when the request operation 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 request operation and the error describing the network or parsing error that occurred. - - @see -HTTPRequestOperationWithRequest:success:failure: - */ -- (AFHTTPRequestOperation *)HEAD:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(AFHTTPRequestOperation *operation))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; - -/** - Creates and runs an `AFHTTPRequestOperation` with a `POST` request. - - @param URLString The URL string used to create the request URL. - @param parameters The parameters to be encoded according to the client request serializer. - @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the request operation, and the response object created by the client response serializer. - @param failure A block object to be executed when the request operation 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 request operation and the error describing the network or parsing error that occurred. - - @see -HTTPRequestOperationWithRequest:success:failure: - */ -- (AFHTTPRequestOperation *)POST:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; - -/** - Creates and runs an `AFHTTPRequestOperation` with a multipart `POST` request. - - @param URLString The URL string used to create the request URL. - @param parameters The parameters to be encoded according to the client request serializer. - @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. - @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the request operation, and the response object created by the client response serializer. - @param failure A block object to be executed when the request operation 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 request operation and the error describing the network or parsing error that occurred. - - @see -HTTPRequestOperationWithRequest:success:failure: - */ -- (AFHTTPRequestOperation *)POST:(NSString *)URLString - parameters:(id)parameters - constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block - success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; - -/** - Creates and runs an `AFHTTPRequestOperation` with a `PUT` request. - - @param URLString The URL string used to create the request URL. - @param parameters The parameters to be encoded according to the client request serializer. - @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the request operation, and the response object created by the client response serializer. - @param failure A block object to be executed when the request operation 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 request operation and the error describing the network or parsing error that occurred. - - @see -HTTPRequestOperationWithRequest:success:failure: - */ -- (AFHTTPRequestOperation *)PUT:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; - -/** - Creates and runs an `AFHTTPRequestOperation` with a `PATCH` request. - - @param URLString The URL string used to create the request URL. - @param parameters The parameters to be encoded according to the client request serializer. - @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the request operation, and the response object created by the client response serializer. - @param failure A block object to be executed when the request operation 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 request operation and the error describing the network or parsing error that occurred. - - @see -HTTPRequestOperationWithRequest:success:failure: - */ -- (AFHTTPRequestOperation *)PATCH:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; - -/** - Creates and runs an `AFHTTPRequestOperation` with a `DELETE` request. - - @param URLString The URL string used to create the request URL. - @param parameters The parameters to be encoded according to the client request serializer. - @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the request operation, and the response object created by the client response serializer. - @param failure A block object to be executed when the request operation 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 request operation and the error describing the network or parsing error that occurred. - - @see -HTTPRequestOperationWithRequest:success:failure: - */ -- (AFHTTPRequestOperation *)DELETE:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; - -@end - diff --git a/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFHTTPRequestOperationManager.m b/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFHTTPRequestOperationManager.m deleted file mode 100644 index 4ae72754..00000000 --- a/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFHTTPRequestOperationManager.m +++ /dev/null @@ -1,253 +0,0 @@ -// AFHTTPRequestOperationManager.m -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import <Foundation/Foundation.h> - -#import "AFHTTPRequestOperationManager.h" -#import "AFHTTPRequestOperation.h" - -#import <Availability.h> -#import <Security/Security.h> - -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) -#import <UIKit/UIKit.h> -#endif - -@interface AFHTTPRequestOperationManager () -@property (readwrite, nonatomic, strong) NSURL *baseURL; -@end - -@implementation AFHTTPRequestOperationManager - -+ (instancetype)manager { - return [[self alloc] initWithBaseURL:nil]; -} - -- (instancetype)init { - return [self initWithBaseURL:nil]; -} - -- (instancetype)initWithBaseURL:(NSURL *)url { - self = [super init]; - if (!self) { - return nil; - } - - // Ensure terminal slash for baseURL path, so that NSURL +URLWithString:relativeToURL: works as expected - if ([[url path] length] > 0 && ![[url absoluteString] hasSuffix:@"/"]) { - url = [url URLByAppendingPathComponent:@""]; - } - - self.baseURL = url; - - self.requestSerializer = [AFHTTPRequestSerializer serializer]; - self.responseSerializer = [AFJSONResponseSerializer serializer]; - - self.securityPolicy = [AFSecurityPolicy defaultPolicy]; - - self.reachabilityManager = [AFNetworkReachabilityManager sharedManager]; - - self.operationQueue = [[NSOperationQueue alloc] init]; - - self.shouldUseCredentialStorage = YES; - - return self; -} - -#pragma mark - - -#ifdef _SYSTEMCONFIGURATION_H -#endif - -- (void)setRequestSerializer:(AFHTTPRequestSerializer <AFURLRequestSerialization> *)requestSerializer { - NSParameterAssert(requestSerializer); - - _requestSerializer = requestSerializer; -} - -- (void)setResponseSerializer:(AFHTTPResponseSerializer <AFURLResponseSerialization> *)responseSerializer { - NSParameterAssert(responseSerializer); - - _responseSerializer = responseSerializer; -} - -#pragma mark - - -- (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)request - success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure -{ - AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; - operation.responseSerializer = self.responseSerializer; - operation.shouldUseCredentialStorage = self.shouldUseCredentialStorage; - operation.credential = self.credential; - operation.securityPolicy = self.securityPolicy; - - [operation setCompletionBlockWithSuccess:success failure:failure]; - operation.completionQueue = self.completionQueue; - operation.completionGroup = self.completionGroup; - - return operation; -} - -#pragma mark - - -- (AFHTTPRequestOperation *)GET:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure -{ - NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"GET" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:nil]; - AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure]; - - [self.operationQueue addOperation:operation]; - - return operation; -} - -- (AFHTTPRequestOperation *)HEAD:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(AFHTTPRequestOperation *operation))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure -{ - NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"HEAD" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:nil]; - AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *requestOperation, __unused id responseObject) { - if (success) { - success(requestOperation); - } - } failure:failure]; - - [self.operationQueue addOperation:operation]; - - return operation; -} - -- (AFHTTPRequestOperation *)POST:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure -{ - NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:nil]; - AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure]; - - [self.operationQueue addOperation:operation]; - - return operation; -} - -- (AFHTTPRequestOperation *)POST:(NSString *)URLString - parameters:(id)parameters - constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block - success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure -{ - NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters constructingBodyWithBlock:block error:nil]; - AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure]; - - [self.operationQueue addOperation:operation]; - - return operation; -} - -- (AFHTTPRequestOperation *)PUT:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure -{ - NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"PUT" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:nil]; - AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure]; - - [self.operationQueue addOperation:operation]; - - return operation; -} - -- (AFHTTPRequestOperation *)PATCH:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure -{ - NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"PATCH" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:nil]; - AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure]; - - [self.operationQueue addOperation:operation]; - - return operation; -} - -- (AFHTTPRequestOperation *)DELETE:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure -{ - NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"DELETE" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:nil]; - AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure]; - - [self.operationQueue addOperation:operation]; - - return operation; -} - -#pragma mark - NSObject - -- (NSString *)description { - return [NSString stringWithFormat:@"<%@: %p, baseURL: %@, operationQueue: %@>", NSStringFromClass([self class]), self, [self.baseURL absoluteString], self.operationQueue]; -} - -#pragma mark - NSSecureCoding - -+ (BOOL)supportsSecureCoding { - return YES; -} - -- (id)initWithCoder:(NSCoder *)decoder { - NSURL *baseURL = [decoder decodeObjectForKey:NSStringFromSelector(@selector(baseURL))]; - - self = [self initWithBaseURL:baseURL]; - if (!self) { - return nil; - } - - self.requestSerializer = [decoder decodeObjectOfClass:[AFHTTPRequestSerializer class] forKey:NSStringFromSelector(@selector(requestSerializer))]; - self.responseSerializer = [decoder decodeObjectOfClass:[AFHTTPResponseSerializer class] forKey:NSStringFromSelector(@selector(responseSerializer))]; - - return self; -} - -- (void)encodeWithCoder:(NSCoder *)coder { - [coder encodeObject:self.baseURL forKey:NSStringFromSelector(@selector(baseURL))]; - [coder encodeObject:self.requestSerializer forKey:NSStringFromSelector(@selector(requestSerializer))]; - [coder encodeObject:self.responseSerializer forKey:NSStringFromSelector(@selector(responseSerializer))]; -} - -#pragma mark - NSCopying - -- (id)copyWithZone:(NSZone *)zone { - AFHTTPRequestOperationManager *HTTPClient = [[[self class] allocWithZone:zone] initWithBaseURL:self.baseURL]; - - HTTPClient.requestSerializer = [self.requestSerializer copyWithZone:zone]; - HTTPClient.responseSerializer = [self.responseSerializer copyWithZone:zone]; - - return HTTPClient; -} - -@end diff --git a/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFHTTPSessionManager.h b/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFHTTPSessionManager.h deleted file mode 100644 index e2cfe3df..00000000 --- a/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFHTTPSessionManager.h +++ /dev/null @@ -1,238 +0,0 @@ -// AFHTTPSessionManager.h -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import <Foundation/Foundation.h> -#import <SystemConfiguration/SystemConfiguration.h> -#import <Availability.h> - -#if __IPHONE_OS_VERSION_MIN_REQUIRED -#import <MobileCoreServices/MobileCoreServices.h> -#else -#import <CoreServices/CoreServices.h> -#endif - -#import "AFURLSessionManager.h" - -/** - `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. - - ## Subclassing Notes - - 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. - - For developers targeting iOS 6 or Mac OS X 10.8 or earlier, `AFHTTPRequestOperationManager` may be used to similar effect. - - ## Methods to Override - - 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:`. - - ## Serialization - - 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>`. - - Responses received from the server are automatically validated and serialized by the `responseSerializers` property, which is an object conforming to `<AFURLResponseSerialization>` - - ## URL Construction Using Relative Paths - - 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:`. - - Below are a few examples of how `baseURL` and relative paths interact: - - NSURL *baseURL = [NSURL URLWithString:@"http://example.com/v1/"]; - [NSURL URLWithString:@"foo" relativeToURL:baseURL]; // http://example.com/v1/foo - [NSURL URLWithString:@"foo?bar=baz" relativeToURL:baseURL]; // http://example.com/v1/foo?bar=baz - [NSURL URLWithString:@"/foo" relativeToURL:baseURL]; // http://example.com/foo - [NSURL URLWithString:@"foo/" relativeToURL:baseURL]; // http://example.com/v1/foo - [NSURL URLWithString:@"/foo/" relativeToURL:baseURL]; // http://example.com/foo/ - [NSURL URLWithString:@"http://example2.com/" relativeToURL:baseURL]; // http://example2.com/ - - 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. - */ - -#if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000) || (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1090) - -@interface AFHTTPSessionManager : AFURLSessionManager <NSSecureCoding, NSCopying> - -/** - The URL used to monitor reachability, and construct requests from relative paths in methods like `requestWithMethod:URLString:parameters:`, and the `GET` / `POST` / et al. convenience methods. - */ -@property (readonly, nonatomic, strong) NSURL *baseURL; - -/** - 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. - - @warning `requestSerializer` must not be `nil`. - */ -@property (nonatomic, strong) AFHTTPRequestSerializer <AFURLRequestSerialization> * requestSerializer; - -/** - 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`. - - @warning `responseSerializer` must not be `nil`. - */ -@property (nonatomic, strong) AFHTTPResponseSerializer <AFURLResponseSerialization> * responseSerializer; - -///--------------------- -/// @name Initialization -///--------------------- - -/** - Creates and returns an `AFHTTPSessionManager` object. - */ -+ (instancetype)manager; - -/** - Initializes an `AFHTTPSessionManager` object with the specified base URL. - - @param url The base URL for the HTTP client. - - @return The newly-initialized HTTP client - */ -- (instancetype)initWithBaseURL:(NSURL *)url; - -/** - Initializes an `AFHTTPSessionManager` object with the specified base URL. - - This is the designated initializer. - - @param url The base URL for the HTTP client. - @param configuration The configuration used to create the managed session. - - @return The newly-initialized HTTP client - */ -- (instancetype)initWithBaseURL:(NSURL *)url - sessionConfiguration:(NSURLSessionConfiguration *)configuration; - -///--------------------------- -/// @name Making HTTP Requests -///--------------------------- - -/** - Creates and runs an `NSURLSessionDataTask` with a `GET` request. - - @param URLString The URL string used to create the request URL. - @param parameters The parameters to be encoded according to the client request serializer. - @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. - @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. - - @see -dataTaskWithRequest:completionHandler: - */ -- (NSURLSessionDataTask *)GET:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(NSURLSessionDataTask *task, id responseObject))success - failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure; - -/** - Creates and runs an `NSURLSessionDataTask` with a `HEAD` request. - - @param URLString The URL string used to create the request URL. - @param parameters The parameters to be encoded according to the client request serializer. - @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. - @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. - - @see -dataTaskWithRequest:completionHandler: - */ -- (NSURLSessionDataTask *)HEAD:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(NSURLSessionDataTask *task))success - failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure; - -/** - Creates and runs an `NSURLSessionDataTask` with a `POST` request. - - @param URLString The URL string used to create the request URL. - @param parameters The parameters to be encoded according to the client request serializer. - @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. - @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. - - @see -dataTaskWithRequest:completionHandler: - */ -- (NSURLSessionDataTask *)POST:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(NSURLSessionDataTask *task, id responseObject))success - failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure; - -/** - Creates and runs an `NSURLSessionDataTask` with a multipart `POST` request. - - @param URLString The URL string used to create the request URL. - @param parameters The parameters to be encoded according to the client request serializer. - @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. - @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. - @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. - - @see -dataTaskWithRequest:completionHandler: - */ -- (NSURLSessionDataTask *)POST:(NSString *)URLString - parameters:(id)parameters - constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block - success:(void (^)(NSURLSessionDataTask *task, id responseObject))success - failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure; - -/** - Creates and runs an `NSURLSessionDataTask` with a `PUT` request. - - @param URLString The URL string used to create the request URL. - @param parameters The parameters to be encoded according to the client request serializer. - @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. - @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. - - @see -dataTaskWithRequest:completionHandler: - */ -- (NSURLSessionDataTask *)PUT:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(NSURLSessionDataTask *task, id responseObject))success - failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure; - -/** - Creates and runs an `NSURLSessionDataTask` with a `PATCH` request. - - @param URLString The URL string used to create the request URL. - @param parameters The parameters to be encoded according to the client request serializer. - @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. - @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. - - @see -dataTaskWithRequest:completionHandler: - */ -- (NSURLSessionDataTask *)PATCH:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(NSURLSessionDataTask *task, id responseObject))success - failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure; - -/** - Creates and runs an `NSURLSessionDataTask` with a `DELETE` request. - - @param URLString The URL string used to create the request URL. - @param parameters The parameters to be encoded according to the client request serializer. - @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. - @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. - - @see -dataTaskWithRequest:completionHandler: - */ -- (NSURLSessionDataTask *)DELETE:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(NSURLSessionDataTask *task, id responseObject))success - failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure; - -@end - -#endif diff --git a/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFHTTPSessionManager.m b/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFHTTPSessionManager.m deleted file mode 100644 index 6413297d..00000000 --- a/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFHTTPSessionManager.m +++ /dev/null @@ -1,321 +0,0 @@ -// AFHTTPSessionManager.m -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import "AFHTTPSessionManager.h" - -#if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000) || (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1090) - -#import "AFURLRequestSerialization.h" -#import "AFURLResponseSerialization.h" - -#import <Availability.h> -#import <Security/Security.h> - -#ifdef _SYSTEMCONFIGURATION_H -#import <netinet/in.h> -#import <netinet6/in6.h> -#import <arpa/inet.h> -#import <ifaddrs.h> -#import <netdb.h> -#endif - -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) -#import <UIKit/UIKit.h> -#endif - -@interface AFHTTPSessionManager () -@property (readwrite, nonatomic, strong) NSURL *baseURL; -@end - -@implementation AFHTTPSessionManager - -+ (instancetype)manager { - return [[[self class] alloc] initWithBaseURL:nil]; -} - -- (instancetype)init { - return [self initWithBaseURL:nil]; -} - -- (instancetype)initWithBaseURL:(NSURL *)url { - return [self initWithBaseURL:url sessionConfiguration:nil]; -} - -- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration { - return [self initWithBaseURL:nil sessionConfiguration:configuration]; -} - -- (instancetype)initWithBaseURL:(NSURL *)url - sessionConfiguration:(NSURLSessionConfiguration *)configuration -{ - self = [super initWithSessionConfiguration:configuration]; - if (!self) { - return nil; - } - - // Ensure terminal slash for baseURL path, so that NSURL +URLWithString:relativeToURL: works as expected - if ([[url path] length] > 0 && ![[url absoluteString] hasSuffix:@"/"]) { - url = [url URLByAppendingPathComponent:@""]; - } - - self.baseURL = url; - - self.requestSerializer = [AFHTTPRequestSerializer serializer]; - self.responseSerializer = [AFJSONResponseSerializer serializer]; - - return self; -} - -#pragma mark - - -#ifdef _SYSTEMCONFIGURATION_H -#endif - -- (void)setRequestSerializer:(AFHTTPRequestSerializer <AFURLRequestSerialization> *)requestSerializer { - NSParameterAssert(requestSerializer); - - _requestSerializer = requestSerializer; -} - -- (void)setResponseSerializer:(AFHTTPResponseSerializer <AFURLResponseSerialization> *)responseSerializer { - NSParameterAssert(responseSerializer); - - [super setResponseSerializer:responseSerializer]; -} - -#pragma mark - - -- (NSURLSessionDataTask *)GET:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(NSURLSessionDataTask *task, id responseObject))success - failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure -{ - NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"GET" URLString:URLString parameters:parameters success:success failure:failure]; - - [dataTask resume]; - - return dataTask; -} - -- (NSURLSessionDataTask *)HEAD:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(NSURLSessionDataTask *task))success - failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure -{ - NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"HEAD" URLString:URLString parameters:parameters success:^(NSURLSessionDataTask *task, __unused id responseObject) { - if (success) { - success(task); - } - } failure:failure]; - - [dataTask resume]; - - return dataTask; -} - -- (NSURLSessionDataTask *)POST:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(NSURLSessionDataTask *task, id responseObject))success - failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure -{ - NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"POST" URLString:URLString parameters:parameters success:success failure:failure]; - - [dataTask resume]; - - return dataTask; -} - -- (NSURLSessionDataTask *)POST:(NSString *)URLString - parameters:(id)parameters - constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block - success:(void (^)(NSURLSessionDataTask *task, id responseObject))success - failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure -{ - NSError *serializationError = nil; - NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters constructingBodyWithBlock:block error:&serializationError]; - if (serializationError) { - if (failure) { -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wgnu" - dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{ - failure(nil, serializationError); - }); -#pragma clang diagnostic pop - } - - return nil; - } - - __block NSURLSessionDataTask *task = [self uploadTaskWithStreamedRequest:request progress:nil completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) { - if (error) { - if (failure) { - failure(task, error); - } - } else { - if (success) { - success(task, responseObject); - } - } - }]; - - [task resume]; - - return task; -} - -- (NSURLSessionDataTask *)PUT:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(NSURLSessionDataTask *task, id responseObject))success - failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure -{ - NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"PUT" URLString:URLString parameters:parameters success:success failure:failure]; - - [dataTask resume]; - - return dataTask; -} - -- (NSURLSessionDataTask *)PATCH:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(NSURLSessionDataTask *task, id responseObject))success - failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure -{ - NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"PATCH" URLString:URLString parameters:parameters success:success failure:failure]; - - [dataTask resume]; - - return dataTask; -} - -- (NSURLSessionDataTask *)DELETE:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(NSURLSessionDataTask *task, id responseObject))success - failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure -{ - NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"DELETE" URLString:URLString parameters:parameters success:success failure:failure]; - - [dataTask resume]; - - return dataTask; -} - -- (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method - URLString:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(NSURLSessionDataTask *, id))success - failure:(void (^)(NSURLSessionDataTask *, NSError *))failure -{ - NSError *serializationError = nil; - NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:method URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:&serializationError]; - if (serializationError) { - if (failure) { -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wgnu" - dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{ - failure(nil, serializationError); - }); -#pragma clang diagnostic pop - } - - return nil; - } - - __block NSURLSessionDataTask *dataTask = nil; - dataTask = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) { - if (error) { - if (failure) { - failure(dataTask, error); - } - } else { - if (success) { - success(dataTask, responseObject); - } - } - }]; - - return dataTask; -} - -#pragma mark - NSObject - -- (NSString *)description { - return [NSString stringWithFormat:@"<%@: %p, baseURL: %@, session: %@, operationQueue: %@>", NSStringFromClass([self class]), self, [self.baseURL absoluteString], self.session, self.operationQueue]; -} - -#pragma mark - NSSecureCoding - -+ (BOOL)supportsSecureCoding { - return YES; -} - -- (id)initWithCoder:(NSCoder *)decoder { - NSURL *baseURL = [decoder decodeObjectOfClass:[NSURL class] forKey:NSStringFromSelector(@selector(baseURL))]; - NSURLSessionConfiguration *configuration = [decoder decodeObjectOfClass:[NSURLSessionConfiguration class] forKey:@"sessionConfiguration"]; - if (!configuration) { - NSString *configurationIdentifier = [decoder decodeObjectOfClass:[NSString class] forKey:@"identifier"]; - if (configurationIdentifier) { -#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) - configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:configurationIdentifier]; -#else - configuration = [NSURLSessionConfiguration backgroundSessionConfiguration:configurationIdentifier]; -#endif - } - } - - self = [self initWithBaseURL:baseURL sessionConfiguration:configuration]; - if (!self) { - return nil; - } - - self.requestSerializer = [decoder decodeObjectOfClass:[AFHTTPRequestSerializer class] forKey:NSStringFromSelector(@selector(requestSerializer))]; - self.responseSerializer = [decoder decodeObjectOfClass:[AFHTTPResponseSerializer class] forKey:NSStringFromSelector(@selector(responseSerializer))]; - - return self; -} - -- (void)encodeWithCoder:(NSCoder *)coder { - [super encodeWithCoder:coder]; - - [coder encodeObject:self.baseURL forKey:NSStringFromSelector(@selector(baseURL))]; - if ([self.session.configuration conformsToProtocol:@protocol(NSCoding)]) { - [coder encodeObject:self.session.configuration forKey:@"sessionConfiguration"]; - } else { - [coder encodeObject:self.session.configuration.identifier forKey:@"identifier"]; - } - [coder encodeObject:self.requestSerializer forKey:NSStringFromSelector(@selector(requestSerializer))]; - [coder encodeObject:self.responseSerializer forKey:NSStringFromSelector(@selector(responseSerializer))]; -} - -#pragma mark - NSCopying - -- (id)copyWithZone:(NSZone *)zone { - AFHTTPSessionManager *HTTPClient = [[[self class] allocWithZone:zone] initWithBaseURL:self.baseURL sessionConfiguration:self.session.configuration]; - - HTTPClient.requestSerializer = [self.requestSerializer copyWithZone:zone]; - HTTPClient.responseSerializer = [self.responseSerializer copyWithZone:zone]; - - return HTTPClient; -} - -@end - -#endif diff --git a/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFNetworkReachabilityManager.h b/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFNetworkReachabilityManager.h deleted file mode 100644 index c92c21c7..00000000 --- a/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFNetworkReachabilityManager.h +++ /dev/null @@ -1,193 +0,0 @@ -// AFNetworkReachabilityManager.h -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import <Foundation/Foundation.h> -#import <SystemConfiguration/SystemConfiguration.h> - -typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) { - AFNetworkReachabilityStatusUnknown = -1, - AFNetworkReachabilityStatusNotReachable = 0, - AFNetworkReachabilityStatusReachableViaWWAN = 1, - AFNetworkReachabilityStatusReachableViaWiFi = 2, -}; - -/** - `AFNetworkReachabilityManager` monitors the reachability of domains, and addresses for both WWAN and WiFi network interfaces. - - 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. - - See Apple's Reachability Sample Code (https://developer.apple.com/library/ios/samplecode/reachability/) - - @warning Instances of `AFNetworkReachabilityManager` must be started with `-startMonitoring` before reachability status can be determined. - */ -@interface AFNetworkReachabilityManager : NSObject - -/** - The current network reachability status. - */ -@property (readonly, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus; - -/** - Whether or not the network is currently reachable. - */ -@property (readonly, nonatomic, assign, getter = isReachable) BOOL reachable; - -/** - Whether or not the network is currently reachable via WWAN. - */ -@property (readonly, nonatomic, assign, getter = isReachableViaWWAN) BOOL reachableViaWWAN; - -/** - Whether or not the network is currently reachable via WiFi. - */ -@property (readonly, nonatomic, assign, getter = isReachableViaWiFi) BOOL reachableViaWiFi; - -///--------------------- -/// @name Initialization -///--------------------- - -/** - Returns the shared network reachability manager. - */ -+ (instancetype)sharedManager; - -/** - Creates and returns a network reachability manager for the specified domain. - - @param domain The domain used to evaluate network reachability. - - @return An initialized network reachability manager, actively monitoring the specified domain. - */ -+ (instancetype)managerForDomain:(NSString *)domain; - -/** - Creates and returns a network reachability manager for the socket address. - - @param address The socket address (`sockaddr_in`) used to evaluate network reachability. - - @return An initialized network reachability manager, actively monitoring the specified socket address. - */ -+ (instancetype)managerForAddress:(const void *)address; - -/** - Initializes an instance of a network reachability manager from the specified reachability object. - - @param reachability The reachability object to monitor. - - @return An initialized network reachability manager, actively monitoring the specified reachability. - */ -- (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability; - -///-------------------------------------------------- -/// @name Starting & Stopping Reachability Monitoring -///-------------------------------------------------- - -/** - Starts monitoring for changes in network reachability status. - */ -- (void)startMonitoring; - -/** - Stops monitoring for changes in network reachability status. - */ -- (void)stopMonitoring; - -///------------------------------------------------- -/// @name Getting Localized Reachability Description -///------------------------------------------------- - -/** - Returns a localized string representation of the current network reachability status. - */ -- (NSString *)localizedNetworkReachabilityStatusString; - -///--------------------------------------------------- -/// @name Setting Network Reachability Change Callback -///--------------------------------------------------- - -/** - Sets a callback to be executed when the network availability of the `baseURL` host changes. - - @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`. - */ -- (void)setReachabilityStatusChangeBlock:(void (^)(AFNetworkReachabilityStatus status))block; - -@end - -///---------------- -/// @name Constants -///---------------- - -/** - ## Network Reachability - - The following constants are provided by `AFNetworkReachabilityManager` as possible network reachability statuses. - - enum { - AFNetworkReachabilityStatusUnknown, - AFNetworkReachabilityStatusNotReachable, - AFNetworkReachabilityStatusReachableViaWWAN, - AFNetworkReachabilityStatusReachableViaWiFi, - } - - `AFNetworkReachabilityStatusUnknown` - The `baseURL` host reachability is not known. - - `AFNetworkReachabilityStatusNotReachable` - The `baseURL` host cannot be reached. - - `AFNetworkReachabilityStatusReachableViaWWAN` - The `baseURL` host can be reached via a cellular connection, such as EDGE or GPRS. - - `AFNetworkReachabilityStatusReachableViaWiFi` - The `baseURL` host can be reached via a Wi-Fi connection. - - ### Keys for Notification UserInfo Dictionary - - Strings that are used as keys in a `userInfo` dictionary in a network reachability status change notification. - - `AFNetworkingReachabilityNotificationStatusItem` - A key in the userInfo dictionary in a `AFNetworkingReachabilityDidChangeNotification` notification. - The corresponding value is an `NSNumber` object representing the `AFNetworkReachabilityStatus` value for the current reachability status. - */ - -///-------------------- -/// @name Notifications -///-------------------- - -/** - Posted when network reachability changes. - 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. - - @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`). - */ -extern NSString * const AFNetworkingReachabilityDidChangeNotification; -extern NSString * const AFNetworkingReachabilityNotificationStatusItem; - -///-------------------- -/// @name Functions -///-------------------- - -/** - Returns a localized string representation of an `AFNetworkReachabilityStatus` value. - */ -extern NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status); diff --git a/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFNetworkReachabilityManager.m b/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFNetworkReachabilityManager.m deleted file mode 100644 index 1da14828..00000000 --- a/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFNetworkReachabilityManager.m +++ /dev/null @@ -1,259 +0,0 @@ -// AFNetworkReachabilityManager.m -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import "AFNetworkReachabilityManager.h" - -#import <netinet/in.h> -#import <netinet6/in6.h> -#import <arpa/inet.h> -#import <ifaddrs.h> -#import <netdb.h> - -NSString * const AFNetworkingReachabilityDidChangeNotification = @"com.alamofire.networking.reachability.change"; -NSString * const AFNetworkingReachabilityNotificationStatusItem = @"AFNetworkingReachabilityNotificationStatusItem"; - -typedef void (^AFNetworkReachabilityStatusBlock)(AFNetworkReachabilityStatus status); - -typedef NS_ENUM(NSUInteger, AFNetworkReachabilityAssociation) { - AFNetworkReachabilityForAddress = 1, - AFNetworkReachabilityForAddressPair = 2, - AFNetworkReachabilityForName = 3, -}; - -NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status) { - switch (status) { - case AFNetworkReachabilityStatusNotReachable: - return NSLocalizedStringFromTable(@"Not Reachable", @"AFNetworking", nil); - case AFNetworkReachabilityStatusReachableViaWWAN: - return NSLocalizedStringFromTable(@"Reachable via WWAN", @"AFNetworking", nil); - case AFNetworkReachabilityStatusReachableViaWiFi: - return NSLocalizedStringFromTable(@"Reachable via WiFi", @"AFNetworking", nil); - case AFNetworkReachabilityStatusUnknown: - default: - return NSLocalizedStringFromTable(@"Unknown", @"AFNetworking", nil); - } -} - -static AFNetworkReachabilityStatus AFNetworkReachabilityStatusForFlags(SCNetworkReachabilityFlags flags) { - BOOL isReachable = ((flags & kSCNetworkReachabilityFlagsReachable) != 0); - BOOL needsConnection = ((flags & kSCNetworkReachabilityFlagsConnectionRequired) != 0); - BOOL canConnectionAutomatically = (((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) || ((flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0)); - BOOL canConnectWithoutUserInteraction = (canConnectionAutomatically && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0); - BOOL isNetworkReachable = (isReachable && (!needsConnection || canConnectWithoutUserInteraction)); - - AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusUnknown; - if (isNetworkReachable == NO) { - status = AFNetworkReachabilityStatusNotReachable; - } -#if TARGET_OS_IPHONE - else if ((flags & kSCNetworkReachabilityFlagsIsWWAN) != 0) { - status = AFNetworkReachabilityStatusReachableViaWWAN; - } -#endif - else { - status = AFNetworkReachabilityStatusReachableViaWiFi; - } - - return status; -} - -static void AFNetworkReachabilityCallback(SCNetworkReachabilityRef __unused target, SCNetworkReachabilityFlags flags, void *info) { - AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusForFlags(flags); - AFNetworkReachabilityStatusBlock block = (__bridge AFNetworkReachabilityStatusBlock)info; - if (block) { - block(status); - } - - - dispatch_async(dispatch_get_main_queue(), ^{ - NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; - [notificationCenter postNotificationName:AFNetworkingReachabilityDidChangeNotification object:nil userInfo:@{ AFNetworkingReachabilityNotificationStatusItem: @(status) }]; - }); - -} - -static const void * AFNetworkReachabilityRetainCallback(const void *info) { - return Block_copy(info); -} - -static void AFNetworkReachabilityReleaseCallback(const void *info) { - if (info) { - Block_release(info); - } -} - -@interface AFNetworkReachabilityManager () -@property (readwrite, nonatomic, assign) SCNetworkReachabilityRef networkReachability; -@property (readwrite, nonatomic, assign) AFNetworkReachabilityAssociation networkReachabilityAssociation; -@property (readwrite, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus; -@property (readwrite, nonatomic, copy) AFNetworkReachabilityStatusBlock networkReachabilityStatusBlock; -@end - -@implementation AFNetworkReachabilityManager - -+ (instancetype)sharedManager { - static AFNetworkReachabilityManager *_sharedManager = nil; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - struct sockaddr_in address; - bzero(&address, sizeof(address)); - address.sin_len = sizeof(address); - address.sin_family = AF_INET; - - _sharedManager = [self managerForAddress:&address]; - }); - - return _sharedManager; -} - -+ (instancetype)managerForDomain:(NSString *)domain { - SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [domain UTF8String]); - - AFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability]; - manager.networkReachabilityAssociation = AFNetworkReachabilityForName; - - return manager; -} - -+ (instancetype)managerForAddress:(const void *)address { - SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr *)address); - - AFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability]; - manager.networkReachabilityAssociation = AFNetworkReachabilityForAddress; - - return manager; -} - -- (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability { - self = [super init]; - if (!self) { - return nil; - } - - self.networkReachability = reachability; - self.networkReachabilityStatus = AFNetworkReachabilityStatusUnknown; - - return self; -} - -- (void)dealloc { - [self stopMonitoring]; - - if (_networkReachability) { - CFRelease(_networkReachability); - _networkReachability = NULL; - } -} - -#pragma mark - - -- (BOOL)isReachable { - return [self isReachableViaWWAN] || [self isReachableViaWiFi]; -} - -- (BOOL)isReachableViaWWAN { - return self.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWWAN; -} - -- (BOOL)isReachableViaWiFi { - return self.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWiFi; -} - -#pragma mark - - -- (void)startMonitoring { - [self stopMonitoring]; - - if (!self.networkReachability) { - return; - } - - __weak __typeof(self)weakSelf = self; - AFNetworkReachabilityStatusBlock callback = ^(AFNetworkReachabilityStatus status) { - __strong __typeof(weakSelf)strongSelf = weakSelf; - - strongSelf.networkReachabilityStatus = status; - if (strongSelf.networkReachabilityStatusBlock) { - strongSelf.networkReachabilityStatusBlock(status); - } - - }; - - SCNetworkReachabilityContext context = {0, (__bridge void *)callback, AFNetworkReachabilityRetainCallback, AFNetworkReachabilityReleaseCallback, NULL}; - SCNetworkReachabilitySetCallback(self.networkReachability, AFNetworkReachabilityCallback, &context); - SCNetworkReachabilityScheduleWithRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes); - - switch (self.networkReachabilityAssociation) { - case AFNetworkReachabilityForName: - break; - case AFNetworkReachabilityForAddress: - case AFNetworkReachabilityForAddressPair: - default: { - dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0),^{ - SCNetworkReachabilityFlags flags; - SCNetworkReachabilityGetFlags(self.networkReachability, &flags); - AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusForFlags(flags); - dispatch_async(dispatch_get_main_queue(), ^{ - callback(status); - - NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; - [notificationCenter postNotificationName:AFNetworkingReachabilityDidChangeNotification object:nil userInfo:@{ AFNetworkingReachabilityNotificationStatusItem: @(status) }]; - - - }); - }); - } - break; - } -} - -- (void)stopMonitoring { - if (!self.networkReachability) { - return; - } - - SCNetworkReachabilityUnscheduleFromRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes); -} - -#pragma mark - - -- (NSString *)localizedNetworkReachabilityStatusString { - return AFStringFromNetworkReachabilityStatus(self.networkReachabilityStatus); -} - -#pragma mark - - -- (void)setReachabilityStatusChangeBlock:(void (^)(AFNetworkReachabilityStatus status))block { - self.networkReachabilityStatusBlock = block; -} - -#pragma mark - NSKeyValueObserving - -+ (NSSet *)keyPathsForValuesAffectingValueForKey:(NSString *)key { - if ([key isEqualToString:@"reachable"] || [key isEqualToString:@"reachableViaWWAN"] || [key isEqualToString:@"reachableViaWiFi"]) { - return [NSSet setWithObject:@"networkReachabilityStatus"]; - } - - return [super keyPathsForValuesAffectingValueForKey:key]; -} - -@end diff --git a/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFNetworking.h b/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFNetworking.h deleted file mode 100644 index 693ffbb5..00000000 --- a/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFNetworking.h +++ /dev/null @@ -1,44 +0,0 @@ -// AFNetworking.h -// -// Copyright (c) 2013 AFNetworking (http://afnetworking.com/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import <Foundation/Foundation.h> -#import <Availability.h> - -#ifndef _AFNETWORKING_ - #define _AFNETWORKING_ - - #import "AFURLRequestSerialization.h" - #import "AFURLResponseSerialization.h" - #import "AFSecurityPolicy.h" - #import "AFNetworkReachabilityManager.h" - - #import "AFURLConnectionOperation.h" - #import "AFHTTPRequestOperation.h" - #import "AFHTTPRequestOperationManager.h" - -#if ( ( defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1090) || \ - ( defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000 ) ) - #import "AFURLSessionManager.h" - #import "AFHTTPSessionManager.h" -#endif - -#endif /* _AFNETWORKING_ */ diff --git a/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFSecurityPolicy.h b/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFSecurityPolicy.h deleted file mode 100644 index 49c8209e..00000000 --- a/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFSecurityPolicy.h +++ /dev/null @@ -1,143 +0,0 @@ -// AFSecurity.h -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import <Foundation/Foundation.h> -#import <Security/Security.h> - -typedef NS_ENUM(NSUInteger, AFSSLPinningMode) { - AFSSLPinningModeNone, - AFSSLPinningModePublicKey, - AFSSLPinningModeCertificate, -}; - -/** - `AFSecurityPolicy` evaluates server trust against pinned X.509 certificates and public keys over secure connections. - - 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. - */ -@interface AFSecurityPolicy : NSObject - -/** - The criteria by which server trust should be evaluated against the pinned SSL certificates. Defaults to `AFSSLPinningModeNone`. - */ -@property (nonatomic, assign) AFSSLPinningMode SSLPinningMode; - -/** - Whether to evaluate an entire SSL certificate chain, or just the leaf certificate. Defaults to `YES`. - */ -@property (nonatomic, assign) BOOL validatesCertificateChain; - -/** - The certificates used to evaluate server trust according to the SSL pinning mode. By default, this property is set to any (`.cer`) certificates included in the app bundle. - */ -@property (nonatomic, strong) NSArray *pinnedCertificates; - -/** - Whether or not to trust servers with an invalid or expired SSL certificates. Defaults to `NO`. - */ -@property (nonatomic, assign) BOOL allowInvalidCertificates; - -/** - Whether or not to validate the domain name in the certificates CN field. Defaults to `YES` for `AFSSLPinningModePublicKey` or `AFSSLPinningModeCertificate`, otherwise `NO`. - */ -@property (nonatomic, assign) BOOL validatesDomainName; - -///----------------------------------------- -/// @name Getting Specific Security Policies -///----------------------------------------- - -/** - Returns the shared default security policy, which does not accept invalid certificates, and does not validate against pinned certificates or public keys. - - @return The default security policy. - */ -+ (instancetype)defaultPolicy; - -///--------------------- -/// @name Initialization -///--------------------- - -/** - Creates and returns a security policy with the specified pinning mode. - - @param pinningMode The SSL pinning mode. - - @return A new security policy. - */ -+ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode; - -///------------------------------ -/// @name Evaluating Server Trust -///------------------------------ - -/** - Whether or not the specified server trust should be accepted, based on the security policy. - - This method should be used when responding to an authentication challenge from a server. - - @param serverTrust The X.509 certificate trust of the server. - - @return Whether or not to trust the server. - - @warning This method has been deprecated in favor of `-evaluateServerTrust:forDomain:`. - */ -- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust DEPRECATED_ATTRIBUTE; - -/** - Whether or not the specified server trust should be accepted, based on the security policy. - - This method should be used when responding to an authentication challenge from a server. - - @param serverTrust The X.509 certificate trust of the server. - @param domain The domain of serverTrust. If `nil`, the domain will not be validated. - - @return Whether or not to trust the server. - */ -- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust - forDomain:(NSString *)domain; - -@end - -///---------------- -/// @name Constants -///---------------- - -/** - ## SSL Pinning Modes - - The following constants are provided by `AFSSLPinningMode` as possible SSL pinning modes. - - enum { - AFSSLPinningModeNone, - AFSSLPinningModePublicKey, - AFSSLPinningModeCertificate, - } - - `AFSSLPinningModeNone` - Do not used pinned certificates to validate servers. - - `AFSSLPinningModePublicKey` - Validate host certificates against public keys of pinned certificates. - - `AFSSLPinningModeCertificate` - Validate host certificates against pinned certificates. -*/ diff --git a/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFSecurityPolicy.m b/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFSecurityPolicy.m deleted file mode 100644 index 35703163..00000000 --- a/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFSecurityPolicy.m +++ /dev/null @@ -1,325 +0,0 @@ -// AFSecurity.m -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import "AFSecurityPolicy.h" - -// Equivalent of macro in <AssertMacros.h>, without causing compiler warning: -// "'DebugAssert' is deprecated: first deprecated in OS X 10.8" -#ifndef AF_Require - #define AF_Require(assertion, exceptionLabel) \ - do { \ - if (__builtin_expect(!(assertion), 0)) { \ - goto exceptionLabel; \ - } \ - } while (0) -#endif - -#ifndef AF_Require_noErr - #define AF_Require_noErr(errorCode, exceptionLabel) \ - do { \ - if (__builtin_expect(0 != (errorCode), 0)) { \ - goto exceptionLabel; \ - } \ - } while (0) -#endif - -#if !defined(__IPHONE_OS_VERSION_MIN_REQUIRED) -static NSData * AFSecKeyGetData(SecKeyRef key) { - CFDataRef data = NULL; - - AF_Require_noErr(SecItemExport(key, kSecFormatUnknown, kSecItemPemArmour, NULL, &data), _out); - - return (__bridge_transfer NSData *)data; - -_out: - if (data) { - CFRelease(data); - } - - return nil; -} -#endif - -static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) { -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) - return [(__bridge id)key1 isEqual:(__bridge id)key2]; -#else - return [AFSecKeyGetData(key1) isEqual:AFSecKeyGetData(key2)]; -#endif -} - -static id AFPublicKeyForCertificate(NSData *certificate) { - id allowedPublicKey = nil; - SecCertificateRef allowedCertificate; - SecCertificateRef allowedCertificates[1]; - CFArrayRef tempCertificates = nil; - SecPolicyRef policy = nil; - SecTrustRef allowedTrust = nil; - SecTrustResultType result; - - allowedCertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificate); - AF_Require(allowedCertificate != NULL, _out); - - allowedCertificates[0] = allowedCertificate; - tempCertificates = CFArrayCreate(NULL, (const void **)allowedCertificates, 1, NULL); - - policy = SecPolicyCreateBasicX509(); - AF_Require_noErr(SecTrustCreateWithCertificates(tempCertificates, policy, &allowedTrust), _out); - AF_Require_noErr(SecTrustEvaluate(allowedTrust, &result), _out); - - allowedPublicKey = (__bridge_transfer id)SecTrustCopyPublicKey(allowedTrust); - -_out: - if (allowedTrust) { - CFRelease(allowedTrust); - } - - if (policy) { - CFRelease(policy); - } - - if (tempCertificates) { - CFRelease(tempCertificates); - } - - if (allowedCertificate) { - CFRelease(allowedCertificate); - } - - return allowedPublicKey; -} - -static BOOL AFServerTrustIsValid(SecTrustRef serverTrust) { - BOOL isValid = NO; - SecTrustResultType result; - AF_Require_noErr(SecTrustEvaluate(serverTrust, &result), _out); - - isValid = (result == kSecTrustResultUnspecified || result == kSecTrustResultProceed); - -_out: - return isValid; -} - -static NSArray * AFCertificateTrustChainForServerTrust(SecTrustRef serverTrust) { - CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust); - NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:(NSUInteger)certificateCount]; - - for (CFIndex i = 0; i < certificateCount; i++) { - SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i); - [trustChain addObject:(__bridge_transfer NSData *)SecCertificateCopyData(certificate)]; - } - - return [NSArray arrayWithArray:trustChain]; -} - -static NSArray * AFPublicKeyTrustChainForServerTrust(SecTrustRef serverTrust) { - SecPolicyRef policy = SecPolicyCreateBasicX509(); - CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust); - NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:(NSUInteger)certificateCount]; - for (CFIndex i = 0; i < certificateCount; i++) { - SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i); - - SecCertificateRef someCertificates[] = {certificate}; - CFArrayRef certificates = CFArrayCreate(NULL, (const void **)someCertificates, 1, NULL); - - SecTrustRef trust; - AF_Require_noErr(SecTrustCreateWithCertificates(certificates, policy, &trust), _out); - - SecTrustResultType result; - AF_Require_noErr(SecTrustEvaluate(trust, &result), _out); - - [trustChain addObject:(__bridge_transfer id)SecTrustCopyPublicKey(trust)]; - - _out: - if (trust) { - CFRelease(trust); - } - - if (certificates) { - CFRelease(certificates); - } - - continue; - } - CFRelease(policy); - - return [NSArray arrayWithArray:trustChain]; -} - -#pragma mark - - -@interface AFSecurityPolicy() -@property (readwrite, nonatomic, strong) NSArray *pinnedPublicKeys; -@end - -@implementation AFSecurityPolicy - -+ (NSArray *)defaultPinnedCertificates { - static NSArray *_defaultPinnedCertificates = nil; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - NSBundle *bundle = [NSBundle bundleForClass:[self class]]; - NSArray *paths = [bundle pathsForResourcesOfType:@"cer" inDirectory:@"."]; - NSMutableArray *certificates = [NSMutableArray arrayWithCapacity:[paths count]]; - for (NSString *path in paths) { - NSData *certificateData = [NSData dataWithContentsOfFile:path]; - [certificates addObject:certificateData]; - } - // also add certs from www/certificates - paths = [bundle pathsForResourcesOfType:@"cer" inDirectory:@"www/certificates"]; - for (NSString *path in paths) { - NSData *certificateData = [NSData dataWithContentsOfFile:path]; - [certificates addObject:certificateData]; - } - - _defaultPinnedCertificates = [[NSArray alloc] initWithArray:certificates]; - }); - - return _defaultPinnedCertificates; -} - -+ (instancetype)defaultPolicy { - AFSecurityPolicy *securityPolicy = [[self alloc] init]; - securityPolicy.SSLPinningMode = AFSSLPinningModeNone; - - return securityPolicy; -} - -+ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode { - AFSecurityPolicy *securityPolicy = [[self alloc] init]; - securityPolicy.SSLPinningMode = pinningMode; - securityPolicy.validatesDomainName = YES; - [securityPolicy setPinnedCertificates:[self defaultPinnedCertificates]]; - - return securityPolicy; -} - -- (id)init { - self = [super init]; - if (!self) { - return nil; - } - - self.validatesCertificateChain = YES; - - return self; -} - -#pragma mark - - -- (void)setPinnedCertificates:(NSArray *)pinnedCertificates { - _pinnedCertificates = pinnedCertificates; - - if (self.pinnedCertificates) { - NSMutableArray *mutablePinnedPublicKeys = [NSMutableArray arrayWithCapacity:[self.pinnedCertificates count]]; - for (NSData *certificate in self.pinnedCertificates) { - id publicKey = AFPublicKeyForCertificate(certificate); - if (!publicKey) { - continue; - } - [mutablePinnedPublicKeys addObject:publicKey]; - } - self.pinnedPublicKeys = [NSArray arrayWithArray:mutablePinnedPublicKeys]; - } else { - self.pinnedPublicKeys = nil; - } -} - -#pragma mark - - -- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust { - return [self evaluateServerTrust:serverTrust forDomain:nil]; -} - -- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust - forDomain:(NSString *)domain -{ - NSMutableArray *policies = [NSMutableArray array]; - if (self.validatesDomainName) { - [policies addObject:(__bridge_transfer id)SecPolicyCreateSSL(true, (__bridge CFStringRef)domain)]; - } else { - [policies addObject:(__bridge_transfer id)SecPolicyCreateBasicX509()]; - } - - SecTrustSetPolicies(serverTrust, (__bridge CFArrayRef)policies); - - if (!AFServerTrustIsValid(serverTrust) && !self.allowInvalidCertificates) { - return NO; - } - - NSArray *serverCertificates = AFCertificateTrustChainForServerTrust(serverTrust); - switch (self.SSLPinningMode) { - case AFSSLPinningModeNone: - return YES; - case AFSSLPinningModeCertificate: { - NSMutableArray *pinnedCertificates = [NSMutableArray array]; - for (NSData *certificateData in self.pinnedCertificates) { - [pinnedCertificates addObject:(__bridge_transfer id)SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificateData)]; - } - SecTrustSetAnchorCertificates(serverTrust, (__bridge CFArrayRef)pinnedCertificates); - - if (!AFServerTrustIsValid(serverTrust)) { - return NO; - } - - if (!self.validatesCertificateChain) { - return YES; - } - - NSUInteger trustedCertificateCount = 0; - for (NSData *trustChainCertificate in serverCertificates) { - if ([self.pinnedCertificates containsObject:trustChainCertificate]) { - trustedCertificateCount++; - } - } - - return trustedCertificateCount == [serverCertificates count]; - } - case AFSSLPinningModePublicKey: { - NSUInteger trustedPublicKeyCount = 0; - NSArray *publicKeys = AFPublicKeyTrustChainForServerTrust(serverTrust); - if (!self.validatesCertificateChain && [publicKeys count] > 0) { - publicKeys = @[[publicKeys firstObject]]; - } - - for (id trustChainPublicKey in publicKeys) { - for (id pinnedPublicKey in self.pinnedPublicKeys) { - if (AFSecKeyIsEqualToKey((__bridge SecKeyRef)trustChainPublicKey, (__bridge SecKeyRef)pinnedPublicKey)) { - trustedPublicKeyCount += 1; - } - } - } - - return trustedPublicKeyCount > 0 && ((self.validatesCertificateChain && trustedPublicKeyCount == [serverCertificates count]) || (!self.validatesCertificateChain && trustedPublicKeyCount >= 1)); - } - } - - return NO; -} - -#pragma mark - NSKeyValueObserving - -+ (NSSet *)keyPathsForValuesAffectingPinnedPublicKeys { - return [NSSet setWithObject:@"pinnedCertificates"]; -} - -@end diff --git a/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFURLConnectionOperation.h b/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFURLConnectionOperation.h deleted file mode 100644 index cf1b698a..00000000 --- a/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFURLConnectionOperation.h +++ /dev/null @@ -1,328 +0,0 @@ -// AFURLConnectionOperation.h -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import <Foundation/Foundation.h> - -#import <Availability.h> -#import "AFURLRequestSerialization.h" -#import "AFURLResponseSerialization.h" -#import "AFSecurityPolicy.h" - -/** - `AFURLConnectionOperation` is a subclass of `NSOperation` that implements `NSURLConnection` delegate methods. - - ## Subclassing Notes - - This is the base class of all network request operations. You may wish to create your own subclass in order to implement additional `NSURLConnection` delegate methods (see "`NSURLConnection` Delegate Methods" below), or to provide additional properties and/or class constructors. - - If you are creating a subclass that communicates over the HTTP or HTTPS protocols, you may want to consider subclassing `AFHTTPRequestOperation` instead, as it supports specifying acceptable content types or status codes. - - ## NSURLConnection Delegate Methods - - `AFURLConnectionOperation` implements the following `NSURLConnection` delegate methods: - - - `connection:didReceiveResponse:` - - `connection:didReceiveData:` - - `connectionDidFinishLoading:` - - `connection:didFailWithError:` - - `connection:didSendBodyData:totalBytesWritten:totalBytesExpectedToWrite:` - - `connection:willCacheResponse:` - - `connectionShouldUseCredentialStorage:` - - `connection:needNewBodyStream:` - - `connection:willSendRequestForAuthenticationChallenge:` - - If any of these methods are overridden in a subclass, they _must_ call the `super` implementation first. - - ## Callbacks and Completion Blocks - - The built-in `completionBlock` provided by `NSOperation` allows for custom behavior to be executed after the request finishes. It is a common pattern for class constructors in subclasses to take callback block parameters, and execute them conditionally in the body of its `completionBlock`. Make sure to handle cancelled operations appropriately when setting a `completionBlock` (i.e. returning early before parsing response data). See the implementation of any of the `AFHTTPRequestOperation` subclasses for an example of this. - - Subclasses are strongly discouraged from overriding `setCompletionBlock:`, as `AFURLConnectionOperation`'s implementation includes a workaround to mitigate retain cycles, and what Apple rather ominously refers to as ["The Deallocation Problem"](http://developer.apple.com/library/ios/#technotes/tn2109/). - - ## SSL Pinning - - Relying on the CA trust model to validate SSL certificates exposes your app to security vulnerabilities, such as man-in-the-middle attacks. For applications that connect to known servers, SSL certificate pinning provides an increased level of security, by checking server certificate validity against those specified in the app bundle. - - SSL with certificate pinning is strongly recommended for any application that transmits sensitive information to an external webservice. - - Connections will be validated on all matching certificates with a `.cer` extension in the bundle root. - - ## App Extensions - - When using AFNetworking in an App Extension, `#define AF_APP_EXTENSIONS` to avoid using unavailable APIs. - - ## NSCoding & NSCopying Conformance - - `AFURLConnectionOperation` conforms to the `NSCoding` and `NSCopying` protocols, allowing operations to be archived to disk, and copied in memory, respectively. However, because of the intrinsic limitations of capturing the exact state of an operation at a particular moment, there are some important caveats to keep in mind: - - ### NSCoding Caveats - - - Encoded operations do not include any block or stream properties. Be sure to set `completionBlock`, `outputStream`, and any callback blocks as necessary when using `-initWithCoder:` or `NSKeyedUnarchiver`. - - Operations are paused on `encodeWithCoder:`. If the operation was encoded while paused or still executing, its archived state will return `YES` for `isReady`. Otherwise, the state of an operation when encoding will remain unchanged. - - ### NSCopying Caveats - - - `-copy` and `-copyWithZone:` return a new operation with the `NSURLRequest` of the original. So rather than an exact copy of the operation at that particular instant, the copying mechanism returns a completely new instance, which can be useful for retrying operations. - - A copy of an operation will not include the `outputStream` of the original. - - Operation copies do not include `completionBlock`, as it often strongly captures a reference to `self`, which would otherwise have the unintuitive side-effect of pointing to the _original_ operation when copied. - */ - -@interface AFURLConnectionOperation : NSOperation <NSURLConnectionDelegate, NSURLConnectionDataDelegate, NSSecureCoding, NSCopying> - -///------------------------------- -/// @name Accessing Run Loop Modes -///------------------------------- - -/** - The run loop modes in which the operation will run on the network thread. By default, this is a single-member set containing `NSRunLoopCommonModes`. - */ -@property (nonatomic, strong) NSSet *runLoopModes; - -///----------------------------------------- -/// @name Getting URL Connection Information -///----------------------------------------- - -/** - The request used by the operation's connection. - */ -@property (readonly, nonatomic, strong) NSURLRequest *request; - -/** - The last response received by the operation's connection. - */ -@property (readonly, nonatomic, strong) NSURLResponse *response; - -/** - The error, if any, that occurred in the lifecycle of the request. - */ -@property (readonly, nonatomic, strong) NSError *error; - -///---------------------------- -/// @name Getting Response Data -///---------------------------- - -/** - The data received during the request. - */ -@property (readonly, nonatomic, strong) NSData *responseData; - -/** - The string representation of the response data. - */ -@property (readonly, nonatomic, copy) NSString *responseString; - -/** - The string encoding of the response. - - If the response does not specify a valid string encoding, `responseStringEncoding` will return `NSUTF8StringEncoding`. - */ -@property (readonly, nonatomic, assign) NSStringEncoding responseStringEncoding; - -///------------------------------- -/// @name Managing URL Credentials -///------------------------------- - -/** - Whether the URL connection should consult the credential storage for authenticating the connection. `YES` by default. - - This is the value that is returned in the `NSURLConnectionDelegate` method `-connectionShouldUseCredentialStorage:`. - */ -@property (nonatomic, assign) BOOL shouldUseCredentialStorage; - -/** - The credential used for authentication challenges in `-connection:didReceiveAuthenticationChallenge:`. - - This will be overridden by any shared credentials that exist for the username or password of the request URL, if present. - */ -@property (nonatomic, strong) NSURLCredential *credential; - -///------------------------------- -/// @name Managing Security Policy -///------------------------------- - -/** - The security policy used to evaluate server trust for secure connections. - */ -@property (nonatomic, strong) AFSecurityPolicy *securityPolicy; - -///------------------------ -/// @name Accessing Streams -///------------------------ - -/** - The input stream used to read data to be sent during the request. - - This property acts as a proxy to the `HTTPBodyStream` property of `request`. - */ -@property (nonatomic, strong) NSInputStream *inputStream; - -/** - The output stream that is used to write data received until the request is finished. - - By default, data is accumulated into a buffer that is stored into `responseData` upon completion of the request, with the intermediary `outputStream` property set to `nil`. When `outputStream` is set, the data will not be accumulated into an internal buffer, and as a result, the `responseData` property of the completed request will be `nil`. The output stream will be scheduled in the network thread runloop upon being set. - */ -@property (nonatomic, strong) NSOutputStream *outputStream; - -///--------------------------------- -/// @name Managing Callback Queues -///--------------------------------- - -/** - The dispatch queue for `completionBlock`. If `NULL` (default), the main queue is used. - */ -@property (nonatomic, strong) dispatch_queue_t completionQueue; - -/** - The dispatch group for `completionBlock`. If `NULL` (default), a private dispatch group is used. - */ -@property (nonatomic, strong) dispatch_group_t completionGroup; - -///--------------------------------------------- -/// @name Managing Request Operation Information -///--------------------------------------------- - -/** - The user info dictionary for the receiver. - */ -@property (nonatomic, strong) NSDictionary *userInfo; - -///------------------------------------------------------ -/// @name Initializing an AFURLConnectionOperation Object -///------------------------------------------------------ - -/** - Initializes and returns a newly allocated operation object with a url connection configured with the specified url request. - - This is the designated initializer. - - @param urlRequest The request object to be used by the operation connection. - */ -- (instancetype)initWithRequest:(NSURLRequest *)urlRequest; - -///---------------------------------- -/// @name Pausing / Resuming Requests -///---------------------------------- - -/** - Pauses the execution of the request operation. - - A paused operation returns `NO` for `-isReady`, `-isExecuting`, and `-isFinished`. As such, it will remain in an `NSOperationQueue` until it is either cancelled or resumed. Pausing a finished, cancelled, or paused operation has no effect. - */ -- (void)pause; - -/** - Whether the request operation is currently paused. - - @return `YES` if the operation is currently paused, otherwise `NO`. - */ -- (BOOL)isPaused; - -/** - Resumes the execution of the paused request operation. - - Pause/Resume behavior varies depending on the underlying implementation for the operation class. In its base implementation, resuming a paused requests restarts the original request. However, since HTTP defines a specification for how to request a specific content range, `AFHTTPRequestOperation` will resume downloading the request from where it left off, instead of restarting the original request. - */ -- (void)resume; - -///---------------------------------------------- -/// @name Configuring Backgrounding Task Behavior -///---------------------------------------------- - -/** - Specifies that the operation should continue execution after the app has entered the background, and the expiration handler for that background task. - - @param handler A handler to be called shortly before the application’s remaining background time reaches 0. The handler is wrapped in a block that cancels the operation, and cleans up and marks the end of execution, unlike the `handler` parameter in `UIApplication -beginBackgroundTaskWithExpirationHandler:`, which expects this to be done in the handler itself. The handler is called synchronously on the main thread, thus blocking the application’s suspension momentarily while the application is notified. - */ -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && !defined(AF_APP_EXTENSIONS) -- (void)setShouldExecuteAsBackgroundTaskWithExpirationHandler:(void (^)(void))handler; -#endif - -///--------------------------------- -/// @name Setting Progress Callbacks -///--------------------------------- - -/** - Sets a callback to be called when an undetermined number of bytes have been uploaded to the server. - - @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 three arguments: 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. - */ -- (void)setUploadProgressBlock:(void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))block; - -/** - Sets a callback to be called when an undetermined number of bytes have been downloaded from the server. - - @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 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 main thread. - */ -- (void)setDownloadProgressBlock:(void (^)(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead))block; - -///------------------------------------------------- -/// @name Setting NSURLConnection Delegate Callbacks -///------------------------------------------------- - -/** - Sets a block to be executed when the connection will authenticate a challenge in order to download its request, as handled by the `NSURLConnectionDelegate` method `connection:willSendRequestForAuthenticationChallenge:`. - - @param block A block object to be executed when the connection will authenticate a challenge in order to download its request. The block has no return type and takes two arguments: the URL connection object, and the challenge that must be authenticated. This block must invoke one of the challenge-responder methods (NSURLAuthenticationChallengeSender protocol). - - If `allowsInvalidSSLCertificate` is set to YES, `connection:willSendRequestForAuthenticationChallenge:` will attempt to have the challenge sender use credentials with invalid SSL certificates. - */ -- (void)setWillSendRequestForAuthenticationChallengeBlock:(void (^)(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge))block; - -/** - Sets a block to be executed when the server redirects the request from one URL to another URL, or when the request URL changed by the `NSURLProtocol` subclass handling the request in order to standardize its format, as handled by the `NSURLConnectionDataDelegate` method `connection:willSendRequest:redirectResponse:`. - - @param block A block object to be executed when the request URL was changed. The block returns an `NSURLRequest` object, the URL request to redirect, and takes three arguments: the URL connection object, the the proposed redirected request, and the URL response that caused the redirect. - */ -- (void)setRedirectResponseBlock:(NSURLRequest * (^)(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse))block; - - -/** - Sets a block to be executed to modify the response a connection will cache, if any, as handled by the `NSURLConnectionDelegate` method `connection:willCacheResponse:`. - - @param block A block object to be executed to determine what response a connection will cache, if any. The block returns an `NSCachedURLResponse` object, the cached response to store in memory or `nil` to prevent the response from being cached, and takes two arguments: the URL connection object, and the cached response provided for the request. - */ -- (void)setCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse))block; - -/// - -/** - - */ -+ (NSArray *)batchOfRequestOperations:(NSArray *)operations - progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock - completionBlock:(void (^)(NSArray *operations))completionBlock; - -@end - -///-------------------- -/// @name Notifications -///-------------------- - -/** - Posted when an operation begins executing. - */ -extern NSString * const AFNetworkingOperationDidStartNotification; - -/** - Posted when an operation finishes. - */ -extern NSString * const AFNetworkingOperationDidFinishNotification; diff --git a/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFURLConnectionOperation.m b/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFURLConnectionOperation.m deleted file mode 100644 index d8b55e3e..00000000 --- a/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFURLConnectionOperation.m +++ /dev/null @@ -1,786 +0,0 @@ -// AFURLConnectionOperation.m -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import "AFURLConnectionOperation.h" - -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) -#import <UIKit/UIKit.h> -#endif - -#if !__has_feature(objc_arc) -#error AFNetworking must be built with ARC. -// You can turn on ARC for only AFNetworking files by adding -fobjc-arc to the build phase for each of its files. -#endif - -typedef NS_ENUM(NSInteger, AFOperationState) { - AFOperationPausedState = -1, - AFOperationReadyState = 1, - AFOperationExecutingState = 2, - AFOperationFinishedState = 3, -}; - -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && !defined(AF_APP_EXTENSIONS) -typedef UIBackgroundTaskIdentifier AFBackgroundTaskIdentifier; -#else -typedef id AFBackgroundTaskIdentifier; -#endif - -static dispatch_group_t url_request_operation_completion_group() { - static dispatch_group_t af_url_request_operation_completion_group; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - af_url_request_operation_completion_group = dispatch_group_create(); - }); - - return af_url_request_operation_completion_group; -} - -static dispatch_queue_t url_request_operation_completion_queue() { - static dispatch_queue_t af_url_request_operation_completion_queue; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - af_url_request_operation_completion_queue = dispatch_queue_create("com.alamofire.networking.operation.queue", DISPATCH_QUEUE_CONCURRENT ); - }); - - return af_url_request_operation_completion_queue; -} - -static NSString * const kAFNetworkingLockName = @"com.alamofire.networking.operation.lock"; - -NSString * const AFNetworkingOperationDidStartNotification = @"com.alamofire.networking.operation.start"; -NSString * const AFNetworkingOperationDidFinishNotification = @"com.alamofire.networking.operation.finish"; - -typedef void (^AFURLConnectionOperationProgressBlock)(NSUInteger bytes, long long totalBytes, long long totalBytesExpected); -typedef void (^AFURLConnectionOperationAuthenticationChallengeBlock)(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge); -typedef NSCachedURLResponse * (^AFURLConnectionOperationCacheResponseBlock)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse); -typedef NSURLRequest * (^AFURLConnectionOperationRedirectResponseBlock)(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse); - -static inline NSString * AFKeyPathFromOperationState(AFOperationState state) { - switch (state) { - case AFOperationReadyState: - return @"isReady"; - case AFOperationExecutingState: - return @"isExecuting"; - case AFOperationFinishedState: - return @"isFinished"; - case AFOperationPausedState: - return @"isPaused"; - default: { -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wunreachable-code" - return @"state"; -#pragma clang diagnostic pop - } - } -} - -static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperationState toState, BOOL isCancelled) { - switch (fromState) { - case AFOperationReadyState: - switch (toState) { - case AFOperationPausedState: - case AFOperationExecutingState: - return YES; - case AFOperationFinishedState: - return isCancelled; - default: - return NO; - } - case AFOperationExecutingState: - switch (toState) { - case AFOperationPausedState: - case AFOperationFinishedState: - return YES; - default: - return NO; - } - case AFOperationFinishedState: - return NO; - case AFOperationPausedState: - return toState == AFOperationReadyState; - default: { -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wunreachable-code" - switch (toState) { - case AFOperationPausedState: - case AFOperationReadyState: - case AFOperationExecutingState: - case AFOperationFinishedState: - return YES; - default: - return NO; - } - } -#pragma clang diagnostic pop - } -} - -@interface AFURLConnectionOperation () -@property (readwrite, nonatomic, assign) AFOperationState state; -@property (readwrite, nonatomic, strong) NSRecursiveLock *lock; -@property (readwrite, nonatomic, strong) NSURLConnection *connection; -@property (readwrite, nonatomic, strong) NSURLRequest *request; -@property (readwrite, nonatomic, strong) NSURLResponse *response; -@property (readwrite, nonatomic, strong) NSError *error; -@property (readwrite, nonatomic, strong) NSData *responseData; -@property (readwrite, nonatomic, copy) NSString *responseString; -@property (readwrite, nonatomic, assign) NSStringEncoding responseStringEncoding; -@property (readwrite, nonatomic, assign) long long totalBytesRead; -@property (readwrite, nonatomic, assign) AFBackgroundTaskIdentifier backgroundTaskIdentifier; -@property (readwrite, nonatomic, copy) AFURLConnectionOperationProgressBlock uploadProgress; -@property (readwrite, nonatomic, copy) AFURLConnectionOperationProgressBlock downloadProgress; -@property (readwrite, nonatomic, copy) AFURLConnectionOperationAuthenticationChallengeBlock authenticationChallenge; -@property (readwrite, nonatomic, copy) AFURLConnectionOperationCacheResponseBlock cacheResponse; -@property (readwrite, nonatomic, copy) AFURLConnectionOperationRedirectResponseBlock redirectResponse; - -- (void)operationDidStart; -- (void)finish; -- (void)cancelConnection; -@end - -@implementation AFURLConnectionOperation -@synthesize outputStream = _outputStream; - -+ (void)networkRequestThreadEntryPoint:(id)__unused object { - @autoreleasepool { - [[NSThread currentThread] setName:@"AFNetworking"]; - - NSRunLoop *runLoop = [NSRunLoop currentRunLoop]; - [runLoop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode]; - [runLoop run]; - } -} - -+ (NSThread *)networkRequestThread { - static NSThread *_networkRequestThread = nil; - static dispatch_once_t oncePredicate; - dispatch_once(&oncePredicate, ^{ - _networkRequestThread = [[NSThread alloc] initWithTarget:self selector:@selector(networkRequestThreadEntryPoint:) object:nil]; - [_networkRequestThread start]; - }); - - return _networkRequestThread; -} - -- (instancetype)initWithRequest:(NSURLRequest *)urlRequest { - NSParameterAssert(urlRequest); - - self = [super init]; - if (!self) { - return nil; - } - - _state = AFOperationReadyState; - - self.lock = [[NSRecursiveLock alloc] init]; - self.lock.name = kAFNetworkingLockName; - - self.runLoopModes = [NSSet setWithObject:NSRunLoopCommonModes]; - - self.request = urlRequest; - - self.shouldUseCredentialStorage = YES; - - self.securityPolicy = [AFSecurityPolicy defaultPolicy]; - - return self; -} - -- (void)dealloc { - if (_outputStream) { - [_outputStream close]; - _outputStream = nil; - } - -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && !defined(AF_APP_EXTENSIONS) - if (_backgroundTaskIdentifier) { - [[UIApplication sharedApplication] endBackgroundTask:_backgroundTaskIdentifier]; - _backgroundTaskIdentifier = UIBackgroundTaskInvalid; - } -#endif -} - -#pragma mark - - -- (void)setResponseData:(NSData *)responseData { - [self.lock lock]; - if (!responseData) { - _responseData = nil; - } else { - _responseData = [NSData dataWithBytes:responseData.bytes length:responseData.length]; - } - [self.lock unlock]; -} - -- (NSString *)responseString { - [self.lock lock]; - if (!_responseString && self.response && self.responseData) { - self.responseString = [[NSString alloc] initWithData:self.responseData encoding:self.responseStringEncoding]; - } - [self.lock unlock]; - - return _responseString; -} - -- (NSStringEncoding)responseStringEncoding { - [self.lock lock]; - if (!_responseStringEncoding && self.response) { - NSStringEncoding stringEncoding = NSUTF8StringEncoding; - if (self.response.textEncodingName) { - CFStringEncoding IANAEncoding = CFStringConvertIANACharSetNameToEncoding((__bridge CFStringRef)self.response.textEncodingName); - if (IANAEncoding != kCFStringEncodingInvalidId) { - stringEncoding = CFStringConvertEncodingToNSStringEncoding(IANAEncoding); - } - } - - self.responseStringEncoding = stringEncoding; - } - [self.lock unlock]; - - return _responseStringEncoding; -} - -- (NSInputStream *)inputStream { - return self.request.HTTPBodyStream; -} - -- (void)setInputStream:(NSInputStream *)inputStream { - NSMutableURLRequest *mutableRequest = [self.request mutableCopy]; - mutableRequest.HTTPBodyStream = inputStream; - self.request = mutableRequest; -} - -- (NSOutputStream *)outputStream { - if (!_outputStream) { - self.outputStream = [NSOutputStream outputStreamToMemory]; - } - - return _outputStream; -} - -- (void)setOutputStream:(NSOutputStream *)outputStream { - [self.lock lock]; - if (outputStream != _outputStream) { - if (_outputStream) { - [_outputStream close]; - } - - _outputStream = outputStream; - } - [self.lock unlock]; -} - -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && !defined(AF_APP_EXTENSIONS) -- (void)setShouldExecuteAsBackgroundTaskWithExpirationHandler:(void (^)(void))handler { - [self.lock lock]; - if (!self.backgroundTaskIdentifier) { - UIApplication *application = [UIApplication sharedApplication]; - __weak __typeof(self)weakSelf = self; - self.backgroundTaskIdentifier = [application beginBackgroundTaskWithExpirationHandler:^{ - __strong __typeof(weakSelf)strongSelf = weakSelf; - - if (handler) { - handler(); - } - - if (strongSelf) { - [strongSelf cancel]; - - [application endBackgroundTask:strongSelf.backgroundTaskIdentifier]; - strongSelf.backgroundTaskIdentifier = UIBackgroundTaskInvalid; - } - }]; - } - [self.lock unlock]; -} -#endif - -#pragma mark - - -- (void)setState:(AFOperationState)state { - if (!AFStateTransitionIsValid(self.state, state, [self isCancelled])) { - return; - } - - [self.lock lock]; - NSString *oldStateKey = AFKeyPathFromOperationState(self.state); - NSString *newStateKey = AFKeyPathFromOperationState(state); - - [self willChangeValueForKey:newStateKey]; - [self willChangeValueForKey:oldStateKey]; - _state = state; - [self didChangeValueForKey:oldStateKey]; - [self didChangeValueForKey:newStateKey]; - [self.lock unlock]; -} - -- (void)pause { - if ([self isPaused] || [self isFinished] || [self isCancelled]) { - return; - } - - [self.lock lock]; - if ([self isExecuting]) { - [self performSelector:@selector(operationDidPause) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]]; - - dispatch_async(dispatch_get_main_queue(), ^{ - NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; - [notificationCenter postNotificationName:AFNetworkingOperationDidFinishNotification object:self]; - }); - } - - self.state = AFOperationPausedState; - [self.lock unlock]; -} - -- (void)operationDidPause { - [self.lock lock]; - [self.connection cancel]; - [self.lock unlock]; -} - -- (BOOL)isPaused { - return self.state == AFOperationPausedState; -} - -- (void)resume { - if (![self isPaused]) { - return; - } - - [self.lock lock]; - self.state = AFOperationReadyState; - - [self start]; - [self.lock unlock]; -} - -#pragma mark - - -- (void)setUploadProgressBlock:(void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))block { - self.uploadProgress = block; -} - -- (void)setDownloadProgressBlock:(void (^)(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead))block { - self.downloadProgress = block; -} - -- (void)setWillSendRequestForAuthenticationChallengeBlock:(void (^)(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge))block { - self.authenticationChallenge = block; -} - -- (void)setCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse))block { - self.cacheResponse = block; -} - -- (void)setRedirectResponseBlock:(NSURLRequest * (^)(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse))block { - self.redirectResponse = block; -} - -#pragma mark - NSOperation - -- (void)setCompletionBlock:(void (^)(void))block { - [self.lock lock]; - if (!block) { - [super setCompletionBlock:nil]; - } else { - __weak __typeof(self)weakSelf = self; - [super setCompletionBlock:^ { - __strong __typeof(weakSelf)strongSelf = weakSelf; - -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wgnu" - dispatch_group_t group = strongSelf.completionGroup ?: url_request_operation_completion_group(); - dispatch_queue_t queue = strongSelf.completionQueue ?: dispatch_get_main_queue(); -#pragma clang diagnostic pop - - dispatch_group_async(group, queue, ^{ - block(); - }); - - dispatch_group_notify(group, url_request_operation_completion_queue(), ^{ - [strongSelf setCompletionBlock:nil]; - }); - }]; - } - [self.lock unlock]; -} - -- (BOOL)isReady { - return self.state == AFOperationReadyState && [super isReady]; -} - -- (BOOL)isExecuting { - return self.state == AFOperationExecutingState; -} - -- (BOOL)isFinished { - return self.state == AFOperationFinishedState; -} - -- (BOOL)isConcurrent { - return YES; -} - -- (void)start { - [self.lock lock]; - if ([self isCancelled]) { - [self performSelector:@selector(cancelConnection) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]]; - } else if ([self isReady]) { - self.state = AFOperationExecutingState; - - [self performSelector:@selector(operationDidStart) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]]; - } - [self.lock unlock]; -} - -- (void)operationDidStart { - [self.lock lock]; - if (![self isCancelled]) { - self.connection = [[NSURLConnection alloc] initWithRequest:self.request delegate:self startImmediately:NO]; - - NSRunLoop *runLoop = [NSRunLoop currentRunLoop]; - for (NSString *runLoopMode in self.runLoopModes) { - [self.connection scheduleInRunLoop:runLoop forMode:runLoopMode]; - [self.outputStream scheduleInRunLoop:runLoop forMode:runLoopMode]; - } - - [self.outputStream open]; - [self.connection start]; - } - [self.lock unlock]; - - dispatch_async(dispatch_get_main_queue(), ^{ - [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingOperationDidStartNotification object:self]; - }); -} - -- (void)finish { - [self.lock lock]; - self.state = AFOperationFinishedState; - [self.lock unlock]; - - dispatch_async(dispatch_get_main_queue(), ^{ - [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingOperationDidFinishNotification object:self]; - }); -} - -- (void)cancel { - [self.lock lock]; - if (![self isFinished] && ![self isCancelled]) { - [super cancel]; - - if ([self isExecuting]) { - [self performSelector:@selector(cancelConnection) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]]; - } - } - [self.lock unlock]; -} - -- (void)cancelConnection { - NSDictionary *userInfo = nil; - if ([self.request URL]) { - userInfo = [NSDictionary dictionaryWithObject:[self.request URL] forKey:NSURLErrorFailingURLErrorKey]; - } - NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCancelled userInfo:userInfo]; - - if (![self isFinished]) { - if (self.connection) { - [self.connection cancel]; - [self performSelector:@selector(connection:didFailWithError:) withObject:self.connection withObject:error]; - } else { - // Accomodate race condition where `self.connection` has not yet been set before cancellation - self.error = error; - [self finish]; - } - } -} - -#pragma mark - - -+ (NSArray *)batchOfRequestOperations:(NSArray *)operations - progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock - completionBlock:(void (^)(NSArray *operations))completionBlock -{ - if (!operations || [operations count] == 0) { - return @[[NSBlockOperation blockOperationWithBlock:^{ - dispatch_async(dispatch_get_main_queue(), ^{ - if (completionBlock) { - completionBlock(@[]); - } - }); - }]]; - } - - __block dispatch_group_t group = dispatch_group_create(); - NSBlockOperation *batchedOperation = [NSBlockOperation blockOperationWithBlock:^{ - dispatch_group_notify(group, dispatch_get_main_queue(), ^{ - if (completionBlock) { - completionBlock(operations); - } - }); - }]; - - for (AFURLConnectionOperation *operation in operations) { - operation.completionGroup = group; - void (^originalCompletionBlock)(void) = [operation.completionBlock copy]; - __weak __typeof(operation)weakOperation = operation; - operation.completionBlock = ^{ - __strong __typeof(weakOperation)strongOperation = weakOperation; -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wgnu" - dispatch_queue_t queue = strongOperation.completionQueue ?: dispatch_get_main_queue(); -#pragma clang diagnostic pop - dispatch_group_async(group, queue, ^{ - if (originalCompletionBlock) { - originalCompletionBlock(); - } - - NSUInteger numberOfFinishedOperations = [[operations indexesOfObjectsPassingTest:^BOOL(id op, NSUInteger __unused idx, BOOL __unused *stop) { - return [op isFinished]; - }] count]; - - if (progressBlock) { - progressBlock(numberOfFinishedOperations, [operations count]); - } - - dispatch_group_leave(group); - }); - }; - - dispatch_group_enter(group); - [batchedOperation addDependency:operation]; - } - - return [operations arrayByAddingObject:batchedOperation]; -} - -#pragma mark - NSObject - -- (NSString *)description { - return [NSString stringWithFormat:@"<%@: %p, state: %@, cancelled: %@ request: %@, response: %@>", NSStringFromClass([self class]), self, AFKeyPathFromOperationState(self.state), ([self isCancelled] ? @"YES" : @"NO"), self.request, self.response]; -} - -#pragma mark - NSURLConnectionDelegate - -- (void)connection:(NSURLConnection *)connection -willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge -{ - if (self.authenticationChallenge) { - self.authenticationChallenge(connection, challenge); - return; - } - - if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) { - if ([self.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) { - NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]; - [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge]; - } else { - [[challenge sender] cancelAuthenticationChallenge:challenge]; - } - } else { - if ([challenge previousFailureCount] == 0) { - if (self.credential) { - [[challenge sender] useCredential:self.credential forAuthenticationChallenge:challenge]; - } else { - [[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge]; - } - } else { - [[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge]; - } - } -} - -- (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection __unused *)connection { - return self.shouldUseCredentialStorage; -} - -- (NSURLRequest *)connection:(NSURLConnection *)connection - willSendRequest:(NSURLRequest *)request - redirectResponse:(NSURLResponse *)redirectResponse -{ - if (self.redirectResponse) { - return self.redirectResponse(connection, request, redirectResponse); - } else { - return request; - } -} - -- (void)connection:(NSURLConnection __unused *)connection - didSendBodyData:(NSInteger)bytesWritten - totalBytesWritten:(NSInteger)totalBytesWritten -totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite -{ - dispatch_async(dispatch_get_main_queue(), ^{ - if (self.uploadProgress) { - self.uploadProgress((NSUInteger)bytesWritten, totalBytesWritten, totalBytesExpectedToWrite); - } - }); -} - -- (void)connection:(NSURLConnection __unused *)connection -didReceiveResponse:(NSURLResponse *)response -{ - self.response = response; -} - -- (void)connection:(NSURLConnection __unused *)connection - didReceiveData:(NSData *)data -{ - NSUInteger length = [data length]; - while (YES) { - NSInteger totalNumberOfBytesWritten = 0; - if ([self.outputStream hasSpaceAvailable]) { - const uint8_t *dataBuffer = (uint8_t *)[data bytes]; - - NSInteger numberOfBytesWritten = 0; - while (totalNumberOfBytesWritten < (NSInteger)length) { - numberOfBytesWritten = [self.outputStream write:&dataBuffer[(NSUInteger)totalNumberOfBytesWritten] maxLength:(length - (NSUInteger)totalNumberOfBytesWritten)]; - if (numberOfBytesWritten == -1) { - break; - } - - totalNumberOfBytesWritten += numberOfBytesWritten; - } - - break; - } - - if (self.outputStream.streamError) { - [self.connection cancel]; - [self performSelector:@selector(connection:didFailWithError:) withObject:self.connection withObject:self.outputStream.streamError]; - return; - } - } - - dispatch_async(dispatch_get_main_queue(), ^{ - self.totalBytesRead += (long long)length; - - if (self.downloadProgress) { - self.downloadProgress(length, self.totalBytesRead, self.response.expectedContentLength); - } - }); -} - -- (void)connectionDidFinishLoading:(NSURLConnection __unused *)connection { - self.responseData = [self.outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey]; - - [self.outputStream close]; - if (self.responseData) { - self.outputStream = nil; - } - - self.connection = nil; - - [self finish]; -} - -- (void)connection:(NSURLConnection __unused *)connection - didFailWithError:(NSError *)error -{ - self.error = error; - - [self.outputStream close]; - if (self.responseData) { - self.outputStream = nil; - } - - self.connection = nil; - - [self finish]; -} - -- (NSCachedURLResponse *)connection:(NSURLConnection *)connection - willCacheResponse:(NSCachedURLResponse *)cachedResponse -{ - if (self.cacheResponse) { - return self.cacheResponse(connection, cachedResponse); - } else { - if ([self isCancelled]) { - return nil; - } - - return cachedResponse; - } -} - -#pragma mark - NSSecureCoding - -+ (BOOL)supportsSecureCoding { - return YES; -} - -- (id)initWithCoder:(NSCoder *)decoder { - NSURLRequest *request = [decoder decodeObjectOfClass:[NSURLRequest class] forKey:NSStringFromSelector(@selector(request))]; - - self = [self initWithRequest:request]; - if (!self) { - return nil; - } - - self.state = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(state))] integerValue]; - self.response = [decoder decodeObjectOfClass:[NSHTTPURLResponse class] forKey:NSStringFromSelector(@selector(response))]; - self.error = [decoder decodeObjectOfClass:[NSError class] forKey:NSStringFromSelector(@selector(error))]; - self.responseData = [decoder decodeObjectOfClass:[NSData class] forKey:NSStringFromSelector(@selector(responseData))]; - self.totalBytesRead = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(totalBytesRead))] longLongValue]; - - return self; -} - -- (void)encodeWithCoder:(NSCoder *)coder { - [self pause]; - - [coder encodeObject:self.request forKey:NSStringFromSelector(@selector(request))]; - - switch (self.state) { - case AFOperationExecutingState: - case AFOperationPausedState: - [coder encodeInteger:AFOperationReadyState forKey:NSStringFromSelector(@selector(state))]; - break; - default: - [coder encodeInteger:self.state forKey:NSStringFromSelector(@selector(state))]; - break; - } - - [coder encodeObject:self.response forKey:NSStringFromSelector(@selector(response))]; - [coder encodeObject:self.error forKey:NSStringFromSelector(@selector(error))]; - [coder encodeObject:self.responseData forKey:NSStringFromSelector(@selector(responseData))]; - [coder encodeInt64:self.totalBytesRead forKey:NSStringFromSelector(@selector(totalBytesRead))]; -} - -#pragma mark - NSCopying - -- (id)copyWithZone:(NSZone *)zone { - AFURLConnectionOperation *operation = [(AFURLConnectionOperation *)[[self class] allocWithZone:zone] initWithRequest:self.request]; - - operation.uploadProgress = self.uploadProgress; - operation.downloadProgress = self.downloadProgress; - operation.authenticationChallenge = self.authenticationChallenge; - operation.cacheResponse = self.cacheResponse; - operation.redirectResponse = self.redirectResponse; - operation.completionQueue = self.completionQueue; - operation.completionGroup = self.completionGroup; - - return operation; -} - -@end diff --git a/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFURLRequestSerialization.h b/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFURLRequestSerialization.h deleted file mode 100644 index f3bc7c07..00000000 --- a/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFURLRequestSerialization.h +++ /dev/null @@ -1,453 +0,0 @@ -// AFSerialization.h -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import <Foundation/Foundation.h> -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) -#import <UIKit/UIKit.h> -#endif - -/** - 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. - - 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`. - */ -@protocol AFURLRequestSerialization <NSObject, NSSecureCoding, NSCopying> - -/** - Returns a request with the specified parameters encoded into a copy of the original request. - - @param request The original request. - @param parameters The parameters to be encoded. - @param error The error that occurred while attempting to encode the request parameters. - - @return A serialized request. - */ -- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request - withParameters:(id)parameters - error:(NSError * __autoreleasing *)error; - -@end - -#pragma mark - - -/** - - */ -typedef NS_ENUM(NSUInteger, AFHTTPRequestQueryStringSerializationStyle) { - AFHTTPRequestQueryStringDefaultStyle = 0, -}; - -@protocol AFMultipartFormData; - -/** - `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. - - Any request or response serializer dealing with HTTP is encouraged to subclass `AFHTTPRequestSerializer` in order to ensure consistent default behavior. - */ -@interface AFHTTPRequestSerializer : NSObject <AFURLRequestSerialization> - -/** - The string encoding used to serialize parameters. `NSUTF8StringEncoding` by default. - */ -@property (nonatomic, assign) NSStringEncoding stringEncoding; - -/** - Whether created requests can use the device’s cellular radio (if present). `YES` by default. - - @see NSMutableURLRequest -setAllowsCellularAccess: - */ -@property (nonatomic, assign) BOOL allowsCellularAccess; - -/** - The cache policy of created requests. `NSURLRequestUseProtocolCachePolicy` by default. - - @see NSMutableURLRequest -setCachePolicy: - */ -@property (nonatomic, assign) NSURLRequestCachePolicy cachePolicy; - -/** - Whether created requests should use the default cookie handling. `YES` by default. - - @see NSMutableURLRequest -setHTTPShouldHandleCookies: - */ -@property (nonatomic, assign) BOOL HTTPShouldHandleCookies; - -/** - Whether created requests can continue transmitting data before receiving a response from an earlier transmission. `NO` by default - - @see NSMutableURLRequest -setHTTPShouldUsePipelining: - */ -@property (nonatomic, assign) BOOL HTTPShouldUsePipelining; - -/** - The network service type for created requests. `NSURLNetworkServiceTypeDefault` by default. - - @see NSMutableURLRequest -setNetworkServiceType: - */ -@property (nonatomic, assign) NSURLRequestNetworkServiceType networkServiceType; - -/** - The timeout interval, in seconds, for created requests. The default timeout interval is 60 seconds. - - @see NSMutableURLRequest -setTimeoutInterval: - */ -@property (nonatomic, assign) NSTimeInterval timeoutInterval; - -///--------------------------------------- -/// @name Configuring HTTP Request Headers -///--------------------------------------- - -/** - Default HTTP header field values to be applied to serialized requests. - */ -@property (readonly, nonatomic, strong) NSDictionary *HTTPRequestHeaders; - -/** - Creates and returns a serializer with default configuration. - */ -+ (instancetype)serializer; - -/** - 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. - - @param field The HTTP header to set a default value for - @param value The value set as default for the specified header, or `nil` - */ -- (void)setValue:(NSString *)value -forHTTPHeaderField:(NSString *)field; - -/** - Returns the value for the HTTP headers set in the request serializer. - - @param field The HTTP header to retrieve the default value for - - @return The value set as default for the specified header, or `nil` - */ -- (NSString *)valueForHTTPHeaderField:(NSString *)field; - -/** - 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. - - @param username The HTTP basic auth username - @param password The HTTP basic auth password - */ -- (void)setAuthorizationHeaderFieldWithUsername:(NSString *)username - password:(NSString *)password; - -/** - @deprecated This method has been deprecated. Use -setValue:forHTTPHeaderField: instead. - */ -- (void)setAuthorizationHeaderFieldWithToken:(NSString *)token DEPRECATED_ATTRIBUTE; - - -/** - Clears any existing value for the "Authorization" HTTP header. - */ -- (void)clearAuthorizationHeader; - -///------------------------------------------------------- -/// @name Configuring Query String Parameter Serialization -///------------------------------------------------------- - -/** - HTTP methods for which serialized requests will encode parameters as a query string. `GET`, `HEAD`, and `DELETE` by default. - */ -@property (nonatomic, strong) NSSet *HTTPMethodsEncodingParametersInURI; - -/** - Set the method of query string serialization according to one of the pre-defined styles. - - @param style The serialization style. - - @see AFHTTPRequestQueryStringSerializationStyle - */ -- (void)setQueryStringSerializationWithStyle:(AFHTTPRequestQueryStringSerializationStyle)style; - -/** - Set the a custom method of query string serialization according to the specified block. - - @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. - */ -- (void)setQueryStringSerializationWithBlock:(NSString * (^)(NSURLRequest *request, NSDictionary *parameters, NSError * __autoreleasing *error))block; - -///------------------------------- -/// @name Creating Request Objects -///------------------------------- - -/** - @deprecated This method has been deprecated. Use -requestWithMethod:URLString:parameters:error: instead. - */ -- (NSMutableURLRequest *)requestWithMethod:(NSString *)method - URLString:(NSString *)URLString - parameters:(id)parameters DEPRECATED_ATTRIBUTE; - -/** - Creates an `NSMutableURLRequest` object with the specified HTTP method and URL string. - - 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. - - @param method The HTTP method for the request, such as `GET`, `POST`, `PUT`, or `DELETE`. This parameter must not be `nil`. - @param URLString The URL string used to create the request URL. - @param parameters The parameters to be either set as a query string for `GET` requests, or the request HTTP body. - @param error The error that occured while constructing the request. - - @return An `NSMutableURLRequest` object. - */ -- (NSMutableURLRequest *)requestWithMethod:(NSString *)method - URLString:(NSString *)URLString - parameters:(id)parameters - error:(NSError * __autoreleasing *)error; - -/** - @deprecated This method has been deprecated. Use -multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:error: instead. - */ -- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method - URLString:(NSString *)URLString - parameters:(NSDictionary *)parameters - constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block DEPRECATED_ATTRIBUTE; - -/** - 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 - - 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. - - @param method The HTTP method for the request. This parameter must not be `GET` or `HEAD`, or `nil`. - @param URLString The URL string used to create the request URL. - @param parameters The parameters to be encoded and set in the request HTTP body. - @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. - @param error The error that occured while constructing the request. - - @return An `NSMutableURLRequest` object - */ -- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method - URLString:(NSString *)URLString - parameters:(NSDictionary *)parameters - constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block - error:(NSError * __autoreleasing *)error; - -/** - 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. - - @param request The multipart form request. - @param fileURL The file URL to write multipart form contents to. - @param handler A handler block to execute. - - @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. - - @see https://github.com/AFNetworking/AFNetworking/issues/1398 - */ -- (NSMutableURLRequest *)requestWithMultipartFormRequest:(NSURLRequest *)request - writingStreamContentsToFile:(NSURL *)fileURL - completionHandler:(void (^)(NSError *error))handler; - -@end - -#pragma mark - - -/** - The `AFMultipartFormData` protocol defines the methods supported by the parameter in the block argument of `AFHTTPRequestSerializer -multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:`. - */ -@protocol AFMultipartFormData - -/** - 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. - - 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. - - @param fileURL The URL corresponding to the file whose content will be appended to the form. This parameter must not be `nil`. - @param name The name to be associated with the specified data. This parameter must not be `nil`. - @param error If an error occurs, upon return contains an `NSError` object that describes the problem. - - @return `YES` if the file data was successfully appended, otherwise `NO`. - */ -- (BOOL)appendPartWithFileURL:(NSURL *)fileURL - name:(NSString *)name - error:(NSError * __autoreleasing *)error; - -/** - 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. - - @param fileURL The URL corresponding to the file whose content will be appended to the form. This parameter must not be `nil`. - @param name The name to be associated with the specified data. This parameter must not be `nil`. - @param fileName The file name to be used in the `Content-Disposition` header. This parameter must not be `nil`. - @param mimeType The declared MIME type of the file data. This parameter must not be `nil`. - @param error If an error occurs, upon return contains an `NSError` object that describes the problem. - - @return `YES` if the file data was successfully appended otherwise `NO`. - */ -- (BOOL)appendPartWithFileURL:(NSURL *)fileURL - name:(NSString *)name - fileName:(NSString *)fileName - mimeType:(NSString *)mimeType - error:(NSError * __autoreleasing *)error; - -/** - 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. - - @param inputStream The input stream to be appended to the form data - @param name The name to be associated with the specified input stream. This parameter must not be `nil`. - @param fileName The filename to be associated with the specified input stream. This parameter must not be `nil`. - @param length The length of the specified input stream in bytes. - @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`. - */ -- (void)appendPartWithInputStream:(NSInputStream *)inputStream - name:(NSString *)name - fileName:(NSString *)fileName - length:(int64_t)length - mimeType:(NSString *)mimeType; - -/** - 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. - - @param data The data to be encoded and appended to the form data. - @param name The name to be associated with the specified data. This parameter must not be `nil`. - @param fileName The filename to be associated with the specified data. This parameter must not be `nil`. - @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`. - */ -- (void)appendPartWithFileData:(NSData *)data - name:(NSString *)name - fileName:(NSString *)fileName - mimeType:(NSString *)mimeType; - -/** - Appends the HTTP headers `Content-Disposition: form-data; name=#{name}"`, followed by the encoded data and the multipart form boundary. - - @param data The data to be encoded and appended to the form data. - @param name The name to be associated with the specified data. This parameter must not be `nil`. - */ - -- (void)appendPartWithFormData:(NSData *)data - name:(NSString *)name; - - -/** - Appends HTTP headers, followed by the encoded data and the multipart form boundary. - - @param headers The HTTP headers to be appended to the form data. - @param body The data to be encoded and appended to the form data. This parameter must not be `nil`. - */ -- (void)appendPartWithHeaders:(NSDictionary *)headers - body:(NSData *)body; - -/** - Throttles request bandwidth by limiting the packet size and adding a delay for each chunk read from the upload stream. - - 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. - - @param numberOfBytes Maximum packet size, in number of bytes. The default packet size for an input stream is 16kb. - @param delay Duration of delay each time a packet is read. By default, no delay is set. - */ -- (void)throttleBandwidthWithPacketSize:(NSUInteger)numberOfBytes - delay:(NSTimeInterval)delay; - -@end - -#pragma mark - - -@interface AFJSONRequestSerializer : AFHTTPRequestSerializer - -/** - Options for writing the request JSON data from Foundation objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONWritingOptions". `0` by default. - */ -@property (nonatomic, assign) NSJSONWritingOptions writingOptions; - -/** - Creates and returns a JSON serializer with specified reading and writing options. - - @param writingOptions The specified JSON writing options. - */ -+ (instancetype)serializerWithWritingOptions:(NSJSONWritingOptions)writingOptions; - -@end - -@interface AFPropertyListRequestSerializer : AFHTTPRequestSerializer - -/** - The property list format. Possible values are described in "NSPropertyListFormat". - */ -@property (nonatomic, assign) NSPropertyListFormat format; - -/** - @warning The `writeOptions` property is currently unused. - */ -@property (nonatomic, assign) NSPropertyListWriteOptions writeOptions; - -/** - Creates and returns a property list serializer with a specified format, read options, and write options. - - @param format The property list format. - @param writeOptions The property list write options. - - @warning The `writeOptions` property is currently unused. - */ -+ (instancetype)serializerWithFormat:(NSPropertyListFormat)format - writeOptions:(NSPropertyListWriteOptions)writeOptions; - -@end - -///---------------- -/// @name Constants -///---------------- - -/** - ## Error Domains - - The following error domain is predefined. - - - `NSString * const AFURLRequestSerializationErrorDomain` - - ### Constants - - `AFURLRequestSerializationErrorDomain` - AFURLRequestSerializer errors. Error codes for `AFURLRequestSerializationErrorDomain` correspond to codes in `NSURLErrorDomain`. - */ -extern NSString * const AFURLRequestSerializationErrorDomain; - -/** - ## User info dictionary keys - - These keys may exist in the user info dictionary, in addition to those defined for NSError. - - - `NSString * const AFNetworkingOperationFailingURLResponseErrorKey` - - ### Constants - - `AFNetworkingOperationFailingURLRequestErrorKey` - The corresponding value is an `NSURLRequest` containing the request of the operation associated with an error. This key is only present in the `AFURLRequestSerializationErrorDomain`. - */ -extern NSString * const AFNetworkingOperationFailingURLRequestErrorKey; - -/** - ## Throttling Bandwidth for HTTP Request Input Streams - - @see -throttleBandwidthWithPacketSize:delay: - - ### Constants - - `kAFUploadStream3GSuggestedPacketSize` - Maximum packet size, in number of bytes. Equal to 16kb. - - `kAFUploadStream3GSuggestedDelay` - Duration of delay each time a packet is read. Equal to 0.2 seconds. - */ -extern NSUInteger const kAFUploadStream3GSuggestedPacketSize; -extern NSTimeInterval const kAFUploadStream3GSuggestedDelay; diff --git a/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFURLRequestSerialization.m b/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFURLRequestSerialization.m deleted file mode 100644 index aea41d9b..00000000 --- a/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFURLRequestSerialization.m +++ /dev/null @@ -1,1335 +0,0 @@ -// AFSerialization.h -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import "AFURLRequestSerialization.h" - -#if __IPHONE_OS_VERSION_MIN_REQUIRED -#import <MobileCoreServices/MobileCoreServices.h> -#else -#import <CoreServices/CoreServices.h> -#endif - -NSString * const AFURLRequestSerializationErrorDomain = @"com.alamofire.error.serialization.request"; -NSString * const AFNetworkingOperationFailingURLRequestErrorKey = @"com.alamofire.serialization.request.error.response"; - -typedef NSString * (^AFQueryStringSerializationBlock)(NSURLRequest *request, NSDictionary *parameters, NSError *__autoreleasing *error); - -static NSString * AFBase64EncodedStringFromString(NSString *string) { - NSData *data = [NSData dataWithBytes:[string UTF8String] length:[string lengthOfBytesUsingEncoding:NSUTF8StringEncoding]]; - NSUInteger length = [data length]; - NSMutableData *mutableData = [NSMutableData dataWithLength:((length + 2) / 3) * 4]; - - uint8_t *input = (uint8_t *)[data bytes]; - uint8_t *output = (uint8_t *)[mutableData mutableBytes]; - - for (NSUInteger i = 0; i < length; i += 3) { - NSUInteger value = 0; - for (NSUInteger j = i; j < (i + 3); j++) { - value <<= 8; - if (j < length) { - value |= (0xFF & input[j]); - } - } - - static uint8_t const kAFBase64EncodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - - NSUInteger idx = (i / 3) * 4; - output[idx + 0] = kAFBase64EncodingTable[(value >> 18) & 0x3F]; - output[idx + 1] = kAFBase64EncodingTable[(value >> 12) & 0x3F]; - output[idx + 2] = (i + 1) < length ? kAFBase64EncodingTable[(value >> 6) & 0x3F] : '='; - output[idx + 3] = (i + 2) < length ? kAFBase64EncodingTable[(value >> 0) & 0x3F] : '='; - } - - return [[NSString alloc] initWithData:mutableData encoding:NSASCIIStringEncoding]; -} - -static NSString * const kAFCharactersToBeEscapedInQueryString = @":/?&=;+!@#$()',*"; - -static NSString * AFPercentEscapedQueryStringKeyFromStringWithEncoding(NSString *string, NSStringEncoding encoding) { - static NSString * const kAFCharactersToLeaveUnescapedInQueryStringPairKey = @"[]."; - - return (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)string, (__bridge CFStringRef)kAFCharactersToLeaveUnescapedInQueryStringPairKey, (__bridge CFStringRef)kAFCharactersToBeEscapedInQueryString, CFStringConvertNSStringEncodingToEncoding(encoding)); -} - -static NSString * AFPercentEscapedQueryStringValueFromStringWithEncoding(NSString *string, NSStringEncoding encoding) { - return (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)string, NULL, (__bridge CFStringRef)kAFCharactersToBeEscapedInQueryString, CFStringConvertNSStringEncodingToEncoding(encoding)); -} - -#pragma mark - - -@interface AFQueryStringPair : NSObject -@property (readwrite, nonatomic, strong) id field; -@property (readwrite, nonatomic, strong) id value; - -- (id)initWithField:(id)field value:(id)value; - -- (NSString *)URLEncodedStringValueWithEncoding:(NSStringEncoding)stringEncoding; -@end - -@implementation AFQueryStringPair - -- (id)initWithField:(id)field value:(id)value { - self = [super init]; - if (!self) { - return nil; - } - - self.field = field; - self.value = value; - - return self; -} - -- (NSString *)URLEncodedStringValueWithEncoding:(NSStringEncoding)stringEncoding { - if (!self.value || [self.value isEqual:[NSNull null]]) { - return AFPercentEscapedQueryStringKeyFromStringWithEncoding([self.field description], stringEncoding); - } else { - return [NSString stringWithFormat:@"%@=%@", AFPercentEscapedQueryStringKeyFromStringWithEncoding([self.field description], stringEncoding), AFPercentEscapedQueryStringValueFromStringWithEncoding([self.value description], stringEncoding)]; - } -} - -@end - -#pragma mark - - -extern NSArray * AFQueryStringPairsFromDictionary(NSDictionary *dictionary); -extern NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value); - -static NSString * AFQueryStringFromParametersWithEncoding(NSDictionary *parameters, NSStringEncoding stringEncoding) { - NSMutableArray *mutablePairs = [NSMutableArray array]; - for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) { - [mutablePairs addObject:[pair URLEncodedStringValueWithEncoding:stringEncoding]]; - } - - return [mutablePairs componentsJoinedByString:@"&"]; -} - -NSArray * AFQueryStringPairsFromDictionary(NSDictionary *dictionary) { - return AFQueryStringPairsFromKeyAndValue(nil, dictionary); -} - -NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value) { - NSMutableArray *mutableQueryStringComponents = [NSMutableArray array]; - - NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"description" ascending:YES selector:@selector(compare:)]; - - if ([value isKindOfClass:[NSDictionary class]]) { - NSDictionary *dictionary = value; - // Sort dictionary keys to ensure consistent ordering in query string, which is important when deserializing potentially ambiguous sequences, such as an array of dictionaries - for (id nestedKey in [dictionary.allKeys sortedArrayUsingDescriptors:@[ sortDescriptor ]]) { - id nestedValue = [dictionary objectForKey:nestedKey]; - if (nestedValue) { - [mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue((key ? [NSString stringWithFormat:@"%@[%@]", key, nestedKey] : nestedKey), nestedValue)]; - } - } - } else if ([value isKindOfClass:[NSArray class]]) { - NSArray *array = value; - for (id nestedValue in array) { - [mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue([NSString stringWithFormat:@"%@[]", key], nestedValue)]; - } - } else if ([value isKindOfClass:[NSSet class]]) { - NSSet *set = value; - for (id obj in [set sortedArrayUsingDescriptors:@[ sortDescriptor ]]) { - [mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue(key, obj)]; - } - } else { - [mutableQueryStringComponents addObject:[[AFQueryStringPair alloc] initWithField:key value:value]]; - } - - return mutableQueryStringComponents; -} - -#pragma mark - - -@interface AFStreamingMultipartFormData : NSObject <AFMultipartFormData> -- (instancetype)initWithURLRequest:(NSMutableURLRequest *)urlRequest - stringEncoding:(NSStringEncoding)encoding; - -- (NSMutableURLRequest *)requestByFinalizingMultipartFormData; -@end - -#pragma mark - - -static NSArray * AFHTTPRequestSerializerObservedKeyPaths() { - static NSArray *_AFHTTPRequestSerializerObservedKeyPaths = nil; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - _AFHTTPRequestSerializerObservedKeyPaths = @[NSStringFromSelector(@selector(allowsCellularAccess)), NSStringFromSelector(@selector(cachePolicy)), NSStringFromSelector(@selector(HTTPShouldHandleCookies)), NSStringFromSelector(@selector(HTTPShouldUsePipelining)), NSStringFromSelector(@selector(networkServiceType)), NSStringFromSelector(@selector(timeoutInterval))]; - }); - - return _AFHTTPRequestSerializerObservedKeyPaths; -} - -static void *AFHTTPRequestSerializerObserverContext = &AFHTTPRequestSerializerObserverContext; - -@interface AFHTTPRequestSerializer () -@property (readwrite, nonatomic, strong) NSMutableSet *mutableObservedChangedKeyPaths; -@property (readwrite, nonatomic, strong) NSMutableDictionary *mutableHTTPRequestHeaders; -@property (readwrite, nonatomic, assign) AFHTTPRequestQueryStringSerializationStyle queryStringSerializationStyle; -@property (readwrite, nonatomic, copy) AFQueryStringSerializationBlock queryStringSerialization; -@end - -@implementation AFHTTPRequestSerializer - -+ (instancetype)serializer { - return [[self alloc] init]; -} - -- (instancetype)init { - self = [super init]; - if (!self) { - return nil; - } - - self.stringEncoding = NSUTF8StringEncoding; - - self.mutableHTTPRequestHeaders = [NSMutableDictionary dictionary]; - - // Accept-Language HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4 - NSMutableArray *acceptLanguagesComponents = [NSMutableArray array]; - [[NSLocale preferredLanguages] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { - float q = 1.0f - (idx * 0.1f); - [acceptLanguagesComponents addObject:[NSString stringWithFormat:@"%@;q=%0.1g", obj, q]]; - *stop = q <= 0.5f; - }]; - [self setValue:[acceptLanguagesComponents componentsJoinedByString:@", "] forHTTPHeaderField:@"Accept-Language"]; - - NSString *userAgent = nil; -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wgnu" -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) - // User-Agent Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43 - userAgent = [NSString stringWithFormat:@"%@/%@ (%@; iOS %@; Scale/%0.2f)", [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleExecutableKey] ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleIdentifierKey], (__bridge id)CFBundleGetValueForInfoDictionaryKey(CFBundleGetMainBundle(), kCFBundleVersionKey) ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleVersionKey], [[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion], [[UIScreen mainScreen] scale]]; -#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED) - userAgent = [NSString stringWithFormat:@"%@/%@ (Mac OS X %@)", [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleExecutableKey] ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleIdentifierKey], [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleVersionKey], [[NSProcessInfo processInfo] operatingSystemVersionString]]; -#endif -#pragma clang diagnostic pop - if (userAgent) { - if (![userAgent canBeConvertedToEncoding:NSASCIIStringEncoding]) { - NSMutableString *mutableUserAgent = [userAgent mutableCopy]; - if (CFStringTransform((__bridge CFMutableStringRef)(mutableUserAgent), NULL, (__bridge CFStringRef)@"Any-Latin; Latin-ASCII; [:^ASCII:] Remove", false)) { - userAgent = mutableUserAgent; - } - } - [self setValue:userAgent forHTTPHeaderField:@"User-Agent"]; - } - - // HTTP Method Definitions; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html - self.HTTPMethodsEncodingParametersInURI = [NSSet setWithObjects:@"GET", @"HEAD", @"DELETE", nil]; - - self.mutableObservedChangedKeyPaths = [NSMutableSet set]; - for (NSString *keyPath in AFHTTPRequestSerializerObservedKeyPaths()) { - [self addObserver:self forKeyPath:keyPath options:NSKeyValueObservingOptionNew context:AFHTTPRequestSerializerObserverContext]; - } - - return self; -} - -- (void)dealloc { - for (NSString *keyPath in AFHTTPRequestSerializerObservedKeyPaths()) { - [self removeObserver:self forKeyPath:keyPath context:AFHTTPRequestSerializerObserverContext]; - } -} - -#pragma mark - - -- (NSDictionary *)HTTPRequestHeaders { - return [NSDictionary dictionaryWithDictionary:self.mutableHTTPRequestHeaders]; -} - -- (void)setValue:(NSString *)value -forHTTPHeaderField:(NSString *)field -{ - [self.mutableHTTPRequestHeaders setValue:value forKey:field]; -} - -- (NSString *)valueForHTTPHeaderField:(NSString *)field { - return [self.mutableHTTPRequestHeaders valueForKey:field]; -} - -- (void)setAuthorizationHeaderFieldWithUsername:(NSString *)username - password:(NSString *)password -{ - NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", username, password]; - [self setValue:[NSString stringWithFormat:@"Basic %@", AFBase64EncodedStringFromString(basicAuthCredentials)] forHTTPHeaderField:@"Authorization"]; -} - -- (void)setAuthorizationHeaderFieldWithToken:(NSString *)token { - [self setValue:[NSString stringWithFormat:@"Token token=\"%@\"", token] forHTTPHeaderField:@"Authorization"]; -} - -- (void)clearAuthorizationHeader { - [self.mutableHTTPRequestHeaders removeObjectForKey:@"Authorization"]; -} - -#pragma mark - - -- (void)setQueryStringSerializationWithStyle:(AFHTTPRequestQueryStringSerializationStyle)style { - self.queryStringSerializationStyle = style; - self.queryStringSerialization = nil; -} - -- (void)setQueryStringSerializationWithBlock:(NSString *(^)(NSURLRequest *, NSDictionary *, NSError *__autoreleasing *))block { - self.queryStringSerialization = block; -} - -#pragma mark - - -- (NSMutableURLRequest *)requestWithMethod:(NSString *)method - URLString:(NSString *)URLString - parameters:(id)parameters -{ - return [self requestWithMethod:method URLString:URLString parameters:parameters error:nil]; -} - -- (NSMutableURLRequest *)requestWithMethod:(NSString *)method - URLString:(NSString *)URLString - parameters:(id)parameters - error:(NSError *__autoreleasing *)error -{ - NSParameterAssert(method); - NSParameterAssert(URLString); - - NSURL *url = [NSURL URLWithString:URLString]; - - NSParameterAssert(url); - - NSMutableURLRequest *mutableRequest = [[NSMutableURLRequest alloc] initWithURL:url]; - mutableRequest.HTTPMethod = method; - - for (NSString *keyPath in AFHTTPRequestSerializerObservedKeyPaths()) { - if ([self.mutableObservedChangedKeyPaths containsObject:keyPath]) { - [mutableRequest setValue:[self valueForKeyPath:keyPath] forKey:keyPath]; - } - } - - mutableRequest = [[self requestBySerializingRequest:mutableRequest withParameters:parameters error:error] mutableCopy]; - - return mutableRequest; -} - -- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method - URLString:(NSString *)URLString - parameters:(NSDictionary *)parameters - constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block -{ - return [self multipartFormRequestWithMethod:method URLString:URLString parameters:parameters constructingBodyWithBlock:block error:nil]; -} - -- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method - URLString:(NSString *)URLString - parameters:(NSDictionary *)parameters - constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block - error:(NSError *__autoreleasing *)error -{ - NSParameterAssert(method); - NSParameterAssert(![method isEqualToString:@"GET"] && ![method isEqualToString:@"HEAD"]); - - NSMutableURLRequest *mutableRequest = [self requestWithMethod:method URLString:URLString parameters:nil error:error]; - - __block AFStreamingMultipartFormData *formData = [[AFStreamingMultipartFormData alloc] initWithURLRequest:mutableRequest stringEncoding:NSUTF8StringEncoding]; - - if (parameters) { - for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) { - NSData *data = nil; - if ([pair.value isKindOfClass:[NSData class]]) { - data = pair.value; - } else if ([pair.value isEqual:[NSNull null]]) { - data = [NSData data]; - } else { - data = [[pair.value description] dataUsingEncoding:self.stringEncoding]; - } - - if (data) { - [formData appendPartWithFormData:data name:[pair.field description]]; - } - } - } - - if (block) { - block(formData); - } - - return [formData requestByFinalizingMultipartFormData]; -} - -- (NSMutableURLRequest *)requestWithMultipartFormRequest:(NSURLRequest *)request - writingStreamContentsToFile:(NSURL *)fileURL - completionHandler:(void (^)(NSError *error))handler -{ - if (!request.HTTPBodyStream) { - return [request mutableCopy]; - } - - NSParameterAssert([fileURL isFileURL]); - - NSInputStream *inputStream = request.HTTPBodyStream; - NSOutputStream *outputStream = [[NSOutputStream alloc] initWithURL:fileURL append:NO]; - __block NSError *error = nil; - - dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ - [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; - [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; - - [inputStream open]; - [outputStream open]; - - while ([inputStream hasBytesAvailable] && [outputStream hasSpaceAvailable]) { - uint8_t buffer[1024]; - - NSInteger bytesRead = [inputStream read:buffer maxLength:1024]; - if (inputStream.streamError || bytesRead < 0) { - error = inputStream.streamError; - break; - } - - NSInteger bytesWritten = [outputStream write:buffer maxLength:(NSUInteger)bytesRead]; - if (outputStream.streamError || bytesWritten < 0) { - error = outputStream.streamError; - break; - } - - if (bytesRead == 0 && bytesWritten == 0) { - break; - } - } - - [outputStream close]; - [inputStream close]; - - if (handler) { - dispatch_async(dispatch_get_main_queue(), ^{ - handler(error); - }); - } - }); - - NSMutableURLRequest *mutableRequest = [request mutableCopy]; - mutableRequest.HTTPBodyStream = nil; - - return mutableRequest; -} - -#pragma mark - AFURLRequestSerialization - -- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request - withParameters:(id)parameters - error:(NSError *__autoreleasing *)error -{ - NSParameterAssert(request); - - NSMutableURLRequest *mutableRequest = [request mutableCopy]; - - [self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) { - if (![request valueForHTTPHeaderField:field]) { - [mutableRequest setValue:value forHTTPHeaderField:field]; - } - }]; - - if (parameters) { - NSString *query = nil; - if (self.queryStringSerialization) { - NSError *serializationError; - query = self.queryStringSerialization(request, parameters, &serializationError); - - if (serializationError) { - if (error) { - *error = serializationError; - } - - return nil; - } - } else { - switch (self.queryStringSerializationStyle) { - case AFHTTPRequestQueryStringDefaultStyle: - query = AFQueryStringFromParametersWithEncoding(parameters, self.stringEncoding); - break; - } - } - - if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) { - mutableRequest.URL = [NSURL URLWithString:[[mutableRequest.URL absoluteString] stringByAppendingFormat:mutableRequest.URL.query ? @"&%@" : @"?%@", query]]; - } else { - if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) { - [mutableRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; - } - [mutableRequest setHTTPBody:[query dataUsingEncoding:self.stringEncoding]]; - } - } - - return mutableRequest; -} - -#pragma mark - NSKeyValueObserving - -- (void)observeValueForKeyPath:(NSString *)keyPath - ofObject:(__unused id)object - change:(NSDictionary *)change - context:(void *)context -{ - if (context == AFHTTPRequestSerializerObserverContext) { - if ([change[NSKeyValueChangeNewKey] isEqual:[NSNull null]]) { - [self.mutableObservedChangedKeyPaths removeObject:keyPath]; - } else { - [self.mutableObservedChangedKeyPaths addObject:keyPath]; - } - } -} - -#pragma mark - NSSecureCoding - -+ (BOOL)supportsSecureCoding { - return YES; -} - -- (id)initWithCoder:(NSCoder *)decoder { - self = [self init]; - if (!self) { - return nil; - } - - self.mutableHTTPRequestHeaders = [[decoder decodeObjectOfClass:[NSDictionary class] forKey:NSStringFromSelector(@selector(mutableHTTPRequestHeaders))] mutableCopy]; - self.queryStringSerializationStyle = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(queryStringSerializationStyle))] unsignedIntegerValue]; - - return self; -} - -- (void)encodeWithCoder:(NSCoder *)coder { - [coder encodeObject:self.mutableHTTPRequestHeaders forKey:NSStringFromSelector(@selector(mutableHTTPRequestHeaders))]; - [coder encodeInteger:self.queryStringSerializationStyle forKey:NSStringFromSelector(@selector(queryStringSerializationStyle))]; -} - -#pragma mark - NSCopying - -- (id)copyWithZone:(NSZone *)zone { - AFHTTPRequestSerializer *serializer = [[[self class] allocWithZone:zone] init]; - serializer.mutableHTTPRequestHeaders = [self.mutableHTTPRequestHeaders mutableCopyWithZone:zone]; - serializer.queryStringSerializationStyle = self.queryStringSerializationStyle; - serializer.queryStringSerialization = self.queryStringSerialization; - - return serializer; -} - -@end - -#pragma mark - - -static NSString * AFCreateMultipartFormBoundary() { - return [NSString stringWithFormat:@"Boundary+%08X%08X", arc4random(), arc4random()]; -} - -static NSString * const kAFMultipartFormCRLF = @"\r\n"; - -static inline NSString * AFMultipartFormInitialBoundary(NSString *boundary) { - return [NSString stringWithFormat:@"--%@%@", boundary, kAFMultipartFormCRLF]; -} - -static inline NSString * AFMultipartFormEncapsulationBoundary(NSString *boundary) { - return [NSString stringWithFormat:@"%@--%@%@", kAFMultipartFormCRLF, boundary, kAFMultipartFormCRLF]; -} - -static inline NSString * AFMultipartFormFinalBoundary(NSString *boundary) { - return [NSString stringWithFormat:@"%@--%@--%@", kAFMultipartFormCRLF, boundary, kAFMultipartFormCRLF]; -} - -static inline NSString * AFContentTypeForPathExtension(NSString *extension) { -#ifdef __UTTYPE__ - NSString *UTI = (__bridge_transfer NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)extension, NULL); - NSString *contentType = (__bridge_transfer NSString *)UTTypeCopyPreferredTagWithClass((__bridge CFStringRef)UTI, kUTTagClassMIMEType); - if (!contentType) { - return @"application/octet-stream"; - } else { - return contentType; - } -#else -#pragma unused (extension) - return @"application/octet-stream"; -#endif -} - -NSUInteger const kAFUploadStream3GSuggestedPacketSize = 1024 * 16; -NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2; - -@interface AFHTTPBodyPart : NSObject -@property (nonatomic, assign) NSStringEncoding stringEncoding; -@property (nonatomic, strong) NSDictionary *headers; -@property (nonatomic, copy) NSString *boundary; -@property (nonatomic, strong) id body; -@property (nonatomic, assign) unsigned long long bodyContentLength; -@property (nonatomic, strong) NSInputStream *inputStream; - -@property (nonatomic, assign) BOOL hasInitialBoundary; -@property (nonatomic, assign) BOOL hasFinalBoundary; - -@property (readonly, nonatomic, assign, getter = hasBytesAvailable) BOOL bytesAvailable; -@property (readonly, nonatomic, assign) unsigned long long contentLength; - -- (NSInteger)read:(uint8_t *)buffer - maxLength:(NSUInteger)length; -@end - -@interface AFMultipartBodyStream : NSInputStream <NSStreamDelegate> -@property (nonatomic, assign) NSUInteger numberOfBytesInPacket; -@property (nonatomic, assign) NSTimeInterval delay; -@property (nonatomic, strong) NSInputStream *inputStream; -@property (readonly, nonatomic, assign) unsigned long long contentLength; -@property (readonly, nonatomic, assign, getter = isEmpty) BOOL empty; - -- (id)initWithStringEncoding:(NSStringEncoding)encoding; -- (void)setInitialAndFinalBoundaries; -- (void)appendHTTPBodyPart:(AFHTTPBodyPart *)bodyPart; -@end - -#pragma mark - - -@interface AFStreamingMultipartFormData () -@property (readwrite, nonatomic, copy) NSMutableURLRequest *request; -@property (readwrite, nonatomic, assign) NSStringEncoding stringEncoding; -@property (readwrite, nonatomic, copy) NSString *boundary; -@property (readwrite, nonatomic, strong) AFMultipartBodyStream *bodyStream; -@end - -@implementation AFStreamingMultipartFormData - -- (id)initWithURLRequest:(NSMutableURLRequest *)urlRequest - stringEncoding:(NSStringEncoding)encoding -{ - self = [super init]; - if (!self) { - return nil; - } - - self.request = urlRequest; - self.stringEncoding = encoding; - self.boundary = AFCreateMultipartFormBoundary(); - self.bodyStream = [[AFMultipartBodyStream alloc] initWithStringEncoding:encoding]; - - return self; -} - -- (BOOL)appendPartWithFileURL:(NSURL *)fileURL - name:(NSString *)name - error:(NSError * __autoreleasing *)error -{ - NSParameterAssert(fileURL); - NSParameterAssert(name); - - NSString *fileName = [fileURL lastPathComponent]; - NSString *mimeType = AFContentTypeForPathExtension([fileURL pathExtension]); - - return [self appendPartWithFileURL:fileURL name:name fileName:fileName mimeType:mimeType error:error]; -} - -- (BOOL)appendPartWithFileURL:(NSURL *)fileURL - name:(NSString *)name - fileName:(NSString *)fileName - mimeType:(NSString *)mimeType - error:(NSError * __autoreleasing *)error -{ - NSParameterAssert(fileURL); - NSParameterAssert(name); - NSParameterAssert(fileName); - NSParameterAssert(mimeType); - - if (![fileURL isFileURL]) { - NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey: NSLocalizedStringFromTable(@"Expected URL to be a file URL", @"AFNetworking", nil)}; - if (error) { - *error = [[NSError alloc] initWithDomain:AFURLRequestSerializationErrorDomain code:NSURLErrorBadURL userInfo:userInfo]; - } - - return NO; - } else if ([fileURL checkResourceIsReachableAndReturnError:error] == NO) { - NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey: NSLocalizedStringFromTable(@"File URL not reachable.", @"AFNetworking", nil)}; - if (error) { - *error = [[NSError alloc] initWithDomain:AFURLRequestSerializationErrorDomain code:NSURLErrorBadURL userInfo:userInfo]; - } - - return NO; - } - - NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[fileURL path] error:error]; - if (!fileAttributes) { - return NO; - } - - NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary]; - [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"]; - [mutableHeaders setValue:mimeType forKey:@"Content-Type"]; - - AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init]; - bodyPart.stringEncoding = self.stringEncoding; - bodyPart.headers = mutableHeaders; - bodyPart.boundary = self.boundary; - bodyPart.body = fileURL; - bodyPart.bodyContentLength = [[fileAttributes objectForKey:NSFileSize] unsignedLongLongValue]; - [self.bodyStream appendHTTPBodyPart:bodyPart]; - - return YES; -} - -- (void)appendPartWithInputStream:(NSInputStream *)inputStream - name:(NSString *)name - fileName:(NSString *)fileName - length:(int64_t)length - mimeType:(NSString *)mimeType -{ - NSParameterAssert(name); - NSParameterAssert(fileName); - NSParameterAssert(mimeType); - - NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary]; - [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"]; - [mutableHeaders setValue:mimeType forKey:@"Content-Type"]; - - AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init]; - bodyPart.stringEncoding = self.stringEncoding; - bodyPart.headers = mutableHeaders; - bodyPart.boundary = self.boundary; - bodyPart.body = inputStream; - - bodyPart.bodyContentLength = (unsigned long long)length; - - [self.bodyStream appendHTTPBodyPart:bodyPart]; -} - -- (void)appendPartWithFileData:(NSData *)data - name:(NSString *)name - fileName:(NSString *)fileName - mimeType:(NSString *)mimeType -{ - NSParameterAssert(name); - NSParameterAssert(fileName); - NSParameterAssert(mimeType); - - NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary]; - [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"]; - [mutableHeaders setValue:mimeType forKey:@"Content-Type"]; - - [self appendPartWithHeaders:mutableHeaders body:data]; -} - -- (void)appendPartWithFormData:(NSData *)data - name:(NSString *)name -{ - NSParameterAssert(name); - - NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary]; - [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"", name] forKey:@"Content-Disposition"]; - - [self appendPartWithHeaders:mutableHeaders body:data]; -} - -- (void)appendPartWithHeaders:(NSDictionary *)headers - body:(NSData *)body -{ - NSParameterAssert(body); - - AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init]; - bodyPart.stringEncoding = self.stringEncoding; - bodyPart.headers = headers; - bodyPart.boundary = self.boundary; - bodyPart.bodyContentLength = [body length]; - bodyPart.body = body; - - [self.bodyStream appendHTTPBodyPart:bodyPart]; -} - -- (void)throttleBandwidthWithPacketSize:(NSUInteger)numberOfBytes - delay:(NSTimeInterval)delay -{ - self.bodyStream.numberOfBytesInPacket = numberOfBytes; - self.bodyStream.delay = delay; -} - -- (NSMutableURLRequest *)requestByFinalizingMultipartFormData { - if ([self.bodyStream isEmpty]) { - return self.request; - } - - // Reset the initial and final boundaries to ensure correct Content-Length - [self.bodyStream setInitialAndFinalBoundaries]; - [self.request setHTTPBodyStream:self.bodyStream]; - - [self.request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", self.boundary] forHTTPHeaderField:@"Content-Type"]; - [self.request setValue:[NSString stringWithFormat:@"%llu", [self.bodyStream contentLength]] forHTTPHeaderField:@"Content-Length"]; - - return self.request; -} - -@end - -#pragma mark - - -@interface NSStream () -@property (readwrite) NSStreamStatus streamStatus; -@property (readwrite, copy) NSError *streamError; -@end - -@interface AFMultipartBodyStream () <NSCopying> -@property (readwrite, nonatomic, assign) NSStringEncoding stringEncoding; -@property (readwrite, nonatomic, strong) NSMutableArray *HTTPBodyParts; -@property (readwrite, nonatomic, strong) NSEnumerator *HTTPBodyPartEnumerator; -@property (readwrite, nonatomic, strong) AFHTTPBodyPart *currentHTTPBodyPart; -@property (readwrite, nonatomic, strong) NSOutputStream *outputStream; -@property (readwrite, nonatomic, strong) NSMutableData *buffer; -@end - -@implementation AFMultipartBodyStream -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wimplicit-atomic-properties" -#if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000) || (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1100) -@synthesize delegate; -#endif -@synthesize streamStatus; -@synthesize streamError; -#pragma clang diagnostic pop - -- (id)initWithStringEncoding:(NSStringEncoding)encoding { - self = [super init]; - if (!self) { - return nil; - } - - self.stringEncoding = encoding; - self.HTTPBodyParts = [NSMutableArray array]; - self.numberOfBytesInPacket = NSIntegerMax; - - return self; -} - -- (void)setInitialAndFinalBoundaries { - if ([self.HTTPBodyParts count] > 0) { - for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) { - bodyPart.hasInitialBoundary = NO; - bodyPart.hasFinalBoundary = NO; - } - - [[self.HTTPBodyParts objectAtIndex:0] setHasInitialBoundary:YES]; - [[self.HTTPBodyParts lastObject] setHasFinalBoundary:YES]; - } -} - -- (void)appendHTTPBodyPart:(AFHTTPBodyPart *)bodyPart { - [self.HTTPBodyParts addObject:bodyPart]; -} - -- (BOOL)isEmpty { - return [self.HTTPBodyParts count] == 0; -} - -#pragma mark - NSInputStream - -- (NSInteger)read:(uint8_t *)buffer - maxLength:(NSUInteger)length -{ - if ([self streamStatus] == NSStreamStatusClosed) { - return 0; - } - - NSInteger totalNumberOfBytesRead = 0; - -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wgnu" - while ((NSUInteger)totalNumberOfBytesRead < MIN(length, self.numberOfBytesInPacket)) { - if (!self.currentHTTPBodyPart || ![self.currentHTTPBodyPart hasBytesAvailable]) { - if (!(self.currentHTTPBodyPart = [self.HTTPBodyPartEnumerator nextObject])) { - break; - } - } else { - NSUInteger maxLength = length - (NSUInteger)totalNumberOfBytesRead; - NSInteger numberOfBytesRead = [self.currentHTTPBodyPart read:&buffer[totalNumberOfBytesRead] maxLength:maxLength]; - if (numberOfBytesRead == -1) { - self.streamError = self.currentHTTPBodyPart.inputStream.streamError; - break; - } else { - totalNumberOfBytesRead += numberOfBytesRead; - - if (self.delay > 0.0f) { - [NSThread sleepForTimeInterval:self.delay]; - } - } - } - } -#pragma clang diagnostic pop - - return totalNumberOfBytesRead; -} - -- (BOOL)getBuffer:(__unused uint8_t **)buffer - length:(__unused NSUInteger *)len -{ - return NO; -} - -- (BOOL)hasBytesAvailable { - return [self streamStatus] == NSStreamStatusOpen; -} - -#pragma mark - NSStream - -- (void)open { - if (self.streamStatus == NSStreamStatusOpen) { - return; - } - - self.streamStatus = NSStreamStatusOpen; - - [self setInitialAndFinalBoundaries]; - self.HTTPBodyPartEnumerator = [self.HTTPBodyParts objectEnumerator]; -} - -- (void)close { - self.streamStatus = NSStreamStatusClosed; -} - -- (id)propertyForKey:(__unused NSString *)key { - return nil; -} - -- (BOOL)setProperty:(__unused id)property - forKey:(__unused NSString *)key -{ - return NO; -} - -- (void)scheduleInRunLoop:(__unused NSRunLoop *)aRunLoop - forMode:(__unused NSString *)mode -{} - -- (void)removeFromRunLoop:(__unused NSRunLoop *)aRunLoop - forMode:(__unused NSString *)mode -{} - -- (unsigned long long)contentLength { - unsigned long long length = 0; - for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) { - length += [bodyPart contentLength]; - } - - return length; -} - -#pragma mark - Undocumented CFReadStream Bridged Methods - -- (void)_scheduleInCFRunLoop:(__unused CFRunLoopRef)aRunLoop - forMode:(__unused CFStringRef)aMode -{} - -- (void)_unscheduleFromCFRunLoop:(__unused CFRunLoopRef)aRunLoop - forMode:(__unused CFStringRef)aMode -{} - -- (BOOL)_setCFClientFlags:(__unused CFOptionFlags)inFlags - callback:(__unused CFReadStreamClientCallBack)inCallback - context:(__unused CFStreamClientContext *)inContext { - return NO; -} - -#pragma mark - NSCopying - --(id)copyWithZone:(NSZone *)zone { - AFMultipartBodyStream *bodyStreamCopy = [[[self class] allocWithZone:zone] initWithStringEncoding:self.stringEncoding]; - - for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) { - [bodyStreamCopy appendHTTPBodyPart:[bodyPart copy]]; - } - - [bodyStreamCopy setInitialAndFinalBoundaries]; - - return bodyStreamCopy; -} - -@end - -#pragma mark - - -typedef enum { - AFEncapsulationBoundaryPhase = 1, - AFHeaderPhase = 2, - AFBodyPhase = 3, - AFFinalBoundaryPhase = 4, -} AFHTTPBodyPartReadPhase; - -@interface AFHTTPBodyPart () <NSCopying> { - AFHTTPBodyPartReadPhase _phase; - NSInputStream *_inputStream; - unsigned long long _phaseReadOffset; -} - -- (BOOL)transitionToNextPhase; -- (NSInteger)readData:(NSData *)data - intoBuffer:(uint8_t *)buffer - maxLength:(NSUInteger)length; -@end - -@implementation AFHTTPBodyPart - -- (id)init { - self = [super init]; - if (!self) { - return nil; - } - - [self transitionToNextPhase]; - - return self; -} - -- (void)dealloc { - if (_inputStream) { - [_inputStream close]; - _inputStream = nil; - } -} - -- (NSInputStream *)inputStream { - if (!_inputStream) { - if ([self.body isKindOfClass:[NSData class]]) { - _inputStream = [NSInputStream inputStreamWithData:self.body]; - } else if ([self.body isKindOfClass:[NSURL class]]) { - _inputStream = [NSInputStream inputStreamWithURL:self.body]; - } else if ([self.body isKindOfClass:[NSInputStream class]]) { - _inputStream = self.body; - } else { - _inputStream = [NSInputStream inputStreamWithData:[NSData data]]; - } - } - - return _inputStream; -} - -- (NSString *)stringForHeaders { - NSMutableString *headerString = [NSMutableString string]; - for (NSString *field in [self.headers allKeys]) { - [headerString appendString:[NSString stringWithFormat:@"%@: %@%@", field, [self.headers valueForKey:field], kAFMultipartFormCRLF]]; - } - [headerString appendString:kAFMultipartFormCRLF]; - - return [NSString stringWithString:headerString]; -} - -- (unsigned long long)contentLength { - unsigned long long length = 0; - - NSData *encapsulationBoundaryData = [([self hasInitialBoundary] ? AFMultipartFormInitialBoundary(self.boundary) : AFMultipartFormEncapsulationBoundary(self.boundary)) dataUsingEncoding:self.stringEncoding]; - length += [encapsulationBoundaryData length]; - - NSData *headersData = [[self stringForHeaders] dataUsingEncoding:self.stringEncoding]; - length += [headersData length]; - - length += _bodyContentLength; - - NSData *closingBoundaryData = ([self hasFinalBoundary] ? [AFMultipartFormFinalBoundary(self.boundary) dataUsingEncoding:self.stringEncoding] : [NSData data]); - length += [closingBoundaryData length]; - - return length; -} - -- (BOOL)hasBytesAvailable { - // Allows `read:maxLength:` to be called again if `AFMultipartFormFinalBoundary` doesn't fit into the available buffer - if (_phase == AFFinalBoundaryPhase) { - return YES; - } - -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wcovered-switch-default" - switch (self.inputStream.streamStatus) { - case NSStreamStatusNotOpen: - case NSStreamStatusOpening: - case NSStreamStatusOpen: - case NSStreamStatusReading: - case NSStreamStatusWriting: - return YES; - case NSStreamStatusAtEnd: - case NSStreamStatusClosed: - case NSStreamStatusError: - default: - return NO; - } -#pragma clang diagnostic pop -} - -- (NSInteger)read:(uint8_t *)buffer - maxLength:(NSUInteger)length -{ - NSInteger totalNumberOfBytesRead = 0; - - if (_phase == AFEncapsulationBoundaryPhase) { - NSData *encapsulationBoundaryData = [([self hasInitialBoundary] ? AFMultipartFormInitialBoundary(self.boundary) : AFMultipartFormEncapsulationBoundary(self.boundary)) dataUsingEncoding:self.stringEncoding]; - totalNumberOfBytesRead += [self readData:encapsulationBoundaryData intoBuffer:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)]; - } - - if (_phase == AFHeaderPhase) { - NSData *headersData = [[self stringForHeaders] dataUsingEncoding:self.stringEncoding]; - totalNumberOfBytesRead += [self readData:headersData intoBuffer:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)]; - } - - if (_phase == AFBodyPhase) { - NSInteger numberOfBytesRead = 0; - - numberOfBytesRead = [self.inputStream read:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)]; - if (numberOfBytesRead == -1) { - return -1; - } else { - totalNumberOfBytesRead += numberOfBytesRead; - - if ([self.inputStream streamStatus] >= NSStreamStatusAtEnd) { - [self transitionToNextPhase]; - } - } - } - - if (_phase == AFFinalBoundaryPhase) { - NSData *closingBoundaryData = ([self hasFinalBoundary] ? [AFMultipartFormFinalBoundary(self.boundary) dataUsingEncoding:self.stringEncoding] : [NSData data]); - totalNumberOfBytesRead += [self readData:closingBoundaryData intoBuffer:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)]; - } - - return totalNumberOfBytesRead; -} - -- (NSInteger)readData:(NSData *)data - intoBuffer:(uint8_t *)buffer - maxLength:(NSUInteger)length -{ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wgnu" - NSRange range = NSMakeRange((NSUInteger)_phaseReadOffset, MIN([data length] - ((NSUInteger)_phaseReadOffset), length)); - [data getBytes:buffer range:range]; -#pragma clang diagnostic pop - - _phaseReadOffset += range.length; - - if (((NSUInteger)_phaseReadOffset) >= [data length]) { - [self transitionToNextPhase]; - } - - return (NSInteger)range.length; -} - -- (BOOL)transitionToNextPhase { - if (![[NSThread currentThread] isMainThread]) { - [self performSelectorOnMainThread:@selector(transitionToNextPhase) withObject:nil waitUntilDone:YES]; - return YES; - } - -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wcovered-switch-default" - switch (_phase) { - case AFEncapsulationBoundaryPhase: - _phase = AFHeaderPhase; - break; - case AFHeaderPhase: - [self.inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes]; - [self.inputStream open]; - _phase = AFBodyPhase; - break; - case AFBodyPhase: - [self.inputStream close]; - _phase = AFFinalBoundaryPhase; - break; - case AFFinalBoundaryPhase: - default: - _phase = AFEncapsulationBoundaryPhase; - break; - } - _phaseReadOffset = 0; -#pragma clang diagnostic pop - - return YES; -} - -#pragma mark - NSCopying - -- (id)copyWithZone:(NSZone *)zone { - AFHTTPBodyPart *bodyPart = [[[self class] allocWithZone:zone] init]; - - bodyPart.stringEncoding = self.stringEncoding; - bodyPart.headers = self.headers; - bodyPart.bodyContentLength = self.bodyContentLength; - bodyPart.body = self.body; - bodyPart.boundary = self.boundary; - - return bodyPart; -} - -@end - -#pragma mark - - -@implementation AFJSONRequestSerializer - -+ (instancetype)serializer { - return [self serializerWithWritingOptions:(NSJSONWritingOptions)0]; -} - -+ (instancetype)serializerWithWritingOptions:(NSJSONWritingOptions)writingOptions -{ - AFJSONRequestSerializer *serializer = [[self alloc] init]; - serializer.writingOptions = writingOptions; - - return serializer; -} - -#pragma mark - AFURLRequestSerialization - -- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request - withParameters:(id)parameters - error:(NSError *__autoreleasing *)error -{ - NSParameterAssert(request); - - if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) { - return [super requestBySerializingRequest:request withParameters:parameters error:error]; - } - - NSMutableURLRequest *mutableRequest = [request mutableCopy]; - - [self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) { - if (![request valueForHTTPHeaderField:field]) { - [mutableRequest setValue:value forHTTPHeaderField:field]; - } - }]; - - if (parameters) { - if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) { - NSString *charset = (__bridge NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding)); - [mutableRequest setValue:[NSString stringWithFormat:@"application/json; charset=%@", charset] forHTTPHeaderField:@"Content-Type"]; - } - - [mutableRequest setHTTPBody:[NSJSONSerialization dataWithJSONObject:parameters options:self.writingOptions error:error]]; - } - - return mutableRequest; -} - -#pragma mark - NSSecureCoding - -- (id)initWithCoder:(NSCoder *)decoder { - self = [super initWithCoder:decoder]; - if (!self) { - return nil; - } - - self.writingOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(writingOptions))] unsignedIntegerValue]; - - return self; -} - -- (void)encodeWithCoder:(NSCoder *)coder { - [super encodeWithCoder:coder]; - - [coder encodeInteger:self.writingOptions forKey:NSStringFromSelector(@selector(writingOptions))]; -} - -#pragma mark - NSCopying - -- (id)copyWithZone:(NSZone *)zone { - AFJSONRequestSerializer *serializer = [super copyWithZone:zone]; - serializer.writingOptions = self.writingOptions; - - return serializer; -} - -@end - -#pragma mark - - -@implementation AFPropertyListRequestSerializer - -+ (instancetype)serializer { - return [self serializerWithFormat:NSPropertyListXMLFormat_v1_0 writeOptions:0]; -} - -+ (instancetype)serializerWithFormat:(NSPropertyListFormat)format - writeOptions:(NSPropertyListWriteOptions)writeOptions -{ - AFPropertyListRequestSerializer *serializer = [[self alloc] init]; - serializer.format = format; - serializer.writeOptions = writeOptions; - - return serializer; -} - -#pragma mark - AFURLRequestSerializer - -- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request - withParameters:(id)parameters - error:(NSError *__autoreleasing *)error -{ - NSParameterAssert(request); - - if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) { - return [super requestBySerializingRequest:request withParameters:parameters error:error]; - } - - NSMutableURLRequest *mutableRequest = [request mutableCopy]; - - [self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) { - if (![request valueForHTTPHeaderField:field]) { - [mutableRequest setValue:value forHTTPHeaderField:field]; - } - }]; - - if (parameters) { - if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) { - NSString *charset = (__bridge NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding)); - [mutableRequest setValue:[NSString stringWithFormat:@"application/x-plist; charset=%@", charset] forHTTPHeaderField:@"Content-Type"]; - } - - [mutableRequest setHTTPBody:[NSPropertyListSerialization dataWithPropertyList:parameters format:self.format options:self.writeOptions error:error]]; - } - - return mutableRequest; -} - -#pragma mark - NSSecureCoding - -- (id)initWithCoder:(NSCoder *)decoder { - self = [super initWithCoder:decoder]; - if (!self) { - return nil; - } - - self.format = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(format))] unsignedIntegerValue]; - self.writeOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(writeOptions))] unsignedIntegerValue]; - - return self; -} - -- (void)encodeWithCoder:(NSCoder *)coder { - [super encodeWithCoder:coder]; - - [coder encodeInteger:self.format forKey:NSStringFromSelector(@selector(format))]; - [coder encodeObject:@(self.writeOptions) forKey:NSStringFromSelector(@selector(writeOptions))]; -} - -#pragma mark - NSCopying - -- (id)copyWithZone:(NSZone *)zone { - AFPropertyListRequestSerializer *serializer = [super copyWithZone:zone]; - serializer.format = self.format; - serializer.writeOptions = self.writeOptions; - - return serializer; -} - -@end diff --git a/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFURLResponseSerialization.h b/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFURLResponseSerialization.h deleted file mode 100644 index 14268165..00000000 --- a/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFURLResponseSerialization.h +++ /dev/null @@ -1,302 +0,0 @@ -// AFSerialization.h -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import <Foundation/Foundation.h> -#import <CoreGraphics/CoreGraphics.h> - -/** - 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. - - 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. - */ -@protocol AFURLResponseSerialization <NSObject, NSSecureCoding, NSCopying> - -/** - The response object decoded from the data associated with a specified response. - - @param response The response to be processed. - @param data The response data to be decoded. - @param error The error that occurred while attempting to decode the response data. - - @return The object decoded from the specified response data. - */ -- (id)responseObjectForResponse:(NSURLResponse *)response - data:(NSData *)data - error:(NSError *__autoreleasing *)error; - -@end - -#pragma mark - - -/** - `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. - - Any request or response serializer dealing with HTTP is encouraged to subclass `AFHTTPResponseSerializer` in order to ensure consistent default behavior. - */ -@interface AFHTTPResponseSerializer : NSObject <AFURLResponseSerialization> - -/** - The string encoding used to serialize parameters. - */ -@property (nonatomic, assign) NSStringEncoding stringEncoding; - -/** - Creates and returns a serializer with default configuration. - */ -+ (instancetype)serializer; - -///----------------------------------------- -/// @name Configuring Response Serialization -///----------------------------------------- - -/** - 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. - - See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html - */ -@property (nonatomic, copy) NSIndexSet *acceptableStatusCodes; - -/** - 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. - */ -@property (nonatomic, copy) NSSet *acceptableContentTypes; - -/** - Validates the specified response and data. - - In its base implementation, this method checks for an acceptable status code and content type. Subclasses may wish to add other domain-specific checks. - - @param response The response to be validated. - @param data The data associated with the response. - @param error The error that occurred while attempting to validate the response. - - @return `YES` if the response is valid, otherwise `NO`. - */ -- (BOOL)validateResponse:(NSHTTPURLResponse *)response - data:(NSData *)data - error:(NSError *__autoreleasing *)error; - -@end - -#pragma mark - - - -/** - `AFJSONResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes JSON responses. - - By default, `AFJSONResponseSerializer` accepts the following MIME types, which includes the official standard, `application/json`, as well as other commonly-used types: - - - `application/json` - - `text/json` - - `text/javascript` - */ -@interface AFJSONResponseSerializer : AFHTTPResponseSerializer - -/** - Options for reading the response JSON data and creating the Foundation objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONReadingOptions". `0` by default. - */ -@property (nonatomic, assign) NSJSONReadingOptions readingOptions; - -/** - Whether to remove keys with `NSNull` values from response JSON. Defaults to `NO`. - */ -@property (nonatomic, assign) BOOL removesKeysWithNullValues; - -/** - Creates and returns a JSON serializer with specified reading and writing options. - - @param readingOptions The specified JSON reading options. - */ -+ (instancetype)serializerWithReadingOptions:(NSJSONReadingOptions)readingOptions; - -@end - -#pragma mark - - -/** - `AFXMLParserSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLParser` objects. - - By default, `AFXMLParserSerializer` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types: - - - `application/xml` - - `text/xml` - */ -@interface AFXMLParserResponseSerializer : AFHTTPResponseSerializer - -@end - -#pragma mark - - -#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED - -/** - `AFXMLDocumentSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLDocument` objects. - - By default, `AFXMLDocumentSerializer` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types: - - - `application/xml` - - `text/xml` - */ -@interface AFXMLDocumentResponseSerializer : AFHTTPResponseSerializer - -/** - Input and output options specifically intended for `NSXMLDocument` objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONReadingOptions". `0` by default. - */ -@property (nonatomic, assign) NSUInteger options; - -/** - Creates and returns an XML document serializer with the specified options. - - @param mask The XML document options. - */ -+ (instancetype)serializerWithXMLDocumentOptions:(NSUInteger)mask; - -@end - -#endif - -#pragma mark - - -/** - `AFPropertyListSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLDocument` objects. - - By default, `AFPropertyListSerializer` accepts the following MIME types: - - - `application/x-plist` - */ -@interface AFPropertyListResponseSerializer : AFHTTPResponseSerializer - -/** - The property list format. Possible values are described in "NSPropertyListFormat". - */ -@property (nonatomic, assign) NSPropertyListFormat format; - -/** - The property list reading options. Possible values are described in "NSPropertyListMutabilityOptions." - */ -@property (nonatomic, assign) NSPropertyListReadOptions readOptions; - -/** - Creates and returns a property list serializer with a specified format, read options, and write options. - - @param format The property list format. - @param readOptions The property list reading options. - */ -+ (instancetype)serializerWithFormat:(NSPropertyListFormat)format - readOptions:(NSPropertyListReadOptions)readOptions; - -@end - -#pragma mark - - -/** - `AFImageSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes image responses. - - By default, `AFImageSerializer` accepts the following MIME types, which correspond to the image formats supported by UIImage or NSImage: - - - `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` - */ -@interface AFImageResponseSerializer : AFHTTPResponseSerializer - -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) -/** - 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. - */ -@property (nonatomic, assign) CGFloat imageScale; - -/** - 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. - */ -@property (nonatomic, assign) BOOL automaticallyInflatesResponseImage; -#endif - -@end - -#pragma mark - - -/** - `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. - */ -@interface AFCompoundResponseSerializer : AFHTTPResponseSerializer - -/** - The component response serializers. - */ -@property (readonly, nonatomic, copy) NSArray *responseSerializers; - -/** - Creates and returns a compound serializer comprised of the specified response serializers. - - @warning Each response serializer specified must be a subclass of `AFHTTPResponseSerializer`, and response to `-validateResponse:data:error:`. - */ -+ (instancetype)compoundSerializerWithResponseSerializers:(NSArray *)responseSerializers; - -@end - -///---------------- -/// @name Constants -///---------------- - -/** - ## Error Domains - - The following error domain is predefined. - - - `NSString * const AFURLResponseSerializationErrorDomain` - - ### Constants - - `AFURLResponseSerializationErrorDomain` - AFURLResponseSerializer errors. Error codes for `AFURLResponseSerializationErrorDomain` correspond to codes in `NSURLErrorDomain`. - */ -extern NSString * const AFURLResponseSerializationErrorDomain; - -/** - ## User info dictionary keys - - These keys may exist in the user info dictionary, in addition to those defined for NSError. - - - `NSString * const AFNetworkingOperationFailingURLResponseErrorKey` - - `NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey` - - ### Constants - - `AFNetworkingOperationFailingURLResponseErrorKey` - The corresponding value is an `NSURLResponse` containing the response of the operation associated with an error. This key is only present in the `AFURLResponseSerializationErrorDomain`. - - `AFNetworkingOperationFailingURLResponseDataErrorKey` - 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`. - */ -extern NSString * const AFNetworkingOperationFailingURLResponseErrorKey; - -extern NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey; - - diff --git a/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFURLResponseSerialization.m b/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFURLResponseSerialization.m deleted file mode 100644 index 7b042f75..00000000 --- a/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFURLResponseSerialization.m +++ /dev/null @@ -1,793 +0,0 @@ -// AFSerialization.h -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import "AFURLResponseSerialization.h" - -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) -#import <UIKit/UIKit.h> -#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED) -#import <Cocoa/Cocoa.h> -#endif - -NSString * const AFURLResponseSerializationErrorDomain = @"com.alamofire.error.serialization.response"; -NSString * const AFNetworkingOperationFailingURLResponseErrorKey = @"com.alamofire.serialization.response.error.response"; -NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey = @"com.alamofire.serialization.response.error.data"; - -static NSError * AFErrorWithUnderlyingError(NSError *error, NSError *underlyingError) { - if (!error) { - return underlyingError; - } - - if (!underlyingError || error.userInfo[NSUnderlyingErrorKey]) { - return error; - } - - NSMutableDictionary *mutableUserInfo = [error.userInfo mutableCopy]; - mutableUserInfo[NSUnderlyingErrorKey] = underlyingError; - - return [[NSError alloc] initWithDomain:error.domain code:error.code userInfo:mutableUserInfo]; -} - -static BOOL AFErrorOrUnderlyingErrorHasCodeInDomain(NSError *error, NSInteger code, NSString *domain) { - if ([error.domain isEqualToString:domain] && error.code == code) { - return YES; - } else if (error.userInfo[NSUnderlyingErrorKey]) { - return AFErrorOrUnderlyingErrorHasCodeInDomain(error.userInfo[NSUnderlyingErrorKey], code, domain); - } - - return NO; -} - -static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingOptions readingOptions) { - if ([JSONObject isKindOfClass:[NSArray class]]) { - NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:[(NSArray *)JSONObject count]]; - for (id value in (NSArray *)JSONObject) { - [mutableArray addObject:AFJSONObjectByRemovingKeysWithNullValues(value, readingOptions)]; - } - - return (readingOptions & NSJSONReadingMutableContainers) ? mutableArray : [NSArray arrayWithArray:mutableArray]; - } else if ([JSONObject isKindOfClass:[NSDictionary class]]) { - NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithDictionary:JSONObject]; - for (id <NSCopying> key in [(NSDictionary *)JSONObject allKeys]) { - id value = [(NSDictionary *)JSONObject objectForKey:key]; - if (!value || [value isEqual:[NSNull null]]) { - [mutableDictionary removeObjectForKey:key]; - } else if ([value isKindOfClass:[NSArray class]] || [value isKindOfClass:[NSDictionary class]]) { - [mutableDictionary setObject:AFJSONObjectByRemovingKeysWithNullValues(value, readingOptions) forKey:key]; - } - } - - return (readingOptions & NSJSONReadingMutableContainers) ? mutableDictionary : [NSDictionary dictionaryWithDictionary:mutableDictionary]; - } - - return JSONObject; -} - -@implementation AFHTTPResponseSerializer - -+ (instancetype)serializer { - return [[self alloc] init]; -} - -- (instancetype)init { - self = [super init]; - if (!self) { - return nil; - } - - self.stringEncoding = NSUTF8StringEncoding; - - self.acceptableStatusCodes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)]; - self.acceptableContentTypes = nil; - - return self; -} - -#pragma mark - - -- (BOOL)validateResponse:(NSHTTPURLResponse *)response - data:(NSData *)data - error:(NSError * __autoreleasing *)error -{ - BOOL responseIsValid = YES; - NSError *validationError = nil; - - if (response && [response isKindOfClass:[NSHTTPURLResponse class]]) { - if (self.acceptableContentTypes && ![self.acceptableContentTypes containsObject:[response MIMEType]]) { - if ([data length] > 0) { - NSMutableDictionary *mutableUserInfo = [@{ - NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Request failed: unacceptable content-type: %@", @"AFNetworking", nil), [response MIMEType]], - NSURLErrorFailingURLErrorKey:[response URL], - AFNetworkingOperationFailingURLResponseErrorKey: response, - } mutableCopy]; - if (data) { - mutableUserInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] = data; - } - - validationError = AFErrorWithUnderlyingError([NSError errorWithDomain:AFURLResponseSerializationErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:mutableUserInfo], validationError); - } - - responseIsValid = NO; - } - - if (self.acceptableStatusCodes && ![self.acceptableStatusCodes containsIndex:(NSUInteger)response.statusCode]) { - NSMutableDictionary *mutableUserInfo = [@{ - NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Request failed: %@ (%ld)", @"AFNetworking", nil), [NSHTTPURLResponse localizedStringForStatusCode:response.statusCode], (long)response.statusCode], - NSURLErrorFailingURLErrorKey:[response URL], - AFNetworkingOperationFailingURLResponseErrorKey: response, - } mutableCopy]; - - if (data) { - mutableUserInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] = data; - } - - validationError = AFErrorWithUnderlyingError([NSError errorWithDomain:AFURLResponseSerializationErrorDomain code:NSURLErrorBadServerResponse userInfo:mutableUserInfo], validationError); - - responseIsValid = NO; - } - } - - if (error && !responseIsValid) { - *error = validationError; - } - - return responseIsValid; -} - -#pragma mark - AFURLResponseSerialization - -- (id)responseObjectForResponse:(NSURLResponse *)response - data:(NSData *)data - error:(NSError *__autoreleasing *)error -{ - [self validateResponse:(NSHTTPURLResponse *)response data:data error:error]; - - return data; -} - -#pragma mark - NSSecureCoding - -+ (BOOL)supportsSecureCoding { - return YES; -} - -- (id)initWithCoder:(NSCoder *)decoder { - self = [self init]; - if (!self) { - return nil; - } - - self.acceptableStatusCodes = [decoder decodeObjectOfClass:[NSIndexSet class] forKey:NSStringFromSelector(@selector(acceptableStatusCodes))]; - self.acceptableContentTypes = [decoder decodeObjectOfClass:[NSIndexSet class] forKey:NSStringFromSelector(@selector(acceptableContentTypes))]; - - return self; -} - -- (void)encodeWithCoder:(NSCoder *)coder { - [coder encodeObject:self.acceptableStatusCodes forKey:NSStringFromSelector(@selector(acceptableStatusCodes))]; - [coder encodeObject:self.acceptableContentTypes forKey:NSStringFromSelector(@selector(acceptableContentTypes))]; -} - -#pragma mark - NSCopying - -- (id)copyWithZone:(NSZone *)zone { - AFHTTPResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; - serializer.acceptableStatusCodes = [self.acceptableStatusCodes copyWithZone:zone]; - serializer.acceptableContentTypes = [self.acceptableContentTypes copyWithZone:zone]; - - return serializer; -} - -@end - -#pragma mark - - -@implementation AFJSONResponseSerializer - -+ (instancetype)serializer { - return [self serializerWithReadingOptions:(NSJSONReadingOptions)0]; -} - -+ (instancetype)serializerWithReadingOptions:(NSJSONReadingOptions)readingOptions { - AFJSONResponseSerializer *serializer = [[self alloc] init]; - serializer.readingOptions = readingOptions; - - return serializer; -} - -- (instancetype)init { - self = [super init]; - if (!self) { - return nil; - } - - self.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", nil]; - - return self; -} - -#pragma mark - AFURLResponseSerialization - -- (id)responseObjectForResponse:(NSURLResponse *)response - data:(NSData *)data - error:(NSError *__autoreleasing *)error -{ - if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) { - if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) { - return nil; - } - } - - // 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. - // See https://github.com/rails/rails/issues/1742 - NSStringEncoding stringEncoding = self.stringEncoding; - if (response.textEncodingName) { - CFStringEncoding encoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)response.textEncodingName); - if (encoding != kCFStringEncodingInvalidId) { - stringEncoding = CFStringConvertEncodingToNSStringEncoding(encoding); - } - } - - id responseObject = nil; - NSError *serializationError = nil; - @autoreleasepool { - NSString *responseString = [[NSString alloc] initWithData:data encoding:stringEncoding]; - if (responseString && ![responseString isEqualToString:@" "]) { - // Workaround for a bug in NSJSONSerialization when Unicode character escape codes are used instead of the actual character - // See http://stackoverflow.com/a/12843465/157142 - data = [responseString dataUsingEncoding:NSUTF8StringEncoding]; - - if (data) { - if ([data length] > 0) { - responseObject = [NSJSONSerialization JSONObjectWithData:data options:self.readingOptions error:&serializationError]; - } else { - return nil; - } - } else { - NSDictionary *userInfo = @{ - NSLocalizedDescriptionKey: NSLocalizedStringFromTable(@"Data failed decoding as a UTF-8 string", @"AFNetworking", nil), - NSLocalizedFailureReasonErrorKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Could not decode string: %@", @"AFNetworking", nil), responseString] - }; - - serializationError = [NSError errorWithDomain:AFURLResponseSerializationErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:userInfo]; - } - } - } - - if (self.removesKeysWithNullValues && responseObject) { - responseObject = AFJSONObjectByRemovingKeysWithNullValues(responseObject, self.readingOptions); - } - - if (error) { - *error = AFErrorWithUnderlyingError(serializationError, *error); - } - - return responseObject; -} - -#pragma mark - NSSecureCoding - -- (id)initWithCoder:(NSCoder *)decoder { - self = [super initWithCoder:decoder]; - if (!self) { - return nil; - } - - self.readingOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(readingOptions))] unsignedIntegerValue]; - self.removesKeysWithNullValues = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(removesKeysWithNullValues))] boolValue]; - - return self; -} - -- (void)encodeWithCoder:(NSCoder *)coder { - [super encodeWithCoder:coder]; - - [coder encodeObject:@(self.readingOptions) forKey:NSStringFromSelector(@selector(readingOptions))]; - [coder encodeObject:@(self.removesKeysWithNullValues) forKey:NSStringFromSelector(@selector(removesKeysWithNullValues))]; -} - -#pragma mark - NSCopying - -- (id)copyWithZone:(NSZone *)zone { - AFJSONResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; - serializer.readingOptions = self.readingOptions; - serializer.removesKeysWithNullValues = self.removesKeysWithNullValues; - - return serializer; -} - -@end - -#pragma mark - - -@implementation AFXMLParserResponseSerializer - -+ (instancetype)serializer { - AFXMLParserResponseSerializer *serializer = [[self alloc] init]; - - return serializer; -} - -- (instancetype)init { - self = [super init]; - if (!self) { - return nil; - } - - self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/xml", @"text/xml", nil]; - - return self; -} - -#pragma mark - AFURLResponseSerialization - -- (id)responseObjectForResponse:(NSHTTPURLResponse *)response - data:(NSData *)data - error:(NSError *__autoreleasing *)error -{ - if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) { - if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) { - return nil; - } - } - - return [[NSXMLParser alloc] initWithData:data]; -} - -@end - -#pragma mark - - -#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED - -@implementation AFXMLDocumentResponseSerializer - -+ (instancetype)serializer { - return [self serializerWithXMLDocumentOptions:0]; -} - -+ (instancetype)serializerWithXMLDocumentOptions:(NSUInteger)mask { - AFXMLDocumentResponseSerializer *serializer = [[self alloc] init]; - serializer.options = mask; - - return serializer; -} - -- (instancetype)init { - self = [super init]; - if (!self) { - return nil; - } - - self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/xml", @"text/xml", nil]; - - return self; -} - -#pragma mark - AFURLResponseSerialization - -- (id)responseObjectForResponse:(NSURLResponse *)response - data:(NSData *)data - error:(NSError *__autoreleasing *)error -{ - if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) { - if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) { - return nil; - } - } - - NSError *serializationError = nil; - NSXMLDocument *document = [[NSXMLDocument alloc] initWithData:data options:self.options error:&serializationError]; - - if (error) { - *error = AFErrorWithUnderlyingError(serializationError, *error); - } - - return document; -} - -#pragma mark - NSSecureCoding - -- (id)initWithCoder:(NSCoder *)decoder { - self = [super initWithCoder:decoder]; - if (!self) { - return nil; - } - - self.options = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(options))] unsignedIntegerValue]; - - return self; -} - -- (void)encodeWithCoder:(NSCoder *)coder { - [super encodeWithCoder:coder]; - - [coder encodeObject:@(self.options) forKey:NSStringFromSelector(@selector(options))]; -} - -#pragma mark - NSCopying - -- (id)copyWithZone:(NSZone *)zone { - AFXMLDocumentResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; - serializer.options = self.options; - - return serializer; -} - -@end - -#endif - -#pragma mark - - -@implementation AFPropertyListResponseSerializer - -+ (instancetype)serializer { - return [self serializerWithFormat:NSPropertyListXMLFormat_v1_0 readOptions:0]; -} - -+ (instancetype)serializerWithFormat:(NSPropertyListFormat)format - readOptions:(NSPropertyListReadOptions)readOptions -{ - AFPropertyListResponseSerializer *serializer = [[self alloc] init]; - serializer.format = format; - serializer.readOptions = readOptions; - - return serializer; -} - -- (instancetype)init { - self = [super init]; - if (!self) { - return nil; - } - - self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/x-plist", nil]; - - return self; -} - -#pragma mark - AFURLResponseSerialization - -- (id)responseObjectForResponse:(NSURLResponse *)response - data:(NSData *)data - error:(NSError *__autoreleasing *)error -{ - if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) { - if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) { - return nil; - } - } - - id responseObject; - NSError *serializationError = nil; - - if (data) { - responseObject = [NSPropertyListSerialization propertyListWithData:data options:self.readOptions format:NULL error:&serializationError]; - } - - if (error) { - *error = AFErrorWithUnderlyingError(serializationError, *error); - } - - return responseObject; -} - -#pragma mark - NSSecureCoding - -- (id)initWithCoder:(NSCoder *)decoder { - self = [super initWithCoder:decoder]; - if (!self) { - return nil; - } - - self.format = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(format))] unsignedIntegerValue]; - self.readOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(readOptions))] unsignedIntegerValue]; - - return self; -} - -- (void)encodeWithCoder:(NSCoder *)coder { - [super encodeWithCoder:coder]; - - [coder encodeObject:@(self.format) forKey:NSStringFromSelector(@selector(format))]; - [coder encodeObject:@(self.readOptions) forKey:NSStringFromSelector(@selector(readOptions))]; -} - -#pragma mark - NSCopying - -- (id)copyWithZone:(NSZone *)zone { - AFPropertyListResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; - serializer.format = self.format; - serializer.readOptions = self.readOptions; - - return serializer; -} - -@end - -#pragma mark - - -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) -#import <CoreGraphics/CoreGraphics.h> - -static UIImage * AFImageWithDataAtScale(NSData *data, CGFloat scale) { - UIImage *image = [[UIImage alloc] initWithData:data]; - - return [[UIImage alloc] initWithCGImage:[image CGImage] scale:scale orientation:image.imageOrientation]; -} - -static UIImage * AFInflatedImageFromResponseWithDataAtScale(NSHTTPURLResponse *response, NSData *data, CGFloat scale) { - if (!data || [data length] == 0) { - return nil; - } - - CGImageRef imageRef = NULL; - CGDataProviderRef dataProvider = CGDataProviderCreateWithCFData((__bridge CFDataRef)data); - - if ([response.MIMEType isEqualToString:@"image/png"]) { - imageRef = CGImageCreateWithPNGDataProvider(dataProvider, NULL, true, kCGRenderingIntentDefault); - } else if ([response.MIMEType isEqualToString:@"image/jpeg"]) { - imageRef = CGImageCreateWithJPEGDataProvider(dataProvider, NULL, true, kCGRenderingIntentDefault); - - // CGImageCreateWithJPEGDataProvider does not properly handle CMKY, so if so, fall back to AFImageWithDataAtScale - if (imageRef) { - CGColorSpaceRef imageColorSpace = CGImageGetColorSpace(imageRef); - CGColorSpaceModel imageColorSpaceModel = CGColorSpaceGetModel(imageColorSpace); - if (imageColorSpaceModel == kCGColorSpaceModelCMYK) { - CGImageRelease(imageRef); - imageRef = NULL; - } - } - } - - CGDataProviderRelease(dataProvider); - - UIImage *image = AFImageWithDataAtScale(data, scale); - if (!imageRef) { - if (image.images || !image) { - return image; - } - - imageRef = CGImageCreateCopy([image CGImage]); - if (!imageRef) { - return nil; - } - } - - size_t width = CGImageGetWidth(imageRef); - size_t height = CGImageGetHeight(imageRef); - size_t bitsPerComponent = CGImageGetBitsPerComponent(imageRef); - - if (width * height > 1024 * 1024 || bitsPerComponent > 8) { - CGImageRelease(imageRef); - - return image; - } - - size_t bytesPerRow = 0; // CGImageGetBytesPerRow() calculates incorrectly in iOS 5.0, so defer to CGBitmapContextCreate - CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); - CGColorSpaceModel colorSpaceModel = CGColorSpaceGetModel(colorSpace); - CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef); - - if (colorSpaceModel == kCGColorSpaceModelRGB) { - uint32_t alpha = (bitmapInfo & kCGBitmapAlphaInfoMask); -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wassign-enum" - if (alpha == kCGImageAlphaNone) { - bitmapInfo &= ~kCGBitmapAlphaInfoMask; - bitmapInfo |= kCGImageAlphaNoneSkipFirst; - } else if (!(alpha == kCGImageAlphaNoneSkipFirst || alpha == kCGImageAlphaNoneSkipLast)) { - bitmapInfo &= ~kCGBitmapAlphaInfoMask; - bitmapInfo |= kCGImageAlphaPremultipliedFirst; - } -#pragma clang diagnostic pop - } - - CGContextRef context = CGBitmapContextCreate(NULL, width, height, bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo); - - CGColorSpaceRelease(colorSpace); - - if (!context) { - CGImageRelease(imageRef); - - return image; - } - - CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, width, height), imageRef); - CGImageRef inflatedImageRef = CGBitmapContextCreateImage(context); - - CGContextRelease(context); - - UIImage *inflatedImage = [[UIImage alloc] initWithCGImage:inflatedImageRef scale:scale orientation:image.imageOrientation]; - - CGImageRelease(inflatedImageRef); - CGImageRelease(imageRef); - - return inflatedImage; -} -#endif - - -@implementation AFImageResponseSerializer - -- (instancetype)init { - self = [super init]; - if (!self) { - return nil; - } - - 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]; - -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) - self.imageScale = [[UIScreen mainScreen] scale]; - self.automaticallyInflatesResponseImage = YES; -#endif - - return self; -} - -#pragma mark - AFURLResponseSerializer - -- (id)responseObjectForResponse:(NSURLResponse *)response - data:(NSData *)data - error:(NSError *__autoreleasing *)error -{ - if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) { - if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) { - return nil; - } - } - -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) - if (self.automaticallyInflatesResponseImage) { - return AFInflatedImageFromResponseWithDataAtScale((NSHTTPURLResponse *)response, data, self.imageScale); - } else { - return AFImageWithDataAtScale(data, self.imageScale); - } -#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED) - // Ensure that the image is set to it's correct pixel width and height - NSBitmapImageRep *bitimage = [[NSBitmapImageRep alloc] initWithData:data]; - NSImage *image = [[NSImage alloc] initWithSize:NSMakeSize([bitimage pixelsWide], [bitimage pixelsHigh])]; - [image addRepresentation:bitimage]; - - return image; -#endif - - return nil; -} - -#pragma mark - NSSecureCoding - -- (id)initWithCoder:(NSCoder *)decoder { - self = [super initWithCoder:decoder]; - if (!self) { - return nil; - } - -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) - NSNumber *imageScale = [decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(imageScale))]; -#if CGFLOAT_IS_DOUBLE - self.imageScale = [imageScale doubleValue]; -#else - self.imageScale = [imageScale floatValue]; -#endif - - self.automaticallyInflatesResponseImage = [decoder decodeBoolForKey:NSStringFromSelector(@selector(automaticallyInflatesResponseImage))]; -#endif - - return self; -} - -- (void)encodeWithCoder:(NSCoder *)coder { - [super encodeWithCoder:coder]; - -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) - [coder encodeObject:@(self.imageScale) forKey:NSStringFromSelector(@selector(imageScale))]; - [coder encodeBool:self.automaticallyInflatesResponseImage forKey:NSStringFromSelector(@selector(automaticallyInflatesResponseImage))]; -#endif -} - -#pragma mark - NSCopying - -- (id)copyWithZone:(NSZone *)zone { - AFImageResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; - -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) - serializer.imageScale = self.imageScale; - serializer.automaticallyInflatesResponseImage = self.automaticallyInflatesResponseImage; -#endif - - return serializer; -} - -@end - -#pragma mark - - -@interface AFCompoundResponseSerializer () -@property (readwrite, nonatomic, copy) NSArray *responseSerializers; -@end - -@implementation AFCompoundResponseSerializer - -+ (instancetype)compoundSerializerWithResponseSerializers:(NSArray *)responseSerializers { - AFCompoundResponseSerializer *serializer = [[self alloc] init]; - serializer.responseSerializers = responseSerializers; - - return serializer; -} - -#pragma mark - AFURLResponseSerialization - -- (id)responseObjectForResponse:(NSURLResponse *)response - data:(NSData *)data - error:(NSError *__autoreleasing *)error -{ - for (id <AFURLResponseSerialization> serializer in self.responseSerializers) { - if (![serializer isKindOfClass:[AFHTTPResponseSerializer class]]) { - continue; - } - - NSError *serializerError = nil; - id responseObject = [serializer responseObjectForResponse:response data:data error:&serializerError]; - if (responseObject) { - if (error) { - *error = AFErrorWithUnderlyingError(serializerError, *error); - } - - return responseObject; - } - } - - return [super responseObjectForResponse:response data:data error:error]; -} - -#pragma mark - NSSecureCoding - -- (id)initWithCoder:(NSCoder *)decoder { - self = [super initWithCoder:decoder]; - if (!self) { - return nil; - } - - self.responseSerializers = [decoder decodeObjectOfClass:[NSArray class] forKey:NSStringFromSelector(@selector(responseSerializers))]; - - return self; -} - -- (void)encodeWithCoder:(NSCoder *)coder { - [super encodeWithCoder:coder]; - - [coder encodeObject:self.responseSerializers forKey:NSStringFromSelector(@selector(responseSerializers))]; -} - -#pragma mark - NSCopying - -- (id)copyWithZone:(NSZone *)zone { - AFCompoundResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; - serializer.responseSerializers = self.responseSerializers; - - return serializer; -} - -@end diff --git a/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFURLSessionManager.h b/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFURLSessionManager.h deleted file mode 100644 index 0b1fa078..00000000 --- a/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFURLSessionManager.h +++ /dev/null @@ -1,529 +0,0 @@ -// AFURLSessionManager.h -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import <Foundation/Foundation.h> - -#import "AFURLResponseSerialization.h" -#import "AFURLRequestSerialization.h" -#import "AFSecurityPolicy.h" -#import "AFNetworkReachabilityManager.h" - -/** - `AFURLSessionManager` creates and manages an `NSURLSession` object based on a specified `NSURLSessionConfiguration` object, which conforms to `<NSURLSessionTaskDelegate>`, `<NSURLSessionDataDelegate>`, `<NSURLSessionDownloadDelegate>`, and `<NSURLSessionDelegate>`. - - ## Subclassing Notes - - 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. - - ## NSURLSession & NSURLSessionTask Delegate Methods - - `AFURLSessionManager` implements the following delegate methods: - - ### `NSURLSessionDelegate` - - - `URLSession:didBecomeInvalidWithError:` - - `URLSession:didReceiveChallenge:completionHandler:` - - `URLSessionDidFinishEventsForBackgroundURLSession:` - - ### `NSURLSessionTaskDelegate` - - - `URLSession:willPerformHTTPRedirection:newRequest:completionHandler:` - - `URLSession:task:didReceiveChallenge:completionHandler:` - - `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:` - - `URLSession:task:didCompleteWithError:` - - ### `NSURLSessionDataDelegate` - - - `URLSession:dataTask:didReceiveResponse:completionHandler:` - - `URLSession:dataTask:didBecomeDownloadTask:` - - `URLSession:dataTask:didReceiveData:` - - `URLSession:dataTask:willCacheResponse:completionHandler:` - - ### `NSURLSessionDownloadDelegate` - - - `URLSession:downloadTask:didFinishDownloadingToURL:` - - `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesWritten:totalBytesExpectedToWrite:` - - `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:` - - If any of these methods are overridden in a subclass, they _must_ call the `super` implementation first. - - ## Network Reachability Monitoring - - 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. - - ## NSCoding Caveats - - - Encoded managers do not include any block properties. Be sure to set delegate callback blocks when using `-initWithCoder:` or `NSKeyedUnarchiver`. - - ## NSCopying Caveats - - - `-copy` and `-copyWithZone:` return a new manager with a new `NSURLSession` created from the configuration of the original. - - 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. - */ - -#if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000) || (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1090) - -@interface AFURLSessionManager : NSObject <NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate, NSSecureCoding, NSCopying> - -/** - The managed session. - */ -@property (readonly, nonatomic, strong) NSURLSession *session; - -/** - The operation queue on which delegate callbacks are run. - */ -@property (readonly, nonatomic, strong) NSOperationQueue *operationQueue; - -/** - 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`. - - @warning `responseSerializer` must not be `nil`. - */ -@property (nonatomic, strong) id <AFURLResponseSerialization> responseSerializer; - -///------------------------------- -/// @name Managing Security Policy -///------------------------------- - -/** - The security policy used by created request operations to evaluate server trust for secure connections. `AFURLSessionManager` uses the `defaultPolicy` unless otherwise specified. - */ -@property (nonatomic, strong) AFSecurityPolicy *securityPolicy; - -///-------------------------------------- -/// @name Monitoring Network Reachability -///-------------------------------------- - -/** - The network reachability manager. `AFURLSessionManager` uses the `sharedManager` by default. - */ -@property (readwrite, nonatomic, strong) AFNetworkReachabilityManager *reachabilityManager; - -///---------------------------- -/// @name Getting Session Tasks -///---------------------------- - -/** - The data, upload, and download tasks currently run by the managed session. - */ -@property (readonly, nonatomic, strong) NSArray *tasks; - -/** - The data tasks currently run by the managed session. - */ -@property (readonly, nonatomic, strong) NSArray *dataTasks; - -/** - The upload tasks currently run by the managed session. - */ -@property (readonly, nonatomic, strong) NSArray *uploadTasks; - -/** - The download tasks currently run by the managed session. - */ -@property (readonly, nonatomic, strong) NSArray *downloadTasks; - -///------------------------------- -/// @name Managing Callback Queues -///------------------------------- - -/** - The dispatch queue for `completionBlock`. If `NULL` (default), the main queue is used. - */ -@property (nonatomic, strong) dispatch_queue_t completionQueue; - -/** - The dispatch group for `completionBlock`. If `NULL` (default), a private dispatch group is used. - */ -@property (nonatomic, strong) dispatch_group_t completionGroup; - -///--------------------------------- -/// @name Working Around System Bugs -///--------------------------------- - -/** - Whether to attempt to retry creation of upload tasks for background sessions when initial call returns `nil`. `NO` by default. - - @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. - - @see https://github.com/AFNetworking/AFNetworking/issues/1675 - */ -@property (nonatomic, assign) BOOL attemptsToRecreateUploadTasksForBackgroundSessions; - -///--------------------- -/// @name Initialization -///--------------------- - -/** - Creates and returns a manager for a session created with the specified configuration. This is the designated initializer. - - @param configuration The configuration used to create the managed session. - - @return A manager for a newly-created session. - */ -- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration; - -/** - Invalidates the managed session, optionally canceling pending tasks. - - @param cancelPendingTasks Whether or not to cancel pending tasks. - */ -- (void)invalidateSessionCancelingTasks:(BOOL)cancelPendingTasks; - -///------------------------- -/// @name Running Data Tasks -///------------------------- - -/** - Creates an `NSURLSessionDataTask` with the specified request. - - @param request The HTTP request for the request. - @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. - */ -- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request - completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler; - -///--------------------------- -/// @name Running Upload Tasks -///--------------------------- - -/** - Creates an `NSURLSessionUploadTask` with the specified request for a local file. - - @param request The HTTP request for the request. - @param fileURL A URL to the local file to be uploaded. - @param progress A progress object monitoring the current upload progress. - @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. - - @see `attemptsToRecreateUploadTasksForBackgroundSessions` - */ -- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request - fromFile:(NSURL *)fileURL - progress:(NSProgress * __autoreleasing *)progress - completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler; - -/** - Creates an `NSURLSessionUploadTask` with the specified request for an HTTP body. - - @param request The HTTP request for the request. - @param bodyData A data object containing the HTTP body to be uploaded. - @param progress A progress object monitoring the current upload progress. - @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. - */ -- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request - fromData:(NSData *)bodyData - progress:(NSProgress * __autoreleasing *)progress - completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler; - -/** - Creates an `NSURLSessionUploadTask` with the specified streaming request. - - @param request The HTTP request for the request. - @param progress A progress object monitoring the current upload progress. - @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. - */ -- (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)request - progress:(NSProgress * __autoreleasing *)progress - completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler; - -///----------------------------- -/// @name Running Download Tasks -///----------------------------- - -/** - Creates an `NSURLSessionDownloadTask` with the specified request. - - @param request The HTTP request for the request. - @param progress A progress object monitoring the current download progress. - @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. - @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. - - @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. - */ -- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request - progress:(NSProgress * __autoreleasing *)progress - destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination - completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler; - -/** - Creates an `NSURLSessionDownloadTask` with the specified resume data. - - @param resumeData The data used to resume downloading. - @param progress A progress object monitoring the current download progress. - @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. - @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. - */ -- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData - progress:(NSProgress * __autoreleasing *)progress - destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination - completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler; - -///--------------------------------- -/// @name Getting Progress for Tasks -///--------------------------------- - -/** - Returns the upload progress of the specified task. - - @param uploadTask The session upload task. Must not be `nil`. - - @return An `NSProgress` object reporting the upload progress of a task, or `nil` if the progress is unavailable. - */ -- (NSProgress *)uploadProgressForTask:(NSURLSessionUploadTask *)uploadTask; - -/** - Returns the download progress of the specified task. - - @param downloadTask The session download task. Must not be `nil`. - - @return An `NSProgress` object reporting the download progress of a task, or `nil` if the progress is unavailable. - */ -- (NSProgress *)downloadProgressForTask:(NSURLSessionDownloadTask *)downloadTask; - -///----------------------------------------- -/// @name Setting Session Delegate Callbacks -///----------------------------------------- - -/** - Sets a block to be executed when the managed session becomes invalid, as handled by the `NSURLSessionDelegate` method `URLSession:didBecomeInvalidWithError:`. - - @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. - */ -- (void)setSessionDidBecomeInvalidBlock:(void (^)(NSURLSession *session, NSError *error))block; - -/** - Sets a block to be executed when a connection level authentication challenge has occurred, as handled by the `NSURLSessionDelegate` method `URLSession:didReceiveChallenge:completionHandler:`. - - @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. - */ -- (void)setSessionDidReceiveAuthenticationChallengeBlock:(NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential))block; - -///-------------------------------------- -/// @name Setting Task Delegate Callbacks -///-------------------------------------- - -/** - 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:`. - - @param block A block object to be executed when a task requires a new request body stream. - */ -- (void)setTaskNeedNewBodyStreamBlock:(NSInputStream * (^)(NSURLSession *session, NSURLSessionTask *task))block; - -/** - 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:`. - - @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. - */ -- (void)setTaskWillPerformHTTPRedirectionBlock:(NSURLRequest * (^)(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request))block; - -/** - 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:`. - - @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. - */ -- (void)setTaskDidReceiveAuthenticationChallengeBlock:(NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential))block; - -/** - Sets a block to be executed periodically to track upload progress, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`. - - @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. - */ -- (void)setTaskDidSendBodyDataBlock:(void (^)(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend))block; - -/** - Sets a block to be executed as the last message related to a specific task, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didCompleteWithError:`. - - @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. - */ -- (void)setTaskDidCompleteBlock:(void (^)(NSURLSession *session, NSURLSessionTask *task, NSError *error))block; - -///------------------------------------------- -/// @name Setting Data Task Delegate Callbacks -///------------------------------------------- - -/** - Sets a block to be executed when a data task has received a response, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didReceiveResponse:completionHandler:`. - - @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. - */ -- (void)setDataTaskDidReceiveResponseBlock:(NSURLSessionResponseDisposition (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response))block; - -/** - Sets a block to be executed when a data task has become a download task, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didBecomeDownloadTask:`. - - @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. - */ -- (void)setDataTaskDidBecomeDownloadTaskBlock:(void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask))block; - -/** - Sets a block to be executed when a data task receives data, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didReceiveData:`. - - @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. - */ -- (void)setDataTaskDidReceiveDataBlock:(void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data))block; - -/** - 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:`. - - @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. - */ -- (void)setDataTaskWillCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSCachedURLResponse *proposedResponse))block; - -/** - Sets a block to be executed once all messages enqueued for a session have been delivered, as handled by the `NSURLSessionDataDelegate` method `URLSessionDidFinishEventsForBackgroundURLSession:`. - - @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. - */ -- (void)setDidFinishEventsForBackgroundURLSessionBlock:(void (^)(NSURLSession *session))block; - -///----------------------------------------------- -/// @name Setting Download Task Delegate Callbacks -///----------------------------------------------- - -/** - Sets a block to be executed when a download task has completed a download, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didFinishDownloadingToURL:`. - - @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. - */ -- (void)setDownloadTaskDidFinishDownloadingBlock:(NSURL * (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location))block; - -/** - Sets a block to be executed periodically to track download progress, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesWritten:totalBytesExpectedToWrite:`. - - @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. - */ -- (void)setDownloadTaskDidWriteDataBlock:(void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite))block; - -/** - Sets a block to be executed when a download task has been resumed, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:`. - - @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. - */ -- (void)setDownloadTaskDidResumeBlock:(void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes))block; - -@end - -#endif - -///-------------------- -/// @name Notifications -///-------------------- - -/** - Posted when a task begins executing. - - @deprecated Use `AFNetworkingTaskDidResumeNotification` instead. - */ -extern NSString * const AFNetworkingTaskDidStartNotification DEPRECATED_ATTRIBUTE; - -/** - Posted when a task resumes. - */ -extern NSString * const AFNetworkingTaskDidResumeNotification; - -/** - Posted when a task finishes executing. Includes a userInfo dictionary with additional information about the task. - - @deprecated Use `AFNetworkingTaskDidCompleteNotification` instead. - */ -extern NSString * const AFNetworkingTaskDidFinishNotification DEPRECATED_ATTRIBUTE; - -/** - Posted when a task finishes executing. Includes a userInfo dictionary with additional information about the task. - */ -extern NSString * const AFNetworkingTaskDidCompleteNotification; - -/** - Posted when a task suspends its execution. - */ -extern NSString * const AFNetworkingTaskDidSuspendNotification; - -/** - Posted when a session is invalidated. - */ -extern NSString * const AFURLSessionDidInvalidateNotification; - -/** - Posted when a session download task encountered an error when moving the temporary download file to a specified destination. - */ -extern NSString * const AFURLSessionDownloadTaskDidFailToMoveFileNotification; - -/** - The raw response data of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if response data exists for the task. - - @deprecated Use `AFNetworkingTaskDidCompleteResponseDataKey` instead. - */ -extern NSString * const AFNetworkingTaskDidFinishResponseDataKey DEPRECATED_ATTRIBUTE; - -/** - The raw response data of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if response data exists for the task. - */ -extern NSString * const AFNetworkingTaskDidCompleteResponseDataKey; - -/** - The serialized response object of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if the response was serialized. - - @deprecated Use `AFNetworkingTaskDidCompleteSerializedResponseKey` instead. - */ -extern NSString * const AFNetworkingTaskDidFinishSerializedResponseKey DEPRECATED_ATTRIBUTE; - -/** - The serialized response object of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if the response was serialized. - */ -extern NSString * const AFNetworkingTaskDidCompleteSerializedResponseKey; - -/** - The response serializer used to serialize the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if the task has an associated response serializer. - - @deprecated Use `AFNetworkingTaskDidCompleteResponseSerializerKey` instead. - */ -extern NSString * const AFNetworkingTaskDidFinishResponseSerializerKey DEPRECATED_ATTRIBUTE; - -/** - The response serializer used to serialize the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if the task has an associated response serializer. - */ -extern NSString * const AFNetworkingTaskDidCompleteResponseSerializerKey; - -/** - The file path associated with the download task. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if an the response data has been stored directly to disk. - - @deprecated Use `AFNetworkingTaskDidCompleteAssetPathKey` instead. - */ -extern NSString * const AFNetworkingTaskDidFinishAssetPathKey DEPRECATED_ATTRIBUTE; - -/** - The file path associated with the download task. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if an the response data has been stored directly to disk. - */ -extern NSString * const AFNetworkingTaskDidCompleteAssetPathKey; - -/** - Any error associated with the task, or the serialization of the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if an error exists. - - @deprecated Use `AFNetworkingTaskDidCompleteErrorKey` instead. - */ -extern NSString * const AFNetworkingTaskDidFinishErrorKey DEPRECATED_ATTRIBUTE; - -/** - Any error associated with the task, or the serialization of the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if an error exists. - */ -extern NSString * const AFNetworkingTaskDidCompleteErrorKey; diff --git a/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFURLSessionManager.m b/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFURLSessionManager.m deleted file mode 100644 index 0775c4da..00000000 --- a/plugins/com.synconset.cordovaHTTP/src/ios/AFNetworking/AFURLSessionManager.m +++ /dev/null @@ -1,1036 +0,0 @@ -// AFURLSessionManager.m -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import "AFURLSessionManager.h" - -#if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000) || (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1090) - -static dispatch_queue_t url_session_manager_creation_queue() { - static dispatch_queue_t af_url_session_manager_creation_queue; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - af_url_session_manager_creation_queue = dispatch_queue_create("com.alamofire.networking.session.manager.creation", DISPATCH_QUEUE_SERIAL); - }); - - return af_url_session_manager_creation_queue; -} - -static dispatch_queue_t url_session_manager_processing_queue() { - static dispatch_queue_t af_url_session_manager_processing_queue; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - af_url_session_manager_processing_queue = dispatch_queue_create("com.alamofire.networking.session.manager.processing", DISPATCH_QUEUE_CONCURRENT); - }); - - return af_url_session_manager_processing_queue; -} - -static dispatch_group_t url_session_manager_completion_group() { - static dispatch_group_t af_url_session_manager_completion_group; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - af_url_session_manager_completion_group = dispatch_group_create(); - }); - - return af_url_session_manager_completion_group; -} - -NSString * const AFNetworkingTaskDidResumeNotification = @"com.alamofire.networking.task.resume"; -NSString * const AFNetworkingTaskDidCompleteNotification = @"com.alamofire.networking.task.complete"; -NSString * const AFNetworkingTaskDidSuspendNotification = @"com.alamofire.networking.task.suspend"; -NSString * const AFURLSessionDidInvalidateNotification = @"com.alamofire.networking.session.invalidate"; -NSString * const AFURLSessionDownloadTaskDidFailToMoveFileNotification = @"com.alamofire.networking.session.download.file-manager-error"; - -NSString * const AFNetworkingTaskDidStartNotification = @"com.alamofire.networking.task.resume"; // Deprecated -NSString * const AFNetworkingTaskDidFinishNotification = @"com.alamofire.networking.task.complete"; // Deprecated - -NSString * const AFNetworkingTaskDidCompleteSerializedResponseKey = @"com.alamofire.networking.task.complete.serializedresponse"; -NSString * const AFNetworkingTaskDidCompleteResponseSerializerKey = @"com.alamofire.networking.task.complete.responseserializer"; -NSString * const AFNetworkingTaskDidCompleteResponseDataKey = @"com.alamofire.networking.complete.finish.responsedata"; -NSString * const AFNetworkingTaskDidCompleteErrorKey = @"com.alamofire.networking.task.complete.error"; -NSString * const AFNetworkingTaskDidCompleteAssetPathKey = @"com.alamofire.networking.task.complete.assetpath"; - -NSString * const AFNetworkingTaskDidFinishSerializedResponseKey = @"com.alamofire.networking.task.complete.serializedresponse"; // Deprecated -NSString * const AFNetworkingTaskDidFinishResponseSerializerKey = @"com.alamofire.networking.task.complete.responseserializer"; // Deprecated -NSString * const AFNetworkingTaskDidFinishResponseDataKey = @"com.alamofire.networking.complete.finish.responsedata"; // Deprecated -NSString * const AFNetworkingTaskDidFinishErrorKey = @"com.alamofire.networking.task.complete.error"; // Deprecated -NSString * const AFNetworkingTaskDidFinishAssetPathKey = @"com.alamofire.networking.task.complete.assetpath"; // Deprecated - -static NSString * const AFURLSessionManagerLockName = @"com.alamofire.networking.session.manager.lock"; - -static NSUInteger const AFMaximumNumberOfAttemptsToRecreateBackgroundSessionUploadTask = 3; - -static void * AFTaskStateChangedContext = &AFTaskStateChangedContext; - -typedef void (^AFURLSessionDidBecomeInvalidBlock)(NSURLSession *session, NSError *error); -typedef NSURLSessionAuthChallengeDisposition (^AFURLSessionDidReceiveAuthenticationChallengeBlock)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential); - -typedef NSURLRequest * (^AFURLSessionTaskWillPerformHTTPRedirectionBlock)(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request); -typedef NSURLSessionAuthChallengeDisposition (^AFURLSessionTaskDidReceiveAuthenticationChallengeBlock)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential); -typedef void (^AFURLSessionDidFinishEventsForBackgroundURLSessionBlock)(NSURLSession *session); - -typedef NSInputStream * (^AFURLSessionTaskNeedNewBodyStreamBlock)(NSURLSession *session, NSURLSessionTask *task); -typedef void (^AFURLSessionTaskDidSendBodyDataBlock)(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend); -typedef void (^AFURLSessionTaskDidCompleteBlock)(NSURLSession *session, NSURLSessionTask *task, NSError *error); - -typedef NSURLSessionResponseDisposition (^AFURLSessionDataTaskDidReceiveResponseBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response); -typedef void (^AFURLSessionDataTaskDidBecomeDownloadTaskBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask); -typedef void (^AFURLSessionDataTaskDidReceiveDataBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data); -typedef NSCachedURLResponse * (^AFURLSessionDataTaskWillCacheResponseBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSCachedURLResponse *proposedResponse); - -typedef NSURL * (^AFURLSessionDownloadTaskDidFinishDownloadingBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location); -typedef void (^AFURLSessionDownloadTaskDidWriteDataBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite); -typedef void (^AFURLSessionDownloadTaskDidResumeBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes); - -typedef void (^AFURLSessionTaskCompletionHandler)(NSURLResponse *response, id responseObject, NSError *error); - -#pragma mark - - -@interface AFURLSessionManagerTaskDelegate : NSObject <NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate> -@property (nonatomic, weak) AFURLSessionManager *manager; -@property (nonatomic, strong) NSMutableData *mutableData; -@property (nonatomic, strong) NSProgress *progress; -@property (nonatomic, copy) NSURL *downloadFileURL; -@property (nonatomic, copy) AFURLSessionDownloadTaskDidFinishDownloadingBlock downloadTaskDidFinishDownloading; -@property (nonatomic, copy) AFURLSessionTaskCompletionHandler completionHandler; -@end - -@implementation AFURLSessionManagerTaskDelegate - -- (instancetype)init { - self = [super init]; - if (!self) { - return nil; - } - - self.mutableData = [NSMutableData data]; - - self.progress = [NSProgress progressWithTotalUnitCount:0]; - - return self; -} - -#pragma mark - NSURLSessionTaskDelegate - -- (void)URLSession:(__unused NSURLSession *)session - task:(__unused NSURLSessionTask *)task - didSendBodyData:(__unused int64_t)bytesSent - totalBytesSent:(int64_t)totalBytesSent -totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend -{ - self.progress.totalUnitCount = totalBytesExpectedToSend; - self.progress.completedUnitCount = totalBytesSent; -} - -- (void)URLSession:(__unused NSURLSession *)session - task:(NSURLSessionTask *)task -didCompleteWithError:(NSError *)error -{ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wgnu" - __strong AFURLSessionManager *manager = self.manager; - - __block id responseObject = nil; - - __block NSMutableDictionary *userInfo = [NSMutableDictionary dictionary]; - userInfo[AFNetworkingTaskDidCompleteResponseSerializerKey] = manager.responseSerializer; - - if (self.downloadFileURL) { - userInfo[AFNetworkingTaskDidCompleteAssetPathKey] = self.downloadFileURL; - } else if (self.mutableData) { - userInfo[AFNetworkingTaskDidCompleteResponseDataKey] = [NSData dataWithData:self.mutableData]; - } - - if (error) { - userInfo[AFNetworkingTaskDidCompleteErrorKey] = error; - - dispatch_group_async(manager.completionGroup ?: url_session_manager_completion_group(), manager.completionQueue ?: dispatch_get_main_queue(), ^{ - if (self.completionHandler) { - self.completionHandler(task.response, responseObject, error); - } - - dispatch_async(dispatch_get_main_queue(), ^{ - [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidCompleteNotification object:task userInfo:userInfo]; - }); - }); - } else { - dispatch_async(url_session_manager_processing_queue(), ^{ - NSError *serializationError = nil; - responseObject = [manager.responseSerializer responseObjectForResponse:task.response data:[NSData dataWithData:self.mutableData] error:&serializationError]; - - if (self.downloadFileURL) { - responseObject = self.downloadFileURL; - } - - if (responseObject) { - userInfo[AFNetworkingTaskDidCompleteSerializedResponseKey] = responseObject; - } - - if (serializationError) { - userInfo[AFNetworkingTaskDidCompleteErrorKey] = serializationError; - } - - dispatch_group_async(manager.completionGroup ?: url_session_manager_completion_group(), manager.completionQueue ?: dispatch_get_main_queue(), ^{ - if (self.completionHandler) { - self.completionHandler(task.response, responseObject, serializationError); - } - - dispatch_async(dispatch_get_main_queue(), ^{ - [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidCompleteNotification object:task userInfo:userInfo]; - }); - }); - }); - } -#pragma clang diagnostic pop -} - -#pragma mark - NSURLSessionDataTaskDelegate - -- (void)URLSession:(__unused NSURLSession *)session - dataTask:(__unused NSURLSessionDataTask *)dataTask - didReceiveData:(NSData *)data -{ - [self.mutableData appendData:data]; -} - -#pragma mark - NSURLSessionDownloadTaskDelegate - -- (void)URLSession:(NSURLSession *)session - downloadTask:(NSURLSessionDownloadTask *)downloadTask -didFinishDownloadingToURL:(NSURL *)location -{ - NSError *fileManagerError = nil; - self.downloadFileURL = nil; - - if (self.downloadTaskDidFinishDownloading) { - self.downloadFileURL = self.downloadTaskDidFinishDownloading(session, downloadTask, location); - if (self.downloadFileURL) { - [[NSFileManager defaultManager] moveItemAtURL:location toURL:self.downloadFileURL error:&fileManagerError]; - - if (fileManagerError) { - [[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDownloadTaskDidFailToMoveFileNotification object:downloadTask userInfo:fileManagerError.userInfo]; - } - } - } -} - -- (void)URLSession:(__unused NSURLSession *)session - downloadTask:(__unused NSURLSessionDownloadTask *)downloadTask - didWriteData:(__unused int64_t)bytesWritten - totalBytesWritten:(int64_t)totalBytesWritten -totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite -{ - self.progress.totalUnitCount = totalBytesExpectedToWrite; - self.progress.completedUnitCount = totalBytesWritten; -} - -- (void)URLSession:(__unused NSURLSession *)session - downloadTask:(__unused NSURLSessionDownloadTask *)downloadTask - didResumeAtOffset:(int64_t)fileOffset -expectedTotalBytes:(int64_t)expectedTotalBytes { - self.progress.totalUnitCount = expectedTotalBytes; - self.progress.completedUnitCount = fileOffset; -} - -@end - -#pragma mark - - -@interface AFURLSessionManager () -@property (readwrite, nonatomic, strong) NSURLSessionConfiguration *sessionConfiguration; -@property (readwrite, nonatomic, strong) NSOperationQueue *operationQueue; -@property (readwrite, nonatomic, strong) NSURLSession *session; -@property (readwrite, nonatomic, strong) NSMutableDictionary *mutableTaskDelegatesKeyedByTaskIdentifier; -@property (readwrite, nonatomic, strong) NSLock *lock; -@property (readwrite, nonatomic, copy) AFURLSessionDidBecomeInvalidBlock sessionDidBecomeInvalid; -@property (readwrite, nonatomic, copy) AFURLSessionDidReceiveAuthenticationChallengeBlock sessionDidReceiveAuthenticationChallenge; -@property (readwrite, nonatomic, copy) AFURLSessionDidFinishEventsForBackgroundURLSessionBlock didFinishEventsForBackgroundURLSession; -@property (readwrite, nonatomic, copy) AFURLSessionTaskWillPerformHTTPRedirectionBlock taskWillPerformHTTPRedirection; -@property (readwrite, nonatomic, copy) AFURLSessionTaskDidReceiveAuthenticationChallengeBlock taskDidReceiveAuthenticationChallenge; -@property (readwrite, nonatomic, copy) AFURLSessionTaskNeedNewBodyStreamBlock taskNeedNewBodyStream; -@property (readwrite, nonatomic, copy) AFURLSessionTaskDidSendBodyDataBlock taskDidSendBodyData; -@property (readwrite, nonatomic, copy) AFURLSessionTaskDidCompleteBlock taskDidComplete; -@property (readwrite, nonatomic, copy) AFURLSessionDataTaskDidReceiveResponseBlock dataTaskDidReceiveResponse; -@property (readwrite, nonatomic, copy) AFURLSessionDataTaskDidBecomeDownloadTaskBlock dataTaskDidBecomeDownloadTask; -@property (readwrite, nonatomic, copy) AFURLSessionDataTaskDidReceiveDataBlock dataTaskDidReceiveData; -@property (readwrite, nonatomic, copy) AFURLSessionDataTaskWillCacheResponseBlock dataTaskWillCacheResponse; -@property (readwrite, nonatomic, copy) AFURLSessionDownloadTaskDidFinishDownloadingBlock downloadTaskDidFinishDownloading; -@property (readwrite, nonatomic, copy) AFURLSessionDownloadTaskDidWriteDataBlock downloadTaskDidWriteData; -@property (readwrite, nonatomic, copy) AFURLSessionDownloadTaskDidResumeBlock downloadTaskDidResume; -@end - -@implementation AFURLSessionManager - -- (instancetype)init { - return [self initWithSessionConfiguration:nil]; -} - -- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration { - self = [super init]; - if (!self) { - return nil; - } - - if (!configuration) { - configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; - } - - self.sessionConfiguration = configuration; - - self.operationQueue = [[NSOperationQueue alloc] init]; - self.operationQueue.maxConcurrentOperationCount = 1; - - self.session = [NSURLSession sessionWithConfiguration:self.sessionConfiguration delegate:self delegateQueue:self.operationQueue]; - - self.responseSerializer = [AFJSONResponseSerializer serializer]; - - self.securityPolicy = [AFSecurityPolicy defaultPolicy]; - - self.reachabilityManager = [AFNetworkReachabilityManager sharedManager]; - - self.mutableTaskDelegatesKeyedByTaskIdentifier = [[NSMutableDictionary alloc] init]; - - self.lock = [[NSLock alloc] init]; - self.lock.name = AFURLSessionManagerLockName; - - [self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) { - for (NSURLSessionDataTask *task in dataTasks) { - [self addDelegateForDataTask:task completionHandler:nil]; - } - - for (NSURLSessionUploadTask *uploadTask in uploadTasks) { - [self addDelegateForUploadTask:uploadTask progress:nil completionHandler:nil]; - } - - for (NSURLSessionDownloadTask *downloadTask in downloadTasks) { - [self addDelegateForDownloadTask:downloadTask progress:nil destination:nil completionHandler:nil]; - } - }]; - - return self; -} - -#pragma mark - - -- (AFURLSessionManagerTaskDelegate *)delegateForTask:(NSURLSessionTask *)task { - NSParameterAssert(task); - - AFURLSessionManagerTaskDelegate *delegate = nil; - [self.lock lock]; - delegate = self.mutableTaskDelegatesKeyedByTaskIdentifier[@(task.taskIdentifier)]; - [self.lock unlock]; - - return delegate; -} - -- (void)setDelegate:(AFURLSessionManagerTaskDelegate *)delegate - forTask:(NSURLSessionTask *)task -{ - NSParameterAssert(task); - NSParameterAssert(delegate); - - [task addObserver:self forKeyPath:NSStringFromSelector(@selector(state)) options:(NSKeyValueObservingOptions)(NSKeyValueObservingOptionOld |NSKeyValueObservingOptionNew) context:AFTaskStateChangedContext]; - [self.lock lock]; - self.mutableTaskDelegatesKeyedByTaskIdentifier[@(task.taskIdentifier)] = delegate; - [self.lock unlock]; -} - -- (void)addDelegateForDataTask:(NSURLSessionDataTask *)dataTask - completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler -{ - AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] init]; - delegate.manager = self; - delegate.completionHandler = completionHandler; - - [self setDelegate:delegate forTask:dataTask]; -} - -- (void)addDelegateForUploadTask:(NSURLSessionUploadTask *)uploadTask - progress:(NSProgress * __autoreleasing *)progress - completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler -{ - AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] init]; - delegate.manager = self; - delegate.completionHandler = completionHandler; - - int64_t totalUnitCount = uploadTask.countOfBytesExpectedToSend; - if(totalUnitCount == NSURLSessionTransferSizeUnknown) { - NSString *contentLength = [uploadTask.originalRequest valueForHTTPHeaderField:@"Content-Length"]; - if(contentLength) { - totalUnitCount = (int64_t) [contentLength longLongValue]; - } - } - - delegate.progress = [NSProgress progressWithTotalUnitCount:totalUnitCount]; - delegate.progress.pausingHandler = ^{ - [uploadTask suspend]; - }; - delegate.progress.cancellationHandler = ^{ - [uploadTask cancel]; - }; - - if (progress) { - *progress = delegate.progress; - } - - [self setDelegate:delegate forTask:uploadTask]; -} - -- (void)addDelegateForDownloadTask:(NSURLSessionDownloadTask *)downloadTask - progress:(NSProgress * __autoreleasing *)progress - destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination - completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler -{ - AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] init]; - delegate.manager = self; - delegate.completionHandler = completionHandler; - - if (destination) { - delegate.downloadTaskDidFinishDownloading = ^NSURL * (NSURLSession * __unused session, NSURLSessionDownloadTask *task, NSURL *location) { - return destination(location, task.response); - }; - } - - if (progress) { - *progress = delegate.progress; - } - - [self setDelegate:delegate forTask:downloadTask]; -} - -- (void)removeDelegateForTask:(NSURLSessionTask *)task { - NSParameterAssert(task); - - [task removeObserver:self forKeyPath:NSStringFromSelector(@selector(state)) context:AFTaskStateChangedContext]; - [self.lock lock]; - [self.mutableTaskDelegatesKeyedByTaskIdentifier removeObjectForKey:@(task.taskIdentifier)]; - [self.lock unlock]; -} - -- (void)removeAllDelegates { - [self.lock lock]; - [self.mutableTaskDelegatesKeyedByTaskIdentifier removeAllObjects]; - [self.lock unlock]; -} - -#pragma mark - - -- (NSArray *)tasksForKeyPath:(NSString *)keyPath { - __block NSArray *tasks = nil; - dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); - [self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) { - if ([keyPath isEqualToString:NSStringFromSelector(@selector(dataTasks))]) { - tasks = dataTasks; - } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(uploadTasks))]) { - tasks = uploadTasks; - } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(downloadTasks))]) { - tasks = downloadTasks; - } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(tasks))]) { - tasks = [@[dataTasks, uploadTasks, downloadTasks] valueForKeyPath:@"@unionOfArrays.self"]; - } - - dispatch_semaphore_signal(semaphore); - }]; - - dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); - - return tasks; -} - -- (NSArray *)tasks { - return [self tasksForKeyPath:NSStringFromSelector(_cmd)]; -} - -- (NSArray *)dataTasks { - return [self tasksForKeyPath:NSStringFromSelector(_cmd)]; -} - -- (NSArray *)uploadTasks { - return [self tasksForKeyPath:NSStringFromSelector(_cmd)]; -} - -- (NSArray *)downloadTasks { - return [self tasksForKeyPath:NSStringFromSelector(_cmd)]; -} - -#pragma mark - - -- (void)invalidateSessionCancelingTasks:(BOOL)cancelPendingTasks { - dispatch_async(dispatch_get_main_queue(), ^{ - if (cancelPendingTasks) { - [self.session invalidateAndCancel]; - } else { - [self.session finishTasksAndInvalidate]; - } - }); -} - -#pragma mark - - -- (void)setResponseSerializer:(id <AFURLResponseSerialization>)responseSerializer { - NSParameterAssert(responseSerializer); - - _responseSerializer = responseSerializer; -} - -#pragma mark - - -- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request - completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler -{ - __block NSURLSessionDataTask *dataTask = nil; - dispatch_sync(url_session_manager_creation_queue(), ^{ - dataTask = [self.session dataTaskWithRequest:request]; - }); - - [self addDelegateForDataTask:dataTask completionHandler:completionHandler]; - - return dataTask; -} - -#pragma mark - - -- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request - fromFile:(NSURL *)fileURL - progress:(NSProgress * __autoreleasing *)progress - completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler -{ - __block NSURLSessionUploadTask *uploadTask = nil; - dispatch_sync(url_session_manager_creation_queue(), ^{ - uploadTask = [self.session uploadTaskWithRequest:request fromFile:fileURL]; - }); - - if (!uploadTask && self.attemptsToRecreateUploadTasksForBackgroundSessions && self.session.configuration.identifier) { - for (NSUInteger attempts = 0; !uploadTask && attempts < AFMaximumNumberOfAttemptsToRecreateBackgroundSessionUploadTask; attempts++) { - uploadTask = [self.session uploadTaskWithRequest:request fromFile:fileURL]; - } - } - - [self addDelegateForUploadTask:uploadTask progress:progress completionHandler:completionHandler]; - - return uploadTask; -} - -- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request - fromData:(NSData *)bodyData - progress:(NSProgress * __autoreleasing *)progress - completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler -{ - __block NSURLSessionUploadTask *uploadTask = nil; - dispatch_sync(url_session_manager_creation_queue(), ^{ - uploadTask = [self.session uploadTaskWithRequest:request fromData:bodyData]; - }); - - [self addDelegateForUploadTask:uploadTask progress:progress completionHandler:completionHandler]; - - return uploadTask; -} - -- (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)request - progress:(NSProgress * __autoreleasing *)progress - completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler -{ - __block NSURLSessionUploadTask *uploadTask = nil; - dispatch_sync(url_session_manager_creation_queue(), ^{ - uploadTask = [self.session uploadTaskWithStreamedRequest:request]; - }); - - [self addDelegateForUploadTask:uploadTask progress:progress completionHandler:completionHandler]; - - return uploadTask; -} - -#pragma mark - - -- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request - progress:(NSProgress * __autoreleasing *)progress - destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination - completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler -{ - __block NSURLSessionDownloadTask *downloadTask = nil; - dispatch_sync(url_session_manager_creation_queue(), ^{ - downloadTask = [self.session downloadTaskWithRequest:request]; - }); - - [self addDelegateForDownloadTask:downloadTask progress:progress destination:destination completionHandler:completionHandler]; - - return downloadTask; -} - -- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData - progress:(NSProgress * __autoreleasing *)progress - destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination - completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler -{ - __block NSURLSessionDownloadTask *downloadTask = nil; - dispatch_sync(url_session_manager_creation_queue(), ^{ - downloadTask = [self.session downloadTaskWithResumeData:resumeData]; - }); - - [self addDelegateForDownloadTask:downloadTask progress:progress destination:destination completionHandler:completionHandler]; - - return downloadTask; -} - -#pragma mark - - -- (NSProgress *)uploadProgressForTask:(NSURLSessionUploadTask *)uploadTask { - return [[self delegateForTask:uploadTask] progress]; -} - -- (NSProgress *)downloadProgressForTask:(NSURLSessionDownloadTask *)downloadTask { - return [[self delegateForTask:downloadTask] progress]; -} - -#pragma mark - - -- (void)setSessionDidBecomeInvalidBlock:(void (^)(NSURLSession *session, NSError *error))block { - self.sessionDidBecomeInvalid = block; -} - -- (void)setSessionDidReceiveAuthenticationChallengeBlock:(NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential))block { - self.sessionDidReceiveAuthenticationChallenge = block; -} - -- (void)setDidFinishEventsForBackgroundURLSessionBlock:(void (^)(NSURLSession *session))block { - self.didFinishEventsForBackgroundURLSession = block; -} - -#pragma mark - - -- (void)setTaskNeedNewBodyStreamBlock:(NSInputStream * (^)(NSURLSession *session, NSURLSessionTask *task))block { - self.taskNeedNewBodyStream = block; -} - -- (void)setTaskWillPerformHTTPRedirectionBlock:(NSURLRequest * (^)(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request))block { - self.taskWillPerformHTTPRedirection = block; -} - -- (void)setTaskDidReceiveAuthenticationChallengeBlock:(NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential))block { - self.taskDidReceiveAuthenticationChallenge = block; -} - -- (void)setTaskDidSendBodyDataBlock:(void (^)(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend))block { - self.taskDidSendBodyData = block; -} - -- (void)setTaskDidCompleteBlock:(void (^)(NSURLSession *session, NSURLSessionTask *task, NSError *error))block { - self.taskDidComplete = block; -} - -#pragma mark - - -- (void)setDataTaskDidReceiveResponseBlock:(NSURLSessionResponseDisposition (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response))block { - self.dataTaskDidReceiveResponse = block; -} - -- (void)setDataTaskDidBecomeDownloadTaskBlock:(void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask))block { - self.dataTaskDidBecomeDownloadTask = block; -} - -- (void)setDataTaskDidReceiveDataBlock:(void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data))block { - self.dataTaskDidReceiveData = block; -} - -- (void)setDataTaskWillCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSCachedURLResponse *proposedResponse))block { - self.dataTaskWillCacheResponse = block; -} - -#pragma mark - - -- (void)setDownloadTaskDidFinishDownloadingBlock:(NSURL * (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location))block { - self.downloadTaskDidFinishDownloading = block; -} - -- (void)setDownloadTaskDidWriteDataBlock:(void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite))block { - self.downloadTaskDidWriteData = block; -} - -- (void)setDownloadTaskDidResumeBlock:(void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes))block { - self.downloadTaskDidResume = block; -} - -#pragma mark - NSObject - -- (NSString *)description { - return [NSString stringWithFormat:@"<%@: %p, session: %@, operationQueue: %@>", NSStringFromClass([self class]), self, self.session, self.operationQueue]; -} - -- (BOOL)respondsToSelector:(SEL)selector { - if (selector == @selector(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:)) { - return self.taskWillPerformHTTPRedirection != nil; - } else if (selector == @selector(URLSession:dataTask:didReceiveResponse:completionHandler:)) { - return self.dataTaskDidReceiveResponse != nil; - } else if (selector == @selector(URLSession:dataTask:willCacheResponse:completionHandler:)) { - return self.dataTaskWillCacheResponse != nil; - } else if (selector == @selector(URLSessionDidFinishEventsForBackgroundURLSession:)) { - return self.didFinishEventsForBackgroundURLSession != nil; - } - - return [[self class] instancesRespondToSelector:selector]; -} - -#pragma mark - NSKeyValueObserving - -- (void)observeValueForKeyPath:(NSString *)keyPath - ofObject:(id)object - change:(NSDictionary *)change - context:(void *)context -{ - if (context == AFTaskStateChangedContext && [keyPath isEqualToString:@"state"]) { - if (change[NSKeyValueChangeOldKey] && change[NSKeyValueChangeNewKey] && [change[NSKeyValueChangeNewKey] isEqual:change[NSKeyValueChangeOldKey]]) { - return; - } - - NSString *notificationName = nil; - switch ([(NSURLSessionTask *)object state]) { - case NSURLSessionTaskStateRunning: - notificationName = AFNetworkingTaskDidResumeNotification; - break; - case NSURLSessionTaskStateSuspended: - notificationName = AFNetworkingTaskDidSuspendNotification; - break; - case NSURLSessionTaskStateCompleted: - // AFNetworkingTaskDidFinishNotification posted by task completion handlers - default: - break; - } - - if (notificationName) { - dispatch_async(dispatch_get_main_queue(), ^{ - [[NSNotificationCenter defaultCenter] postNotificationName:notificationName object:object]; - }); - } - } else { - [super observeValueForKeyPath:keyPath ofObject:object change:change context:context]; - } -} - -#pragma mark - NSURLSessionDelegate - -- (void)URLSession:(NSURLSession *)session -didBecomeInvalidWithError:(NSError *)error -{ - if (self.sessionDidBecomeInvalid) { - self.sessionDidBecomeInvalid(session, error); - } - - [self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) { - NSArray *tasks = [@[dataTasks, uploadTasks, downloadTasks] valueForKeyPath:@"@unionOfArrays.self"]; - for (NSURLSessionTask *task in tasks) { - [task removeObserver:self forKeyPath:NSStringFromSelector(@selector(state)) context:AFTaskStateChangedContext]; - } - - [self removeAllDelegates]; - }]; - - [[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDidInvalidateNotification object:session]; -} - -- (void)URLSession:(NSURLSession *)session -didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge - completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler -{ - NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling; - __block NSURLCredential *credential = nil; - - if (self.sessionDidReceiveAuthenticationChallenge) { - disposition = self.sessionDidReceiveAuthenticationChallenge(session, challenge, &credential); - } else { - if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) { - if ([self.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) { - credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]; - if (credential) { - disposition = NSURLSessionAuthChallengeUseCredential; - } else { - disposition = NSURLSessionAuthChallengePerformDefaultHandling; - } - } else { - disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge; - } - } else { - disposition = NSURLSessionAuthChallengePerformDefaultHandling; - } - } - - if (completionHandler) { - completionHandler(disposition, credential); - } -} - -#pragma mark - NSURLSessionTaskDelegate - -- (void)URLSession:(NSURLSession *)session - task:(NSURLSessionTask *)task -willPerformHTTPRedirection:(NSHTTPURLResponse *)response - newRequest:(NSURLRequest *)request - completionHandler:(void (^)(NSURLRequest *))completionHandler -{ - NSURLRequest *redirectRequest = request; - - if (self.taskWillPerformHTTPRedirection) { - redirectRequest = self.taskWillPerformHTTPRedirection(session, task, response, request); - } - - if (completionHandler) { - completionHandler(redirectRequest); - } -} - -- (void)URLSession:(NSURLSession *)session - task:(NSURLSessionTask *)task -didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge - completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler -{ - NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling; - __block NSURLCredential *credential = nil; - - if (self.taskDidReceiveAuthenticationChallenge) { - disposition = self.taskDidReceiveAuthenticationChallenge(session, task, challenge, &credential); - } else { - if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) { - if ([self.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) { - disposition = NSURLSessionAuthChallengeUseCredential; - credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]; - } else { - disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge; - } - } else { - disposition = NSURLSessionAuthChallengePerformDefaultHandling; - } - } - - if (completionHandler) { - completionHandler(disposition, credential); - } -} - -- (void)URLSession:(NSURLSession *)session - task:(NSURLSessionTask *)task - needNewBodyStream:(void (^)(NSInputStream *bodyStream))completionHandler -{ - NSInputStream *inputStream = nil; - - if (self.taskNeedNewBodyStream) { - inputStream = self.taskNeedNewBodyStream(session, task); - } else if (task.originalRequest.HTTPBodyStream && [task.originalRequest.HTTPBodyStream conformsToProtocol:@protocol(NSCopying)]) { - inputStream = [task.originalRequest.HTTPBodyStream copy]; - } - - if (completionHandler) { - completionHandler(inputStream); - } -} - -- (void)URLSession:(NSURLSession *)session - task:(NSURLSessionTask *)task - didSendBodyData:(int64_t)bytesSent - totalBytesSent:(int64_t)totalBytesSent -totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend -{ - - int64_t totalUnitCount = totalBytesExpectedToSend; - if(totalUnitCount == NSURLSessionTransferSizeUnknown) { - NSString *contentLength = [task.originalRequest valueForHTTPHeaderField:@"Content-Length"]; - if(contentLength) { - totalUnitCount = (int64_t) [contentLength longLongValue]; - } - } - - AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:task]; - [delegate URLSession:session task:task didSendBodyData:bytesSent totalBytesSent:totalBytesSent totalBytesExpectedToSend:totalUnitCount]; - - if (self.taskDidSendBodyData) { - self.taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalUnitCount); - } -} - -- (void)URLSession:(NSURLSession *)session - task:(NSURLSessionTask *)task -didCompleteWithError:(NSError *)error -{ - AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:task]; - - // delegate may be nil when completing a task in the background - if (delegate) { - [delegate URLSession:session task:task didCompleteWithError:error]; - - [self removeDelegateForTask:task]; - } - - if (self.taskDidComplete) { - self.taskDidComplete(session, task, error); - } - -} - -#pragma mark - NSURLSessionDataDelegate - -- (void)URLSession:(NSURLSession *)session - dataTask:(NSURLSessionDataTask *)dataTask -didReceiveResponse:(NSURLResponse *)response - completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler -{ - NSURLSessionResponseDisposition disposition = NSURLSessionResponseAllow; - - if (self.dataTaskDidReceiveResponse) { - disposition = self.dataTaskDidReceiveResponse(session, dataTask, response); - } - - if (completionHandler) { - completionHandler(disposition); - } -} - -- (void)URLSession:(NSURLSession *)session - dataTask:(NSURLSessionDataTask *)dataTask -didBecomeDownloadTask:(NSURLSessionDownloadTask *)downloadTask -{ - AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:dataTask]; - if (delegate) { - [self removeDelegateForTask:dataTask]; - [self setDelegate:delegate forTask:downloadTask]; - } - - if (self.dataTaskDidBecomeDownloadTask) { - self.dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask); - } -} - -- (void)URLSession:(NSURLSession *)session - dataTask:(NSURLSessionDataTask *)dataTask - didReceiveData:(NSData *)data -{ - AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:dataTask]; - [delegate URLSession:session dataTask:dataTask didReceiveData:data]; - - if (self.dataTaskDidReceiveData) { - self.dataTaskDidReceiveData(session, dataTask, data); - } -} - -- (void)URLSession:(NSURLSession *)session - dataTask:(NSURLSessionDataTask *)dataTask - willCacheResponse:(NSCachedURLResponse *)proposedResponse - completionHandler:(void (^)(NSCachedURLResponse *cachedResponse))completionHandler -{ - NSCachedURLResponse *cachedResponse = proposedResponse; - - if (self.dataTaskWillCacheResponse) { - cachedResponse = self.dataTaskWillCacheResponse(session, dataTask, proposedResponse); - } - - if (completionHandler) { - completionHandler(cachedResponse); - } -} - -- (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session { - if (self.didFinishEventsForBackgroundURLSession) { - dispatch_async(dispatch_get_main_queue(), ^{ - self.didFinishEventsForBackgroundURLSession(session); - }); - } -} - -#pragma mark - NSURLSessionDownloadDelegate - -- (void)URLSession:(NSURLSession *)session - downloadTask:(NSURLSessionDownloadTask *)downloadTask -didFinishDownloadingToURL:(NSURL *)location -{ - if (self.downloadTaskDidFinishDownloading) { - NSURL *fileURL = self.downloadTaskDidFinishDownloading(session, downloadTask, location); - if (fileURL) { - NSError *error = nil; - [[NSFileManager defaultManager] moveItemAtURL:location toURL:fileURL error:&error]; - if (error) { - [[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDownloadTaskDidFailToMoveFileNotification object:downloadTask userInfo:error.userInfo]; - } - - return; - } - } - - AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:downloadTask]; - if (delegate) { - [delegate URLSession:session downloadTask:downloadTask didFinishDownloadingToURL:location]; - } -} - -- (void)URLSession:(NSURLSession *)session - downloadTask:(NSURLSessionDownloadTask *)downloadTask - didWriteData:(int64_t)bytesWritten - totalBytesWritten:(int64_t)totalBytesWritten -totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite -{ - AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:downloadTask]; - [delegate URLSession:session downloadTask:downloadTask didWriteData:bytesWritten totalBytesWritten:totalBytesWritten totalBytesExpectedToWrite:totalBytesExpectedToWrite]; - - if (self.downloadTaskDidWriteData) { - self.downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite); - } -} - -- (void)URLSession:(NSURLSession *)session - downloadTask:(NSURLSessionDownloadTask *)downloadTask - didResumeAtOffset:(int64_t)fileOffset -expectedTotalBytes:(int64_t)expectedTotalBytes -{ - AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:downloadTask]; - [delegate URLSession:session downloadTask:downloadTask didResumeAtOffset:fileOffset expectedTotalBytes:expectedTotalBytes]; - - if (self.downloadTaskDidResume) { - self.downloadTaskDidResume(session, downloadTask, fileOffset, expectedTotalBytes); - } -} - -#pragma mark - NSSecureCoding - -+ (BOOL)supportsSecureCoding { - return YES; -} - -- (id)initWithCoder:(NSCoder *)decoder { - NSURLSessionConfiguration *configuration = [decoder decodeObjectOfClass:[NSURLSessionConfiguration class] forKey:@"sessionConfiguration"]; - - self = [self initWithSessionConfiguration:configuration]; - if (!self) { - return nil; - } - - return self; -} - -- (void)encodeWithCoder:(NSCoder *)coder { - [coder encodeObject:self.session.configuration forKey:@"sessionConfiguration"]; -} - -#pragma mark - NSCopying - -- (id)copyWithZone:(NSZone *)zone { - return [[[self class] allocWithZone:zone] initWithSessionConfiguration:self.session.configuration]; -} - -@end - -#endif diff --git a/plugins/com.synconset.cordovaHTTP/src/ios/CordovaHttpPlugin.h b/plugins/com.synconset.cordovaHTTP/src/ios/CordovaHttpPlugin.h deleted file mode 100644 index a74c8254..00000000 --- a/plugins/com.synconset.cordovaHTTP/src/ios/CordovaHttpPlugin.h +++ /dev/null @@ -1,17 +0,0 @@ -#import <Foundation/Foundation.h> - -#import <Cordova/CDVPlugin.h> -#import <Cordova/CDVJSON.h> - -@interface CordovaHttpPlugin : CDVPlugin - -- (void)useBasicAuth:(CDVInvokedUrlCommand*)command; -- (void)setHeader:(CDVInvokedUrlCommand*)command; -- (void)enableSSLPinning:(CDVInvokedUrlCommand*)command; -- (void)acceptAllCerts:(CDVInvokedUrlCommand*)command; -- (void)post:(CDVInvokedUrlCommand*)command; -- (void)get:(CDVInvokedUrlCommand*)command; -- (void)uploadFile:(CDVInvokedUrlCommand*)command; -- (void)downloadFile:(CDVInvokedUrlCommand*)command; - -@end diff --git a/plugins/com.synconset.cordovaHTTP/src/ios/CordovaHttpPlugin.m b/plugins/com.synconset.cordovaHTTP/src/ios/CordovaHttpPlugin.m deleted file mode 100644 index 54de660d..00000000 --- a/plugins/com.synconset.cordovaHTTP/src/ios/CordovaHttpPlugin.m +++ /dev/null @@ -1,239 +0,0 @@ -#import "CordovaHttpPlugin.h" -#import "CDVFile.h" -#import "TextResponseSerializer.h" -#import "HttpManager.h" - -@interface CordovaHttpPlugin() - -- (void)setRequestHeaders:(NSDictionary*)headers; - -@end - - -@implementation CordovaHttpPlugin { - AFHTTPRequestSerializer *requestSerializer; -} - -- (void)pluginInitialize { - requestSerializer = [AFHTTPRequestSerializer serializer]; -} - -- (void)setRequestHeaders:(NSDictionary*)headers { - [HttpManager sharedClient].requestSerializer = [AFHTTPRequestSerializer serializer]; - [requestSerializer.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { - [[HttpManager sharedClient].requestSerializer setValue:obj forHTTPHeaderField:key]; - }]; - [headers enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { - [[HttpManager sharedClient].requestSerializer setValue:obj forHTTPHeaderField:key]; - }]; -} - -- (void)useBasicAuth:(CDVInvokedUrlCommand*)command { - NSString *username = [command.arguments objectAtIndex:0]; - NSString *password = [command.arguments objectAtIndex:1]; - - [requestSerializer setAuthorizationHeaderFieldWithUsername:username password:password]; - - CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; -} - -- (void)setHeader:(CDVInvokedUrlCommand*)command { - NSString *header = [command.arguments objectAtIndex:0]; - NSString *value = [command.arguments objectAtIndex:1]; - - [requestSerializer setValue:value forHTTPHeaderField: header]; - - CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; -} - -- (void)enableSSLPinning:(CDVInvokedUrlCommand*)command { - bool enable = [[command.arguments objectAtIndex:0] boolValue]; - if (enable) { - [HttpManager sharedClient].securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate]; - [HttpManager sharedClient].securityPolicy.validatesCertificateChain = NO; - } else { - [HttpManager sharedClient].securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone]; - } - - CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; -} - -- (void)acceptAllCerts:(CDVInvokedUrlCommand*)command { - CDVPluginResult* pluginResult = nil; - bool allow = [[command.arguments objectAtIndex:0] boolValue]; - - [HttpManager sharedClient].securityPolicy.allowInvalidCertificates = allow; - - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; -} - -- (void)post:(CDVInvokedUrlCommand*)command { - HttpManager *manager = [HttpManager sharedClient]; - NSString *url = [command.arguments objectAtIndex:0]; - NSDictionary *parameters = [command.arguments objectAtIndex:1]; - NSDictionary *headers = [command.arguments objectAtIndex:2]; - [self setRequestHeaders: headers]; - - CordovaHttpPlugin* __weak weakSelf = self; - manager.responseSerializer = [TextResponseSerializer serializer]; - [manager POST:url parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) { - NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; - [dictionary setObject:[NSNumber numberWithInt:operation.response.statusCode] forKey:@"status"]; - [dictionary setObject:responseObject forKey:@"data"]; - CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:dictionary]; - [weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - } failure:^(AFHTTPRequestOperation *operation, NSError *error) { - NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; - [dictionary setObject:[NSNumber numberWithInt:operation.response.statusCode] forKey:@"status"]; - [dictionary setObject:[error localizedDescription] forKey:@"error"]; - CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:dictionary]; - [weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - }]; -} - -- (void)get:(CDVInvokedUrlCommand*)command { - HttpManager *manager = [HttpManager sharedClient]; - NSString *url = [command.arguments objectAtIndex:0]; - NSDictionary *parameters = [command.arguments objectAtIndex:1]; - NSDictionary *headers = [command.arguments objectAtIndex:2]; - [self setRequestHeaders: headers]; - - CordovaHttpPlugin* __weak weakSelf = self; - - manager.responseSerializer = [TextResponseSerializer serializer]; - [manager GET:url parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) { - NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; - [dictionary setObject:[NSNumber numberWithInt:operation.response.statusCode] forKey:@"status"]; - [dictionary setObject:responseObject forKey:@"data"]; - CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:dictionary]; - [weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - } failure:^(AFHTTPRequestOperation *operation, NSError *error) { - NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; - [dictionary setObject:[NSNumber numberWithInt:operation.response.statusCode] forKey:@"status"]; - [dictionary setObject:[error localizedDescription] forKey:@"error"]; - CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:dictionary]; - [weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - }]; -} - -- (void)uploadFile:(CDVInvokedUrlCommand*)command { - HttpManager *manager = [HttpManager sharedClient]; - NSString *url = [command.arguments objectAtIndex:0]; - NSDictionary *parameters = [command.arguments objectAtIndex:1]; - NSDictionary *headers = [command.arguments objectAtIndex:2]; - NSString *filePath = [command.arguments objectAtIndex: 3]; - NSString *name = [command.arguments objectAtIndex: 4]; - - NSURL *fileURL = [NSURL fileURLWithPath: filePath]; - - [self setRequestHeaders: headers]; - - CordovaHttpPlugin* __weak weakSelf = self; - manager.responseSerializer = [TextResponseSerializer serializer]; - [manager POST:url parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { - NSError *error; - [formData appendPartWithFileURL:fileURL name:name error:&error]; - if (error) { - NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; - [dictionary setObject:[NSNumber numberWithInt:500] forKey:@"status"]; - [dictionary setObject:@"Could not add image to post body." forKey:@"error"]; - CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:dictionary]; - [weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - return; - } - } success:^(AFHTTPRequestOperation *operation, id responseObject) { - NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; - [dictionary setObject:[NSNumber numberWithInt:operation.response.statusCode] forKey:@"status"]; - CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:dictionary]; - [weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - } failure:^(AFHTTPRequestOperation *operation, NSError *error) { - NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; - [dictionary setObject:[NSNumber numberWithInt:operation.response.statusCode] forKey:@"status"]; - [dictionary setObject:[error localizedDescription] forKey:@"error"]; - CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:dictionary]; - [weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - }]; -} - - -- (void)downloadFile:(CDVInvokedUrlCommand*)command { - HttpManager *manager = [HttpManager sharedClient]; - NSString *url = [command.arguments objectAtIndex:0]; - NSDictionary *parameters = [command.arguments objectAtIndex:1]; - NSDictionary *headers = [command.arguments objectAtIndex:2]; - NSString *filePath = [command.arguments objectAtIndex: 3]; - - [self setRequestHeaders: headers]; - - CordovaHttpPlugin* __weak weakSelf = self; - manager.responseSerializer = [AFHTTPResponseSerializer serializer]; - [manager GET:url parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) { - /* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * Modified by Andrew Stephan for Sync OnSet - * - */ - // Download response is okay; begin streaming output to file - NSString* parentPath = [filePath stringByDeletingLastPathComponent]; - - // create parent directories if needed - NSError *error; - if ([[NSFileManager defaultManager] createDirectoryAtPath:parentPath withIntermediateDirectories:YES attributes:nil error:&error] == NO) { - NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; - [dictionary setObject:[NSNumber numberWithInt:500] forKey:@"status"]; - if (error) { - [dictionary setObject:[NSString stringWithFormat:@"Could not create path to save downloaded file: %@", [error localizedDescription]] forKey:@"error"]; - } else { - [dictionary setObject:@"Could not create path to save downloaded file" forKey:@"error"]; - } - CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:dictionary]; - [weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - return; - } - NSData *data = (NSData *)responseObject; - if (![data writeToFile:filePath atomically:YES]) { - NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; - [dictionary setObject:[NSNumber numberWithInt:500] forKey:@"status"]; - [dictionary setObject:@"Could not write the data to the given filePath." forKey:@"error"]; - CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:dictionary]; - [weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - return; - } - - CDVFile *file = [[CDVFile alloc] init]; - NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; - [dictionary setObject:[NSNumber numberWithInt:operation.response.statusCode] forKey:@"status"]; - [dictionary setObject:[file getDirectoryEntry:filePath isDirectory:NO] forKey:@"file"]; - CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:dictionary]; - [weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - } failure:^(AFHTTPRequestOperation *operation, NSError *error) { - NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; - [dictionary setObject:[NSNumber numberWithInt:operation.response.statusCode] forKey:@"status"]; - [dictionary setObject:[error localizedDescription] forKey:@"error"]; - CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:dictionary]; - [weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - }]; -} - -@end diff --git a/plugins/com.synconset.cordovaHTTP/src/ios/HTTPManager.h b/plugins/com.synconset.cordovaHTTP/src/ios/HTTPManager.h deleted file mode 100644 index 776a969d..00000000 --- a/plugins/com.synconset.cordovaHTTP/src/ios/HTTPManager.h +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) 2012 Mattt Thompson (http://mattt.me/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// Modified by Andrew Stephan -#import <Foundation/Foundation.h> -#import "AFHTTPRequestOperationManager.h" - -@interface HttpManager : AFHTTPRequestOperationManager - -+ (instancetype)sharedClient; - -@end diff --git a/plugins/com.synconset.cordovaHTTP/src/ios/HTTPManager.m b/plugins/com.synconset.cordovaHTTP/src/ios/HTTPManager.m deleted file mode 100644 index 5d2b2944..00000000 --- a/plugins/com.synconset.cordovaHTTP/src/ios/HTTPManager.m +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) 2012 Mattt Thompson (http://mattt.me/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// Modified by Andrew Stephan -#import "HttpManager.h" - -@implementation HttpManager - -+ (instancetype)sharedClient { - static HttpManager *_sharedClient = nil; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - _sharedClient = [HttpManager manager]; - }); - - return _sharedClient; -} - -@end
\ No newline at end of file diff --git a/plugins/com.synconset.cordovaHTTP/src/ios/TextResponseSerializer.h b/plugins/com.synconset.cordovaHTTP/src/ios/TextResponseSerializer.h deleted file mode 100644 index d086a8ce..00000000 --- a/plugins/com.synconset.cordovaHTTP/src/ios/TextResponseSerializer.h +++ /dev/null @@ -1,8 +0,0 @@ -#import <Foundation/Foundation.h> -#import "AFURLResponseSerialization.h" - -@interface TextResponseSerializer : AFHTTPResponseSerializer - -+ (instancetype)serializer; - -@end diff --git a/plugins/com.synconset.cordovaHTTP/src/ios/TextResponseSerializer.m b/plugins/com.synconset.cordovaHTTP/src/ios/TextResponseSerializer.m deleted file mode 100644 index 39d4080b..00000000 --- a/plugins/com.synconset.cordovaHTTP/src/ios/TextResponseSerializer.m +++ /dev/null @@ -1,58 +0,0 @@ -#import "TextResponseSerializer.h" - -static BOOL AFErrorOrUnderlyingErrorHasCode(NSError *error, NSInteger code) { - if (error.code == code) { - return YES; - } else if (error.userInfo[NSUnderlyingErrorKey]) { - return AFErrorOrUnderlyingErrorHasCode(error.userInfo[NSUnderlyingErrorKey], code); - } - - return NO; -} - -@implementation TextResponseSerializer - -+ (instancetype)serializer { - TextResponseSerializer *serializer = [[self alloc] init]; - return serializer; -} - -- (instancetype)init { - self = [super init]; - if (!self) { - return nil; - } - - self.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"text/html", @"text/json", @"application/json", @"text/xml", @"application/xml", @"text/css", nil]; - - return self; -} - -#pragma mark - AFURLResponseSerialization - -- (id)responseObjectForResponse:(NSURLResponse *)response - data:(NSData *)data - error:(NSError *__autoreleasing *)error -{ - if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) { - if (AFErrorOrUnderlyingErrorHasCode(*error, NSURLErrorCannotDecodeContentData)) { - return nil; - } - } - - // 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. - // See https://github.com/rails/rails/issues/1742 - NSStringEncoding stringEncoding = self.stringEncoding; - if (response.textEncodingName) { - CFStringEncoding encoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)response.textEncodingName); - if (encoding != kCFStringEncodingInvalidId) { - stringEncoding = CFStringConvertEncodingToNSStringEncoding(encoding); - } - } - - NSString *responseString = [[NSString alloc] initWithData:data encoding:stringEncoding]; - - return responseString; -} - -@end
\ No newline at end of file diff --git a/plugins/com.synconset.cordovaHTTP/www/cordovaHTTP.js b/plugins/com.synconset.cordovaHTTP/www/cordovaHTTP.js deleted file mode 100644 index ce238f13..00000000 --- a/plugins/com.synconset.cordovaHTTP/www/cordovaHTTP.js +++ /dev/null @@ -1,131 +0,0 @@ -/*global angular*/ - -/* - * An HTTP Plugin for PhoneGap. - */ - -var exec = require('cordova/exec'); - -var http = { - useBasicAuth: function(username, password, success, failure) { - return exec(success, failure, "CordovaHttpPlugin", "useBasicAuth", [username, password]); - }, - setHeader: function(header, value, success, failure) { - return exec(success, failure, "CordovaHttpPlugin", "setHeader", [header, value]); - }, - enableSSLPinning: function(enable, success, failure) { - return exec(success, failure, "CordovaHttpPlugin", "enableSSLPinning", [enable]); - }, - acceptAllCerts: function(allow, success, failure) { - return exec(success, failure, "CordovaHttpPlugin", "acceptAllCerts", [allow]); - }, - post: function(url, params, headers, success, failure) { - return exec(success, failure, "CordovaHttpPlugin", "post", [url, params, headers]); - }, - get: function(url, params, headers, success, failure) { - return exec(success, failure, "CordovaHttpPlugin", "get", [url, params, headers]); - }, - uploadFile: function(url, params, headers, filePath, name, success, failure) { - return exec(success, failure, "CordovaHttpPlugin", "uploadFile", [url, params, headers, filePath, name]); - }, - downloadFile: function(url, params, headers, filePath, success, failure) { - /* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * Modified by Andrew Stephan for Sync OnSet - * - */ - var win = function(result) { - var entry = new (require('org.apache.cordova.file.FileEntry'))(); - entry.isDirectory = false; - entry.isFile = true; - entry.name = result.file.name; - entry.fullPath = result.file.fullPath; - success(entry); - }; - return exec(win, failure, "CordovaHttpPlugin", "downloadFile", [url, params, headers, filePath]); - } -}; - -module.exports = http; - -if (typeof angular !== "undefined") { - angular.module('cordovaHTTP', []).factory('cordovaHTTP', function($timeout, $q) { - function makePromise(fn, args, async) { - var deferred = $q.defer(); - - var success = function(response) { - if (async) { - $timeout(function() { - deferred.resolve(response); - }); - } else { - deferred.resolve(response); - } - }; - - var fail = function(response) { - if (async) { - $timeout(function() { - deferred.reject(response); - }); - } else { - deferred.reject(response); - } - }; - - args.push(success); - args.push(fail); - - fn.apply(http, args); - - return deferred.promise; - } - - var cordovaHTTP = { - useBasicAuth: function(username, password) { - return makePromise(http.useBasicAuth, [username, password]); - }, - setHeader: function(header, value) { - return makePromise(http.setHeader, [header, value]); - }, - enableSSLPinning: function(enable) { - return makePromise(http.enableSSLPinning, [enable]); - }, - acceptAllCerts: function(allow) { - return makePromise(http.acceptAllCerts, [allow]); - }, - post: function(url, params, headers) { - return makePromise(http.post, [url, params, headers], true); - }, - get: function(url, params, headers) { - return makePromise(http.get, [url, params, headers], true); - }, - uploadFile: function(url, params, headers, filePath, name) { - return makePromise(http.uploadFile, [url, params, headers, filePath, name], true); - }, - downloadFile: function(url, params, headers, filePath) { - return makePromise(http.downloadFile, [url, params, headers, filePath], true); - } - }; - return cordovaHTTP; - }); -} else { - window.cordovaHTTP = http; -} |
