org.whispersystems.signalservice.api.push.exceptions.NonSuccessfulResponseCodeException Java Examples

The following examples show how to use org.whispersystems.signalservice.api.push.exceptions.NonSuccessfulResponseCodeException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SignalServiceMessageReceiver.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
public ProfileAndCredential retrieveProfile(SignalServiceAddress address,
                                            Optional<ProfileKey> profileKey,
                                            Optional<UnidentifiedAccess> unidentifiedAccess,
                                            SignalServiceProfile.RequestType requestType)
    throws NonSuccessfulResponseCodeException, PushNetworkException, VerificationFailedException
{
  Optional<UUID> uuid = address.getUuid();

  if (uuid.isPresent() && profileKey.isPresent()) {
    if (requestType == SignalServiceProfile.RequestType.PROFILE_AND_CREDENTIAL) {
      return socket.retrieveVersionedProfileAndCredential(uuid.get(), profileKey.get(), unidentifiedAccess);
    } else {
      return new ProfileAndCredential(socket.retrieveVersionedProfile(uuid.get(), profileKey.get(), unidentifiedAccess),
                                      SignalServiceProfile.RequestType.PROFILE,
                                      Optional.absent());
    }
  } else {
    return new ProfileAndCredential(socket.retrieveProfile(address, unidentifiedAccess),
                                    SignalServiceProfile.RequestType.PROFILE,
                                    Optional.absent());
  }
}
 
Example #2
Source File: PushServiceSocket.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
public void requestSmsVerificationCode(boolean androidSmsRetriever, Optional<String> captchaToken, Optional<String> challenge) throws IOException {
  String path = String.format(CREATE_ACCOUNT_SMS_PATH, credentialsProvider.getE164(), androidSmsRetriever ? "android-ng" : "android");

  if (captchaToken.isPresent()) {
    path += "&captcha=" + captchaToken.get();
  } else if (challenge.isPresent()) {
    path += "&challenge=" + challenge.get();
  }

  makeServiceRequest(path, "GET", null, NO_HEADERS, new ResponseCodeHandler() {
    @Override
    public void handle(int responseCode) throws NonSuccessfulResponseCodeException {
      if (responseCode == 402) {
        throw new CaptchaRequiredException();
      }
    }
  });
}
 
Example #3
Source File: PushServiceSocket.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
public void requestVoiceVerificationCode(Locale locale, Optional<String> captchaToken, Optional<String> challenge) throws IOException {
  Map<String, String> headers = locale != null ? Collections.singletonMap("Accept-Language", locale.getLanguage() + "-" + locale.getCountry()) : NO_HEADERS;
  String              path    = String.format(CREATE_ACCOUNT_VOICE_PATH, credentialsProvider.getE164());

  if (captchaToken.isPresent()) {
    path += "?captcha=" + captchaToken.get();
  } else if (challenge.isPresent()) {
    path += "?challenge=" + challenge.get();
  }

  makeServiceRequest(path, "GET", null, headers, new ResponseCodeHandler() {
    @Override
    public void handle(int responseCode) throws NonSuccessfulResponseCodeException {
      if (responseCode == 402) {
        throw new CaptchaRequiredException();
      }
    }
  });
}
 
Example #4
Source File: AttachmentDownloadJob.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
private void retrieveAttachment(long messageId,
                                final AttachmentId attachmentId,
                                final Attachment attachment)
    throws IOException
{

  AttachmentDatabase database       = DatabaseFactory.getAttachmentDatabase(context);
  File               attachmentFile = database.getOrCreateTransferFile(attachmentId);

  try {
    SignalServiceMessageReceiver   messageReceiver = ApplicationDependencies.getSignalServiceMessageReceiver();
    SignalServiceAttachmentPointer pointer         = createAttachmentPointer(attachment);
    InputStream                    stream          = messageReceiver.retrieveAttachment(pointer, attachmentFile, MAX_ATTACHMENT_SIZE, (total, progress) -> EventBus.getDefault().postSticky(new PartProgressEvent(attachment, PartProgressEvent.Type.NETWORK, total, progress)));

    database.insertAttachmentsForPlaceholder(messageId, attachmentId, stream);
  } catch (InvalidPartException | NonSuccessfulResponseCodeException | InvalidMessageException | MmsException | MissingConfigurationException e) {
    Log.w(TAG, "Experienced exception while trying to download an attachment.", e);
    markFailed(messageId, attachmentId);
  }
}
 
