Search in sources :

Example 16 with OkHttpClient

use of com.github.mjeanroy.junit.servers.client.impl.okhttp3.OkHttpClient in project mollyim-android by mollyim.

the class UpdateApkJob method onRun.

@Override
public void onRun() throws IOException, PackageManager.NameNotFoundException {
    if (!TextSecurePreferences.isUpdateApkEnabled(context)) {
        return;
    }
    boolean includeBeta = TextSecurePreferences.isUpdateApkIncludeBetaEnabled(context);
    Log.i(TAG, "Checking for APK update [stable" + (includeBeta ? ", beta" : "") + "]...");
    OkHttpClient client = new OkHttpClient.Builder().socketFactory(Network.getSocketFactory()).dns(Network.getDns()).build();
    Request request = new Request.Builder().url(String.format("%s/index-v1.json", BuildConfig.FDROID_UPDATE_URL)).build();
    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) {
        throw new IOException("Bad response: " + response.message());
    }
    if (response.body() == null) {
        throw new IOException("Missing body!");
    }
    RepoIndex repoIndex = JsonUtils.fromJson(response.body().bytes(), RepoIndex.class);
    if (repoIndex.packages == null || repoIndex.packages.appReleases == null) {
        return;
    }
    List<UpdateDescriptor> releases = repoIndex.packages.appReleases;
    UpdateDescriptor updateDescriptor = releases.stream().filter(r -> r.versionName != null).filter(r -> includeBeta || !r.versionName.contains("beta")).sorted().findFirst().orElse(null);
    if (updateDescriptor == null) {
        return;
    }
    byte[] digest = Hex.fromStringCondensed(updateDescriptor.getDigest());
    Log.i(TAG, "Got descriptor: " + updateDescriptor);
    if (updateDescriptor.getVersionCode() > getVersionCode()) {
        Uri uri = Uri.parse(BuildConfig.FDROID_UPDATE_URL).buildUpon().appendPath(updateDescriptor.getApkName()).build();
        DownloadStatus downloadStatus = getDownloadStatus(uri, digest);
        Log.i(TAG, "Download status: " + downloadStatus.getStatus());
        if (downloadStatus.getStatus() == DownloadStatus.Status.COMPLETE) {
            Log.i(TAG, "Download status complete, notifying...");
            handleDownloadNotify(downloadStatus.getDownloadId());
        } else if (downloadStatus.getStatus() == DownloadStatus.Status.MISSING) {
            Log.i(TAG, "Download status missing, starting download...");
            handleDownloadStart(uri, updateDescriptor.getVersionName(), digest);
        }
    }
}
Also used : Context(android.content.Context) JsonProperty(com.fasterxml.jackson.annotation.JsonProperty) PackageManager(android.content.pm.PackageManager) NonNull(androidx.annotation.NonNull) Data(org.thoughtcrime.securesms.jobmanager.Data) MessageDigest(java.security.MessageDigest) Uri(android.net.Uri) Intent(android.content.Intent) PackageInfo(android.content.pm.PackageInfo) TextSecurePreferences(org.thoughtcrime.securesms.util.TextSecurePreferences) UpdateApkReadyListener(org.thoughtcrime.securesms.service.UpdateApkReadyListener) JsonUtils(org.thoughtcrime.securesms.util.JsonUtils) Response(okhttp3.Response) FileUtils(org.thoughtcrime.securesms.util.FileUtils) Cursor(android.database.Cursor) Request(okhttp3.Request) NetworkConstraint(org.thoughtcrime.securesms.jobmanager.impl.NetworkConstraint) Hex(org.thoughtcrime.securesms.util.Hex) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) Network(org.thoughtcrime.securesms.net.Network) File(java.io.File) DownloadManager(android.app.DownloadManager) Log(org.signal.core.util.logging.Log) List(java.util.List) Nullable(androidx.annotation.Nullable) OkHttpClient(okhttp3.OkHttpClient) Job(org.thoughtcrime.securesms.jobmanager.Job) BuildConfig(org.thoughtcrime.securesms.BuildConfig) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) IOException(java.io.IOException) Uri(android.net.Uri) Response(okhttp3.Response)

Example 17 with OkHttpClient

use of com.github.mjeanroy.junit.servers.client.impl.okhttp3.OkHttpClient in project mollyim-android by mollyim.

the class PushServiceSocket method makeStorageRequestResponse.

