aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/de/thedevstack/conversationsplus/http/HttpClient.java
blob: cde0675c2ce893cd44beaac80fa7a3b705959e47 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
package de.thedevstack.conversationsplus.http;

import android.os.PowerManager;
import android.support.annotation.NonNull;

import org.apache.http.conn.ssl.StrictHostnameVerifier;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.Locale;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;

import de.thedevstack.android.logcat.Logging;
import de.thedevstack.conversationsplus.ConversationsPlusApplication;
import de.thedevstack.conversationsplus.utils.CryptoHelper;
import de.thedevstack.conversationsplus.utils.SSLSocketHelper;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import okio.ForwardingSource;
import okio.Okio;
import okio.Source;

/**
 *
 */
public final class HttpClient implements Http {
    private static final long RETRIEVE_HEAD_WAKELOCK_TIMEOUT = 2000;
    private static HttpClient INSTANCE;
    private static final String LOGTAG = "http-client";

    private final OkHttpClient client;

    public static synchronized void init() {
        INSTANCE = new HttpClient();
    }

    public static synchronized HttpClient getClient() {
        if (null == INSTANCE) {
            init();
        }
        return INSTANCE;
    }

    private static OkHttpClient.Builder getBuilder(boolean interactive) {
        OkHttpClient.Builder builder = INSTANCE.client.newBuilder();
        initTrustManager(builder, interactive);

        return builder;
    }

    public static synchronized OkHttpClient getOkHttpClient(boolean interactive) {
        return getBuilder(interactive).build();
    }

    public static synchronized Call openCancelableAndProgressListenedCall(String url, final ProgressListener progressListener, boolean interactive) {
        OkHttpClient.Builder builder = getBuilder(interactive);
        OkHttpClient client = builder.addNetworkInterceptor(new Interceptor() {
            @Override public Response intercept(Chain chain) throws IOException {
                Response originalResponse = chain.proceed(chain.request());
                return originalResponse.newBuilder()
                        .body(new ProgressResponseBody(originalResponse.body(), progressListener))
                        .build();
            }
        })
                .build();

        return client.newCall(new Request.Builder().url(url).build());
    }

    public static void retrieveHead(String url, @NonNull Callback callback) throws IOException {
        OkHttpClient client = HttpClient.getOkHttpClient(true);
        Request request = new Request.Builder()
                .url(url)
                //.addHeader(HEADER_NAME_ACCEPT_ENCODING, "")
                .head()
                .build();
        Call call = client.newCall(request);
        PowerManager.WakeLock wakeLock = ConversationsPlusApplication.createPartialWakeLock("http-retrieve-head-" + call.hashCode());
        try {
            wakeLock.acquire(RETRIEVE_HEAD_WAKELOCK_TIMEOUT);
            Response response = call.execute();
            if (response.isSuccessful()) {
                callback.onResponse(call, response);
            }
        } catch (IOException e) {
            callback.onFailure(call, e);
        } finally {
            if (wakeLock.isHeld()) {
                wakeLock.release();
            }
        }
    }

    private HttpClient() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.addInterceptor(new UserAgentInterceptor());
        builder.addInterceptor(new LoggingInterceptor());
        this.client = builder.build();
    }

    private static void initTrustManager(final OkHttpClient.Builder builder, final boolean interactive) {
        final X509TrustManager trustManager;
        final HostnameVerifier hostnameVerifier;
        if (interactive) {
            trustManager = ConversationsPlusApplication.getMemorizingTrustManager();
            hostnameVerifier = ConversationsPlusApplication.getMemorizingTrustManager().wrapHostnameVerifier(
                    new StrictHostnameVerifier());
        } else {
            trustManager = ConversationsPlusApplication.getMemorizingTrustManager()
                    .getNonInteractive();
            hostnameVerifier = ConversationsPlusApplication.getMemorizingTrustManager()
                    .wrapHostnameVerifierNonInteractive(
                            new StrictHostnameVerifier());
        }
        try {
            final SSLContext sc = SSLSocketHelper.getSSLContext();
            sc.init(null, new X509TrustManager[]{trustManager},
                    ConversationsPlusApplication.getSecureRandom());

            final SSLSocketFactory sf = sc.getSocketFactory();
            final String[] cipherSuites = CryptoHelper.getOrderedCipherSuites(
                    sf.getSupportedCipherSuites());
            if (cipherSuites.length > 0) {
                sc.getDefaultSSLParameters().setCipherSuites(cipherSuites);

            }

            builder.sslSocketFactory(sf, trustManager);
            builder.hostnameVerifier(hostnameVerifier);
        } catch (final KeyManagementException | NoSuchAlgorithmException ignored) {
        }
    }

    private static class UserAgentInterceptor implements Interceptor, Http {

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request originalRequest = chain.request();
            Request requestWithUserAgent = originalRequest.newBuilder()
                    .header(USER_AGENT_REQUEST_PROPERTY_NAME, ConversationsPlusApplication.getNameAndVersion())
                    .build();
            return chain.proceed(requestWithUserAgent);
        }
    }

    private static class LoggingInterceptor implements Interceptor {
        @Override public Response intercept(Interceptor.Chain chain) throws IOException {
            Request request = chain.request();

            long t1 = System.nanoTime();
            Logging.d(LOGTAG, String.format(Locale.getDefault(), "Sending %s request %s on %s%n%s",
                    request.method(), request.url(), chain.connection(), request.headers()));

            Response response = chain.proceed(request);

            long t2 = System.nanoTime();
            Logging.d(LOGTAG, String.format(Locale.getDefault(), "Received response for %s request %s in %.1fms%n%s",
                    response.request().method(), response.request().url(), (t2 - t1) / 1e6d, response.headers()));

            return response;
        }
    }

    private static class ProgressResponseBody extends ResponseBody {

        private final ResponseBody responseBody;
        private final ProgressListener progressListener;
        private BufferedSource bufferedSource;

        public ProgressResponseBody(ResponseBody responseBody, ProgressListener progressListener) {
            this.responseBody = responseBody;
            this.progressListener = progressListener;
        }

        @Override public MediaType contentType() {
            return responseBody.contentType();
        }

        @Override public long contentLength() {
            return responseBody.contentLength();
        }

        @Override public BufferedSource source() {
            if (bufferedSource == null) {
                bufferedSource = Okio.buffer(source(responseBody.source()));
            }
            return bufferedSource;
        }

        private Source source(Source source) {
            return new ForwardingSource(source) {

                @Override public long read(Buffer sink, long byteCount) throws IOException {
                    long bytesRead = super.read(sink, byteCount);
                    // read() returns the number of bytes read, or -1 if this source is exhausted.
                    boolean done = bytesRead == -1;
                    long currentBytesRead = !done ? bytesRead : 0;
                    progressListener.update(currentBytesRead, responseBody.contentLength(), done);
                    return bytesRead;
                }
            };
        }
    }
}