Example #5
Source File: PushServiceSocket.java    From libsignal-service-java with GNU General Public License v3.0 6 votes vote down vote up
public Pair<RemoteAttestationResponse, List<String>> getContactDiscoveryRemoteAttestation(String authorization, RemoteAttestationRequest request, String mrenclave)
    throws IOException
{
  Response     response   = makeContactDiscoveryRequest(authorization, new LinkedList<String>(), "/v1/attestation/" + mrenclave, "PUT", JsonUtil.toJson(request));
  ResponseBody body       = response.body();
  List<String> rawCookies = response.headers("Set-Cookie");
  List<String> cookies    = new LinkedList<>();

  for (String cookie : rawCookies) {
    cookies.add(cookie.split(";")[0]);
  }

  if (body != null) {
    return new Pair<>(JsonUtil.fromJson(body.string(), RemoteAttestationResponse.class), cookies);
  } else {
    throw new NonSuccessfulResponseCodeException("Empty response!");
  }
}
 
Example #6
Source File: ProfileUtil.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
@WorkerThread
public static @NonNull ProfileAndCredential retrieveProfile(@NonNull Context context,
                                                            @NonNull Recipient recipient,
                                                            @NonNull SignalServiceProfile.RequestType requestType)
  throws IOException
{
  SignalServiceAddress         address            = RecipientUtil.toSignalServiceAddress(context, recipient);
  Optional<UnidentifiedAccess> unidentifiedAccess = getUnidentifiedAccess(context, recipient);
  Optional<ProfileKey>         profileKey         = ProfileKeyUtil.profileKeyOptional(recipient.getProfileKey());

  ProfileAndCredential profile;

  try {
    profile = retrieveProfileInternal(address, profileKey, unidentifiedAccess, requestType);
  } catch (NonSuccessfulResponseCodeException e) {
    if (unidentifiedAccess.isPresent()) {
      profile = retrieveProfileInternal(address, profileKey, Optional.absent(), requestType);
    } else {
      throw e;
    }
  }

  return profile;
}
 
Example #7
Source File: RemoteAttestationUtil.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
private static Pair<RemoteAttestationResponse, List<String>> getRemoteAttestation(PushServiceSocket socket,
                                                                                  PushServiceSocket.ClientSet clientSet,
                                                                                  String authorization,
                                                                                  RemoteAttestationRequest request,
                                                                                  String enclaveName)
  throws IOException
{
  Response response       = socket.makeRequest(clientSet, authorization, new LinkedList<String>(), "/v1/attestation/" + enclaveName, "PUT", JsonUtil.toJson(request));
  ResponseBody body       = response.body();
  List<String> rawCookies = response.headers("Set-Cookie");
  List<String> cookies    = new LinkedList<>();

  for (String cookie : rawCookies) {
    cookies.add(cookie.split(";")[0]);
  }

  if (body != null) {
    return new Pair<>(JsonUtil.fromJson(body.string(), RemoteAttestationResponse.class), cookies);
  } else {
    throw new NonSuccessfulResponseCodeException("Empty response!");
  }
}
 