private Response makeStorageRequestResponse(String authorization, String path, String method, RequestBody body, ResponseCodeHandler responseCodeHandler) throws PushNetworkException, NonSuccessfulResponseCodeException {
    ConnectionHolder connectionHolder = getRandom(storageClients, random);
    OkHttpClient okHttpClient = connectionHolder.getClient().newBuilder().connectTimeout(soTimeoutMillis, TimeUnit.MILLISECONDS).readTimeout(soTimeoutMillis, TimeUnit.MILLISECONDS).build();
    // Log.d(TAG, "Opening URL: " + connectionHolder.getUrl());
    Request.Builder request = new Request.Builder().url(connectionHolder.getUrl() + path);
    request.method(method, body);
    if (connectionHolder.getHostHeader().isPresent()) {
        request.addHeader("Host", connectionHolder.getHostHeader().get());
    }
    if (authorization != null) {
        request.addHeader("Authorization", authorization);
    }
    Call call = okHttpClient.newCall(request.build());
    synchronized (connections) {
        connections.add(call);
    }
    Response response;
    try {
        response = call.execute();
        if (response.isSuccessful() && response.code() != 204) {
            return response;
        }
    } catch (IOException e) {
        throw new PushNetworkException(e);
    } finally {
        synchronized (connections) {
            connections.remove(call);
        }
    }
    ResponseBody responseBody = response.body();
    try {
        responseCodeHandler.handle(response.code(), responseBody);
        switch(response.code()) {
            case 204:
                throw new NoContentException("No content!");
            case 401:
            case 403:
                throw new AuthorizationFailedException(response.code(), "Authorization failed!");
            case 404:
                throw new NotFoundException("Not found");
            case 409:
                if (responseBody != null) {
                    throw new ContactManifestMismatchException(readBodyBytes(responseBody));
                } else {
                    throw new ConflictException();
                }
            case 429:
                throw new RateLimitException("Rate limit exceeded: " + response.code());
            case 499:
                throw new DeprecatedVersionException();
        }
        throw new NonSuccessfulResponseCodeException(response.code(), "Response: " + response);
    } catch (NonSuccessfulResponseCodeException | PushNetworkException e) {
        if (responseBody != null) {
            responseBody.close();
        }
        throw e;
    }
}
Also used : Call(okhttp3.Call) OkHttpClient(okhttp3.OkHttpClient) PushNetworkException(org.whispersystems.signalservice.api.push.exceptions.PushNetworkException) RateLimitException(org.whispersystems.signalservice.api.push.exceptions.RateLimitException) DeprecatedVersionException(org.whispersystems.signalservice.api.push.exceptions.DeprecatedVersionException) ConflictException(org.whispersystems.signalservice.api.push.exceptions.ConflictException) ReceiptCredentialRequest(org.signal.zkgroup.receipts.ReceiptCredentialRequest) Request(okhttp3.Request) ChangePhoneNumberRequest(org.whispersystems.signalservice.api.account.ChangePhoneNumberRequest) DiscoveryRequest(org.whispersystems.signalservice.internal.contacts.entities.DiscoveryRequest) KeyBackupRequest(org.whispersystems.signalservice.internal.contacts.entities.KeyBackupRequest) ProfileKeyCredentialRequest(org.signal.zkgroup.profiles.ProfileKeyCredentialRequest) GroupNotFoundException(org.whispersystems.signalservice.internal.push.exceptions.GroupNotFoundException) NotFoundException(org.whispersystems.signalservice.api.push.exceptions.NotFoundException) NonSuccessfulResponseCodeException(org.whispersystems.signalservice.api.push.exceptions.NonSuccessfulResponseCodeException) IOException(java.io.IOException) NoContentException(org.whispersystems.signalservice.api.push.exceptions.NoContentException) ResponseBody(okhttp3.ResponseBody) CallingResponse(org.whispersystems.signalservice.api.messages.calls.CallingResponse) Response(okhttp3.Response) KeyBackupResponse(org.whispersystems.signalservice.internal.contacts.entities.KeyBackupResponse) ReceiptCredentialResponse(org.signal.zkgroup.receipts.ReceiptCredentialResponse) CredentialResponse(org.whispersystems.signalservice.api.groupsv2.CredentialResponse) StorageAuthResponse(org.whispersystems.signalservice.api.storage.StorageAuthResponse) VerifyDeviceResponse(org.whispersystems.signalservice.api.messages.multidevice.VerifyDeviceResponse) DiscoveryResponse(org.whispersystems.signalservice.internal.contacts.entities.DiscoveryResponse) ProfileKeyCredentialResponse(org.signal.zkgroup.profiles.ProfileKeyCredentialResponse) TokenResponse(org.whispersystems.signalservice.internal.contacts.entities.TokenResponse) AuthorizationFailedException(org.whispersystems.signalservice.api.push.exceptions.AuthorizationFailedException) ContactManifestMismatchException(org.whispersystems.signalservice.api.push.exceptions.ContactManifestMismatchException)