Example #8
Source File: PushServiceSocket.java    From libsignal-service-java with GNU General Public License v3.0 6 votes vote down vote up
public void requestSmsVerificationCode(boolean androidSmsRetriever, Optional<String> captchaToken, Optional<String> challenge) throws IOException {
  String path = String.format(CREATE_ACCOUNT_SMS_PATH, credentialsProvider.getE164(), androidSmsRetriever ? "android-ng" : "android");

  if (captchaToken.isPresent()) {
    path += "&captcha=" + captchaToken.get();
  } else if (challenge.isPresent()) {
    path += "&challenge=" + challenge.get();
  }

  makeServiceRequest(path, "GET", null, NO_HEADERS, new ResponseCodeHandler() {
    @Override
    public void handle(int responseCode) throws NonSuccessfulResponseCodeException {
      if (responseCode == 402) {
        throw new CaptchaRequiredException();
      }
    }
  });
}
 
Example #9
Source File: PushServiceSocket.java    From libsignal-service-java with GNU General Public License v3.0 6 votes vote down vote up
public void requestVoiceVerificationCode(Locale locale, Optional<String> captchaToken, Optional<String> challenge) throws IOException {
  Map<String, String> headers = locale != null ? Collections.singletonMap("Accept-Language", locale.getLanguage() + "-" + locale.getCountry()) : NO_HEADERS;
  String              path    = String.format(CREATE_ACCOUNT_VOICE_PATH, credentialsProvider.getE164());

  if (captchaToken.isPresent()) {
    path += "?captcha=" + captchaToken.get();
  } else if (challenge.isPresent()) {
    path += "?challenge=" + challenge.get();
  }
  
  makeServiceRequest(path, "GET", null, headers, new ResponseCodeHandler() {
    @Override
    public void handle(int responseCode) throws NonSuccessfulResponseCodeException {
      if (responseCode == 402) {
        throw new CaptchaRequiredException();
      }
    }
  });
}
 
Example #10
Source File: PushServiceSocket.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
public ProfileAndCredential retrieveVersionedProfileAndCredential(UUID target, ProfileKey profileKey, Optional<UnidentifiedAccess> unidentifiedAccess)
    throws NonSuccessfulResponseCodeException, PushNetworkException, VerificationFailedException
{
  ProfileKeyVersion                  profileKeyIdentifier = profileKey.getProfileKeyVersion(target);
  ProfileKeyCredentialRequestContext requestContext       = clientZkProfileOperations.createProfileKeyCredentialRequestContext(random, target, profileKey);
  ProfileKeyCredentialRequest        request              = requestContext.getRequest();

  String version           = profileKeyIdentifier.serialize();
  String credentialRequest = Hex.toStringCondensed(request.serialize());
  String subPath           = String.format("%s/%s/%s", target, version, credentialRequest);

  String response = makeServiceRequest(String.format(PROFILE_PATH, subPath), "GET", null, NO_HEADERS, unidentifiedAccess);

  try {
    SignalServiceProfile signalServiceProfile = JsonUtil.fromJson(response, SignalServiceProfile.class);

    ProfileKeyCredential profileKeyCredential = signalServiceProfile.getProfileKeyCredentialResponse() != null
                                              ? clientZkProfileOperations.receiveProfileKeyCredential(requestContext, signalServiceProfile.getProfileKeyCredentialResponse())
                                              : null;

    return new ProfileAndCredential(signalServiceProfile, SignalServiceProfile.RequestType.PROFILE_AND_CREDENTIAL, Optional.fromNullable(profileKeyCredential));
  } catch (IOException e) {
    Log.w(TAG, e);
    throw new NonSuccessfulResponseCodeException("Unable to parse entity");
  }
}
 
Example #11
Source File: PushServiceSocket.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
public SignalServiceProfile retrieveVersionedProfile(UUID target, ProfileKey profileKey, Optional<UnidentifiedAccess> unidentifiedAccess)
    throws NonSuccessfulResponseCodeException, PushNetworkException
{
  ProfileKeyVersion profileKeyIdentifier = profileKey.getProfileKeyVersion(target);

  String version = profileKeyIdentifier.serialize();
  String subPath = String.format("%s/%s", target, version);

  String response = makeServiceRequest(String.format(PROFILE_PATH, subPath), "GET", null, NO_HEADERS, unidentifiedAccess);

  try {
    return JsonUtil.fromJson(response, SignalServiceProfile.class);
  } catch (IOException e) {
    Log.w(TAG, e);
    throw new NonSuccessfulResponseCodeException("Unable to parse entity");
  }
}
 
Example #12
Source File: PushServiceSocket.java    From libsignal-service-java with GNU General Public License v3.0 6 votes vote down vote up
public void setProfileAvatar(ProfileAvatarData profileAvatar)
    throws NonSuccessfulResponseCodeException, PushNetworkException
{
  String                        response       = makeServiceRequest(String.format(PROFILE_PATH, "form/avatar"), "GET", null);
  ProfileAvatarUploadAttributes formAttributes;

  try {
    formAttributes = JsonUtil.fromJson(response, ProfileAvatarUploadAttributes.class);
  } catch (IOException e) {
    Log.w(TAG, e);
    throw new NonSuccessfulResponseCodeException("Unable to parse entity");
  }

  if (profileAvatar != null) {
    uploadToCdn("", formAttributes.getAcl(), formAttributes.getKey(),
                formAttributes.getPolicy(), formAttributes.getAlgorithm(),
                formAttributes.getCredential(), formAttributes.getDate(),
                formAttributes.getSignature(), profileAvatar.getData(),
                profileAvatar.getContentType(), profileAvatar.getDataLength(),
                profileAvatar.getOutputStreamFactory(), null);
  }
}
 
Example #13
Source File: PushServiceSocket.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
private String makeServiceRequest(String urlFragment, String method, String jsonBody, Map<String, String> headers, ResponseCodeHandler responseCodeHandler, Optional<UnidentifiedAccess> unidentifiedAccessKey)
    throws NonSuccessfulResponseCodeException, PushNetworkException
{
  ResponseBody responseBody = makeServiceBodyRequest(urlFragment, method, jsonRequestBody(jsonBody), headers, responseCodeHandler, unidentifiedAccessKey);
  try {
    return responseBody.string();
  } catch (IOException e) {
    throw new PushNetworkException(e);
  }
}
 
Example #14
Source File: PushServiceSocket.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
public void putNewGroupsV2Group(Group group, GroupsV2AuthorizationString authorization)
    throws NonSuccessfulResponseCodeException, PushNetworkException
{
    makeStorageRequest(authorization.toString(),
                       GROUPSV2_GROUP,
                       "PUT",
                       protobufRequestBody(group),
                       GROUPS_V2_PUT_RESPONSE_HANDLER);
}
 
Example #15
Source File: PushServiceSocket.java    From libsignal-service-java with GNU General Public License v3.0 5 votes vote down vote up
public AttachmentUploadAttributes getAttachmentUploadAttributes() throws NonSuccessfulResponseCodeException, PushNetworkException {
  String response = makeServiceRequest(ATTACHMENT_PATH, "GET", null);
  try {
    return JsonUtil.fromJson(response, AttachmentUploadAttributes.class);
  } catch (IOException e) {
    Log.w(TAG, e);
    throw new NonSuccessfulResponseCodeException("Unable to parse entity");
  }
}
 
Example #16
Source File: PushServiceSocket.java    From libsignal-service-java with GNU General Public License v3.0 5 votes vote down vote up
public Pair<Long, byte[]> uploadAttachment(PushAttachmentData attachment, AttachmentUploadAttributes uploadAttributes)
    throws PushNetworkException, NonSuccessfulResponseCodeException
{
  long   id     = Long.parseLong(uploadAttributes.getAttachmentId());
  byte[] digest = uploadToCdn(ATTACHMENT_UPLOAD_PATH, uploadAttributes.getAcl(), uploadAttributes.getKey(),
                              uploadAttributes.getPolicy(), uploadAttributes.getAlgorithm(),
                              uploadAttributes.getCredential(), uploadAttributes.getDate(),
                              uploadAttributes.getSignature(), attachment.getData(),
                              "application/octet-stream", attachment.getDataSize(),
                              attachment.getOutputStreamFactory(), attachment.getListener());

  return new Pair<>(id, digest);
}
 