Example 18 with OkHttpClient

use of com.github.mjeanroy.junit.servers.client.impl.okhttp3.OkHttpClient in project mollyim-android by mollyim.

the class PushServiceSocket method getResumeInfo.

private ResumeInfo getResumeInfo(String resumableUrl, long contentLength) throws IOException {
    ConnectionHolder connectionHolder = getRandom(cdnClientsMap.get(2), random);
    OkHttpClient okHttpClient = connectionHolder.getClient().newBuilder().connectTimeout(soTimeoutMillis, TimeUnit.MILLISECONDS).readTimeout(soTimeoutMillis, TimeUnit.MILLISECONDS).build();
    final long offset;
    final String contentRange;
    Request.Builder request = new Request.Builder().url(buildConfiguredUrl(connectionHolder, resumableUrl)).put(RequestBody.create(null, "")).addHeader("Content-Range", String.format(Locale.US, "bytes */%d", contentLength));
    if (connectionHolder.getHostHeader().isPresent()) {
        request.header("host", connectionHolder.getHostHeader().get());
    }
    Call call = okHttpClient.newCall(request.build());
    synchronized (connections) {
        connections.add(call);
    }
    try {
        Response response;
        try {
            response = call.execute();
        } catch (IOException e) {
            throw new PushNetworkException(e);
        }
        if (response.isSuccessful()) {
            offset = contentLength;
            contentRange = null;
        } else if (response.code() == 308) {
            String rangeCompleted = response.header("Range");
            if (rangeCompleted == null) {
                offset = 0;
            } else {
                offset = Long.parseLong(rangeCompleted.split("-")[1]) + 1;
            }
            contentRange = String.format(Locale.US, "bytes %d-%d/%d", offset, contentLength - 1, contentLength);
        } else if (response.code() == 404) {
            throw new ResumeLocationInvalidException();
        } else {
            throw new NonSuccessfulResumableUploadResponseCodeException(response.code(), "Response: " + response);
        }
    } finally {
        synchronized (connections) {
            connections.remove(call);
        }
    }
    return new ResumeInfo(contentRange, offset);
}
Also used : Call(okhttp3.Call) OkHttpClient(okhttp3.OkHttpClient) PushNetworkException(org.whispersystems.signalservice.api.push.exceptions.PushNetworkException) ReceiptCredentialRequest(org.signal.zkgroup.receipts.ReceiptCredentialRequest) Request(okhttp3.Request) ChangePhoneNumberRequest(org.whispersystems.signalservice.api.account.ChangePhoneNumberRequest) DiscoveryRequest(org.whispersystems.signalservice.internal.contacts.entities.DiscoveryRequest) KeyBackupRequest(org.whispersystems.signalservice.internal.contacts.entities.KeyBackupRequest) ProfileKeyCredentialRequest(org.signal.zkgroup.profiles.ProfileKeyCredentialRequest) GroupsV2AuthorizationString(org.whispersystems.signalservice.api.groupsv2.GroupsV2AuthorizationString) IOException(java.io.IOException) NonSuccessfulResumableUploadResponseCodeException(org.whispersystems.signalservice.api.push.exceptions.NonSuccessfulResumableUploadResponseCodeException) CallingResponse(org.whispersystems.signalservice.api.messages.calls.CallingResponse) Response(okhttp3.Response) KeyBackupResponse(org.whispersystems.signalservice.internal.contacts.entities.KeyBackupResponse) ReceiptCredentialResponse(org.signal.zkgroup.receipts.ReceiptCredentialResponse) CredentialResponse(org.whispersystems.signalservice.api.groupsv2.CredentialResponse) StorageAuthResponse(org.whispersystems.signalservice.api.storage.StorageAuthResponse) VerifyDeviceResponse(org.whispersystems.signalservice.api.messages.multidevice.VerifyDeviceResponse) DiscoveryResponse(org.whispersystems.signalservice.internal.contacts.entities.DiscoveryResponse) ProfileKeyCredentialResponse(org.signal.zkgroup.profiles.ProfileKeyCredentialResponse) TokenResponse(org.whispersystems.signalservice.internal.contacts.entities.TokenResponse) ResumeLocationInvalidException(org.whispersystems.signalservice.api.push.exceptions.ResumeLocationInvalidException)

Example 19 with OkHttpClient

use of com.github.mjeanroy.junit.servers.client.impl.okhttp3.OkHttpClient in project mollyim-android by mollyim.

the class PushServiceSocket method makeRequest.