Example #17
Source File: PushServiceSocket.java    From libsignal-service-java with GNU General Public License v3.0 5 votes vote down vote up
private void downloadFromCdn(File destination, String path, int maxSizeBytes, ProgressListener listener)
    throws PushNetworkException, NonSuccessfulResponseCodeException
{
  try (FileOutputStream outputStream = new FileOutputStream(destination)) {
    downloadFromCdn(outputStream, path, maxSizeBytes, listener);
  } catch (IOException e) {
    throw new PushNetworkException(e);
  }
}
 
Example #18
Source File: PushServiceSocket.java    From libsignal-service-java with GNU General Public License v3.0 5 votes vote down vote up
public byte[] retrieveStickerManifest(byte[] packId)
    throws NonSuccessfulResponseCodeException, PushNetworkException
{
  String                hexPackId = Hex.toStringCondensed(packId);
  ByteArrayOutputStream output    = new ByteArrayOutputStream();

  downloadFromCdn(output, String.format(STICKER_MANIFEST_PATH, hexPackId), 1024 * 1024, null);

  return output.toByteArray();
}
 
Example #19
Source File: RefreshPreKeysJob.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean onShouldRetryThrowable(Exception exception) {
    if (exception instanceof NonSuccessfulResponseCodeException) return false;
    if (exception instanceof PushNetworkException) return true;

    return false;
}
 
Example #20
Source File: PushServiceSocket.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
public void setProfileName(String name) throws NonSuccessfulResponseCodeException, PushNetworkException {
  if (FeatureFlags.DISALLOW_OLD_PROFILE_SETTING) {
    throw new AssertionError();
  }

  makeServiceRequest(String.format(PROFILE_PATH, "name/" + (name == null ? "" : URLEncoder.encode(name))), "PUT", "");
}
 
Example #21
Source File: PushServiceSocket.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
Response makeRequest(ClientSet clientSet, String authorization, List<String> cookies, String path, String method, String body)
    throws PushNetworkException, NonSuccessfulResponseCodeException
{
  ConnectionHolder connectionHolder = getRandom(clientsFor(clientSet), random);

  return makeRequest(connectionHolder, authorization, cookies, path, method, body);
}
 
Example #22
Source File: PushServiceSocket.java    From libsignal-service-java with GNU General Public License v3.0 5 votes vote down vote up
public DiscoveryResponse getContactDiscoveryRegisteredUsers(String authorizationToken, DiscoveryRequest request, List<String> cookies, String mrenclave)
    throws IOException
{
  ResponseBody body = makeContactDiscoveryRequest(authorizationToken, cookies, "/v1/discovery/" + mrenclave, "PUT", JsonUtil.toJson(request)).body();

  if (body != null) {
    return JsonUtil.fromJson(body.string(), DiscoveryResponse.class);
  } else {
    throw new NonSuccessfulResponseCodeException("Empty response!");
  }
}
 
Example #23
Source File: PushServiceSocket.java    From libsignal-service-java with GNU General Public License v3.0 5 votes vote down vote up
public List<ContactTokenDetails> retrieveDirectory(Set<String> contactTokens)
    throws NonSuccessfulResponseCodeException, PushNetworkException
{
  try {
    ContactTokenList        contactTokenList = new ContactTokenList(new LinkedList<>(contactTokens));
    String                  response         = makeServiceRequest(DIRECTORY_TOKENS_PATH, "PUT", JsonUtil.toJson(contactTokenList));
    ContactTokenDetailsList activeTokens     = JsonUtil.fromJson(response, ContactTokenDetailsList.class);

    return activeTokens.getContacts();
  } catch (IOException e) {
    Log.w(TAG, e);
    throw new NonSuccessfulResponseCodeException("Unable to parse entity");
  }
}
 
Example #24
Source File: PushServiceSocket.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
private void downloadFromCdn(File destination, int cdnNumber, String path, long maxSizeBytes, ProgressListener listener)
    throws PushNetworkException, NonSuccessfulResponseCodeException, MissingConfigurationException {
  try (FileOutputStream outputStream = new FileOutputStream(destination, true)) {
    downloadFromCdn(outputStream, destination.length(), cdnNumber, path, maxSizeBytes, listener);
  } catch (IOException e) {
    throw new PushNetworkException(e);
  }
}
 
Example #25
Source File: PushServiceSocket.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
public Group getGroupsV2Group(GroupsV2AuthorizationString authorization)
    throws NonSuccessfulResponseCodeException, PushNetworkException, InvalidProtocolBufferException
{
    ResponseBody response = makeStorageRequest(authorization.toString(),
                                               GROUPSV2_GROUP,
                                               "GET",
                                               null,
                                               GROUPS_V2_GET_CURRENT_HANDLER);

  return Group.parseFrom(readBodyBytes(response));
}
 
Example #26
Source File: PushServiceSocket.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
public AvatarUploadAttributes getGroupsV2AvatarUploadForm(String authorization)
    throws NonSuccessfulResponseCodeException, PushNetworkException, InvalidProtocolBufferException
{
    ResponseBody response = makeStorageRequest(authorization,
                                               GROUPSV2_AVATAR_REQUEST,
                                               "GET",
                                               null,
                                               NO_HANDLER);

  return AvatarUploadAttributes.parseFrom(readBodyBytes(response));
}
 
Example #27
Source File: PushServiceSocket.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
public GroupChange patchGroupsV2Group(GroupChange.Actions groupChange, String authorization)
    throws NonSuccessfulResponseCodeException, PushNetworkException, InvalidProtocolBufferException
{
  ResponseBody response = makeStorageRequest(authorization,
                                             GROUPSV2_GROUP,
                                             "PATCH",
                                             protobufRequestBody(groupChange),
                                             GROUPS_V2_PATCH_RESPONSE_HANDLER);

  return GroupChange.parseFrom(readBodyBytes(response));
}
 
Example #28
Source File: PushServiceSocket.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
public GroupChanges getGroupsV2GroupHistory(int fromVersion, GroupsV2AuthorizationString authorization)
  throws NonSuccessfulResponseCodeException, PushNetworkException, InvalidProtocolBufferException
{
  ResponseBody response = makeStorageRequest(authorization.toString(),
                                             String.format(Locale.US, GROUPSV2_GROUP_CHANGES, fromVersion),
                                             "GET",
                                             null,
                                             GROUPS_V2_GET_LOGS_HANDLER);

  return GroupChanges.parseFrom(readBodyBytes(response));
}
 
Example #29
Source File: PushServiceSocket.java    From libsignal-service-java with GNU General Public License v3.0 5 votes vote down vote up
public SignalServiceProfile retrieveProfile(SignalServiceAddress target, Optional<UnidentifiedAccess> unidentifiedAccess)
    throws NonSuccessfulResponseCodeException, PushNetworkException
{
  try {
    String response = makeServiceRequest(String.format(PROFILE_PATH, target.getIdentifier()), "GET", null, NO_HEADERS, unidentifiedAccess);
    return JsonUtil.fromJson(response, SignalServiceProfile.class);
  } catch (IOException e) {
    Log.w(TAG, e);
    throw new NonSuccessfulResponseCodeException("Unable to parse entity");
  }
}
 
Example #30
Source File: RefreshPreKeysJob.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean onShouldRetry(@NonNull Exception exception) {
  if (exception instanceof NonSuccessfulResponseCodeException) return false;
  if (exception instanceof PushNetworkException)               return true;

  return false;
}