private Response makeRequest(ConnectionHolder connectionHolder, String authorization, List<String> cookies, String path, String method, String body) throws PushNetworkException, NonSuccessfulResponseCodeException {
    OkHttpClient okHttpClient = connectionHolder.getClient().newBuilder().connectTimeout(soTimeoutMillis, TimeUnit.MILLISECONDS).readTimeout(soTimeoutMillis, TimeUnit.MILLISECONDS).build();
    Request.Builder request = new Request.Builder().url(connectionHolder.getUrl() + path);
    if (body != null) {
        request.method(method, RequestBody.create(MediaType.parse("application/json"), body));
    } else {
        request.method(method, null);
    }
    if (connectionHolder.getHostHeader().isPresent()) {
        request.addHeader("Host", connectionHolder.getHostHeader().get());
    }
    if (authorization != null) {
        request.addHeader("Authorization", authorization);
    }
    if (cookies != null && !cookies.isEmpty()) {
        request.addHeader("Cookie", Util.join(cookies, "; "));
    }
    Call call = okHttpClient.newCall(request.build());
    synchronized (connections) {
        connections.add(call);
    }
    Response response;
    try {
        response = call.execute();
        if (response.isSuccessful()) {
            return response;
        }
    } catch (IOException e) {
        throw new PushNetworkException(e);
    } finally {
        synchronized (connections) {
            connections.remove(call);
        }
    }
    switch(response.code()) {
        case 401:
        case 403:
            throw new AuthorizationFailedException(response.code(), "Authorization failed!");
        case 409:
            throw new RemoteAttestationResponseExpiredException("Remote attestation response expired");
        case 429:
            throw new RateLimitException("Rate limit exceeded: " + response.code());
    }
    throw new NonSuccessfulResponseCodeException(response.code(), "Response: " + response);
}
Also used : CallingResponse(org.whispersystems.signalservice.api.messages.calls.CallingResponse) Response(okhttp3.Response) KeyBackupResponse(org.whispersystems.signalservice.internal.contacts.entities.KeyBackupResponse) ReceiptCredentialResponse(org.signal.zkgroup.receipts.ReceiptCredentialResponse) CredentialResponse(org.whispersystems.signalservice.api.groupsv2.CredentialResponse) StorageAuthResponse(org.whispersystems.signalservice.api.storage.StorageAuthResponse) VerifyDeviceResponse(org.whispersystems.signalservice.api.messages.multidevice.VerifyDeviceResponse) DiscoveryResponse(org.whispersystems.signalservice.internal.contacts.entities.DiscoveryResponse) ProfileKeyCredentialResponse(org.signal.zkgroup.profiles.ProfileKeyCredentialResponse) TokenResponse(org.whispersystems.signalservice.internal.contacts.entities.TokenResponse) Call(okhttp3.Call) OkHttpClient(okhttp3.OkHttpClient) PushNetworkException(org.whispersystems.signalservice.api.push.exceptions.PushNetworkException) RateLimitException(org.whispersystems.signalservice.api.push.exceptions.RateLimitException) AuthorizationFailedException(org.whispersystems.signalservice.api.push.exceptions.AuthorizationFailedException) ReceiptCredentialRequest(org.signal.zkgroup.receipts.ReceiptCredentialRequest) Request(okhttp3.Request) ChangePhoneNumberRequest(org.whispersystems.signalservice.api.account.ChangePhoneNumberRequest) DiscoveryRequest(org.whispersystems.signalservice.internal.contacts.entities.DiscoveryRequest) KeyBackupRequest(org.whispersystems.signalservice.internal.contacts.entities.KeyBackupRequest) ProfileKeyCredentialRequest(org.signal.zkgroup.profiles.ProfileKeyCredentialRequest) NonSuccessfulResponseCodeException(org.whispersystems.signalservice.api.push.exceptions.NonSuccessfulResponseCodeException) IOException(java.io.IOException) RemoteAttestationResponseExpiredException(org.whispersystems.signalservice.api.push.exceptions.RemoteAttestationResponseExpiredException)

Example 20 with OkHttpClient

use of com.github.mjeanroy.junit.servers.client.impl.okhttp3.OkHttpClient in project mollyim-android by mollyim.

the class PushServiceSocket method uploadToCdn0.

private byte[] uploadToCdn0(String path, String acl, String key, String policy, String algorithm, String credential, String date, String signature, InputStream data, String contentType, long length, OutputStreamFactory outputStreamFactory, ProgressListener progressListener, CancelationSignal cancelationSignal) throws PushNetworkException, NonSuccessfulResponseCodeException {
    ConnectionHolder connectionHolder = getRandom(cdnClientsMap.get(0), random);
    OkHttpClient okHttpClient = connectionHolder.getClient().newBuilder().connectTimeout(soTimeoutMillis, TimeUnit.MILLISECONDS).readTimeout(soTimeoutMillis, TimeUnit.MILLISECONDS).build();
    DigestingRequestBody file = new DigestingRequestBody(data, outputStreamFactory, contentType, length, progressListener, cancelationSignal, 0);
    RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("acl", acl).addFormDataPart("key", key).addFormDataPart("policy", policy).addFormDataPart("Content-Type", contentType).addFormDataPart("x-amz-algorithm", algorithm).addFormDataPart("x-amz-credential", credential).addFormDataPart("x-amz-date", date).addFormDataPart("x-amz-signature", signature).addFormDataPart("file", "file", file).build();
    Request.Builder request = new Request.Builder().url(connectionHolder.getUrl() + "/" + path).post(requestBody);
    if (connectionHolder.getHostHeader().isPresent()) {
        request.addHeader("Host", connectionHolder.getHostHeader().get());
    }
    Call call = okHttpClient.newCall(request.build());
    synchronized (connections) {
        connections.add(call);
    }
    try {
        Response response;
        try {
            response = call.execute();
        } catch (IOException e) {
            throw new PushNetworkException(e);
        }
        if (response.isSuccessful())
            return file.getTransmittedDigest();
        else
            throw new NonSuccessfulResponseCodeException(response.code(), "Response: " + response);
    } finally {
        synchronized (connections) {
            connections.remove(call);
        }
    }
}
Also used : Call(okhttp3.Call) OkHttpClient(okhttp3.OkHttpClient) PushNetworkException(org.whispersystems.signalservice.api.push.exceptions.PushNetworkException) DigestingRequestBody(org.whispersystems.signalservice.internal.push.http.DigestingRequestBody) ReceiptCredentialRequest(org.signal.zkgroup.receipts.ReceiptCredentialRequest) Request(okhttp3.Request) ChangePhoneNumberRequest(org.whispersystems.signalservice.api.account.ChangePhoneNumberRequest) DiscoveryRequest(org.whispersystems.signalservice.internal.contacts.entities.DiscoveryRequest) KeyBackupRequest(org.whispersystems.signalservice.internal.contacts.entities.KeyBackupRequest) ProfileKeyCredentialRequest(org.signal.zkgroup.profiles.ProfileKeyCredentialRequest) NonSuccessfulResponseCodeException(org.whispersystems.signalservice.api.push.exceptions.NonSuccessfulResponseCodeException) IOException(java.io.IOException) CallingResponse(org.whispersystems.signalservice.api.messages.calls.CallingResponse) Response(okhttp3.Response) KeyBackupResponse(org.whispersystems.signalservice.internal.contacts.entities.KeyBackupResponse) ReceiptCredentialResponse(org.signal.zkgroup.receipts.ReceiptCredentialResponse) CredentialResponse(org.whispersystems.signalservice.api.groupsv2.CredentialResponse) StorageAuthResponse(org.whispersystems.signalservice.api.storage.StorageAuthResponse) VerifyDeviceResponse(org.whispersystems.signalservice.api.messages.multidevice.VerifyDeviceResponse) DiscoveryResponse(org.whispersystems.signalservice.internal.contacts.entities.DiscoveryResponse) ProfileKeyCredentialResponse(org.signal.zkgroup.profiles.ProfileKeyCredentialResponse) TokenResponse(org.whispersystems.signalservice.internal.contacts.entities.TokenResponse) MultipartBody(okhttp3.MultipartBody) DigestingRequestBody(org.whispersystems.signalservice.internal.push.http.DigestingRequestBody) RequestBody(okhttp3.RequestBody)

Aggregations

OkHttpClient (okhttp3.OkHttpClient)1944 Request (okhttp3.Request)1024 Response (okhttp3.Response)880 IOException (java.io.IOException)567 Test (org.junit.Test)365 Call (okhttp3.Call)290 RequestBody (okhttp3.RequestBody)222 Test (org.junit.jupiter.api.Test)145 Retrofit (retrofit2.Retrofit)138 File (java.io.File)132 HttpUrl (okhttp3.HttpUrl)131 HttpLoggingInterceptor (okhttp3.logging.HttpLoggingInterceptor)128 Callback (okhttp3.Callback)117 JSONObject (org.json.JSONObject)110 ArrayList (java.util.ArrayList)106 ResponseBody (okhttp3.ResponseBody)105 Gson (com.google.gson.Gson)98 MediaType (okhttp3.MediaType)98 List (java.util.List)92 Map (java.util.Map)85