Skip to content

Commit

Permalink
More bug fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
Auties00 committed Sep 22, 2023
1 parent 5ba0b97 commit 9c0cd3b
Show file tree
Hide file tree
Showing 21 changed files with 180 additions and 126 deletions.
6 changes: 0 additions & 6 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,6 @@
<sl4j.version>2.0.7</sl4j.version>
<log4j.version>2.20.0</log4j.version>
<maven.versions.version>2.15.0</maven.versions.version>
<dsl-json.version>2.0.2</dsl-json.version>
</properties>

<build>
Expand Down Expand Up @@ -242,11 +241,6 @@
<artifactId>bcprov-jdk15on</artifactId>
<version>${bouncy.castle.version}</version>
</dependency>
<dependency>
<groupId>com.dslplatform</groupId>
<artifactId>dsl-json</artifactId>
<version>${dsl-json.version}</version>
</dependency>
<dependency>
<groupId>com.github.auties00</groupId>
<artifactId>protobuf-base</artifactId>
Expand Down
11 changes: 10 additions & 1 deletion src/main/java/it/auties/whatsapp/api/Whatsapp.java
Original file line number Diff line number Diff line change
Expand Up @@ -432,6 +432,7 @@ public CompletableFuture<MessageInfo> sendReaction(@NonNull MessageMetadataProvi
*/
public CompletableFuture<MessageInfo> sendReaction(@NonNull MessageMetadataProvider message, String reaction) {
var key = new MessageKeyBuilder()
.id(MessageKey.randomId())
.chatJid(message.chatJid())
.senderJid(message.senderJid())
.fromMe(Objects.equals(message.senderJid().toWhatsappJid(), jidOrThrowError().toWhatsappJid()))
Expand Down Expand Up @@ -476,11 +477,13 @@ public CompletableFuture<MessageInfo> sendMessage(@NonNull ContactJidProvider ch
*/
public CompletableFuture<MessageInfo> sendMessage(@NonNull ContactJidProvider chat, @NonNull MessageContainer message) {
var key = new MessageKeyBuilder()
.id(MessageKey.randomId())
.chatJid(chat.toJid())
.fromMe(true)
.senderJid(jidOrThrowError())
.build();
var info = new MessageInfoBuilder()
.status(MessageStatus.PENDING)
.senderJid(jidOrThrowError())
.key(key)
.message(message)
Expand Down Expand Up @@ -1658,8 +1661,14 @@ public CompletableFuture<MessageInfo> delete(@NonNull MessageInfo info, boolean
.key(info.key())
.build();
var sender = info.chatJid().hasServer(ContactJidServer.GROUP) ? jidOrThrowError() : null;
var key = new MessageKeyBuilder().chatJid(info.chatJid()).fromMe(true).senderJid(sender).build();
var key = new MessageKeyBuilder()
.id(MessageKey.randomId())
.chatJid(info.chatJid())
.fromMe(true)
.senderJid(sender)
.build();
var revokeInfo = new MessageInfoBuilder()
.status(MessageStatus.PENDING)
.senderJid(sender)
.key(key)
.message(MessageContainer.of(message))
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/it/auties/whatsapp/controller/Store.java
Original file line number Diff line number Diff line change
Expand Up @@ -414,7 +414,7 @@ public Store(
this.requests = Objects.requireNonNullElseGet(requests, ConcurrentHashMap::new);
this.replyHandlers = Objects.requireNonNullElseGet(replyHandlers, ConcurrentHashMap::new);
this.tag = Objects.requireNonNullElseGet(tag, () -> HexFormat.of().formatHex(BytesHelper.random(1)));
this.initializationTimeStamp = Objects.requireNonNullElseGet(initializationTimeStamp, Clock::nowMilliseconds);
this.initializationTimeStamp = Objects.requireNonNullElseGet(initializationTimeStamp, Clock::nowSeconds);
this.mediaConnection = mediaConnection;
this.mediaConnectionLatch = new CountDownLatch(1);
this.newChatsEphemeralTimer = Objects.requireNonNullElse(newChatsEphemeralTimer, ChatEphemeralTimer.OFF);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package it.auties.whatsapp.model.info;

import com.fasterxml.jackson.core.type.TypeReference;
import it.auties.whatsapp.model.contact.ContactJid;
import it.auties.whatsapp.util.Json;
import org.checkerframework.checker.nullness.qual.NonNull;
Expand Down Expand Up @@ -37,7 +38,7 @@ public static MessageIndexInfo of(@NonNull String type, ContactJid chatJid, Stri
* @return a non-null index info
*/
public static MessageIndexInfo ofJson(@NonNull String json) {
var array = Json.readList(json, String.class);
var array = Json.readValue(json, new TypeReference<List<String>>() {});
var type = getProperty(array, 0).orElseThrow(() -> new NoSuchElementException("Cannot parse MessageSync: missing type"));
var chatJid = getProperty(array, 1).map(ContactJid::of);
var messageId = getProperty(array, 2);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import org.checkerframework.checker.nullness.qual.Nullable;

import java.util.HexFormat;
import java.util.Locale;
import java.util.Objects;
import java.util.Optional;

Expand All @@ -32,10 +33,10 @@ public final class MessageKey implements ProtobufMessage {
private @Nullable ContactJid senderJid;

@JsonCreator(mode = JsonCreator.Mode.PROPERTIES)
public MessageKey(@NonNull ContactJid chatJid, boolean fromMe, @NonNull String id, @Nullable ContactJid senderJid) {
public MessageKey(@NonNull ContactJid chatJid, boolean fromMe, @Nullable String id, @Nullable ContactJid senderJid) {
this.chatJid = chatJid;
this.fromMe = fromMe;
this.id = id;
this.id = Objects.requireNonNull(id, MessageKey::randomId);
this.senderJid = senderJid;
}

Expand All @@ -54,7 +55,8 @@ public MessageKey(@NonNull ContactJid chatJid, boolean fromMe, @Nullable Contact
*/
public static String randomId() {
return HexFormat.of()
.formatHex(BytesHelper.random(5));
.formatHex(BytesHelper.random(8))
.toUpperCase(Locale.ROOT);
}

public @NonNull ContactJid chatJid() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,7 @@
import org.checkerframework.checker.nullness.qual.Nullable;

import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.OptionalLong;
import java.util.*;

/**
* A model that represents the receipt for a message
Expand All @@ -30,18 +27,18 @@ public final class MessageReceipt implements ProtobufMessage {
private Long playedTimestampSeconds;
@ProtobufProperty(index = 5, type = ProtobufType.STRING, repeated = true)
@NonNull
private final List<ContactJid> deliveredJids;
private final Set<ContactJid> deliveredJids;
@ProtobufProperty(index = 6, type = ProtobufType.STRING, repeated = true)
@NonNull
private final List<ContactJid> readJids;
private final Set<ContactJid> readJids;

public MessageReceipt() {
this.deliveredJids = new ArrayList<>();
this.readJids = new ArrayList<>();
this.deliveredJids = new HashSet<>();
this.readJids = new HashSet<>();
}

@JsonCreator(mode = JsonCreator.Mode.PROPERTIES)
public MessageReceipt(@Nullable Long deliveredTimestampSeconds, @Nullable Long readTimestampSeconds, @Nullable Long playedTimestampSeconds, @NonNull List<ContactJid> deliveredJids, @NonNull List<ContactJid> readJids) {
public MessageReceipt(@Nullable Long deliveredTimestampSeconds, @Nullable Long readTimestampSeconds, @Nullable Long playedTimestampSeconds, @NonNull Set<ContactJid> deliveredJids, @NonNull Set<ContactJid> readJids) {
this.deliveredTimestampSeconds = deliveredTimestampSeconds;
this.readTimestampSeconds = readTimestampSeconds;
this.playedTimestampSeconds = playedTimestampSeconds;
Expand Down Expand Up @@ -88,11 +85,11 @@ public Optional<ZonedDateTime> playedTimestamp() {
return Clock.parseSeconds(playedTimestampSeconds);
}

public List<ContactJid> deliveredJids() {
public Set<ContactJid> deliveredJids() {
return deliveredJids;
}

public List<ContactJid> readJids() {
public Set<ContactJid> readJids() {
return readJids;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
package it.auties.whatsapp.model.mobile;

import com.fasterxml.jackson.annotation.JsonCreator;

import java.util.Arrays;

public enum VerificationCodeError {
NETWORK_ERROR("network_error"),
GENERAL_ERROR("error"),
Expand All @@ -23,15 +27,23 @@ public enum VerificationCodeError {
NEXT_METHOD("next_method"),
WRONG_CODE("mismatch"),
OLD_VERSION("old_version"),

CAPTCHA("code_checkpoint");
CAPTCHA("code_checkpoint"),
INVALID_SIGNED_KEY("invalid_skey");

private final String data;

VerificationCodeError(String data) {
this.data = data;
}

@JsonCreator
public static VerificationCodeError of(String name) {
return Arrays.stream(values())
.filter(entry -> entry.data.equalsIgnoreCase(name))
.findFirst()
.orElse(UNKNOWN);
}

public String data() {
return data;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
package it.auties.whatsapp.model.mobile;

import com.fasterxml.jackson.annotation.JsonCreator;

public enum VerificationCodeStatus {
OK,
SENT,
SUCCESS,
ERROR;

public boolean isSuccessful() {
return this == OK || this == SENT;
@JsonCreator
public static VerificationCodeStatus of(String name) {
return name.equalsIgnoreCase("ok") || name.equalsIgnoreCase("sent") ? SUCCESS : ERROR;
}
}
14 changes: 8 additions & 6 deletions src/main/java/it/auties/whatsapp/socket/MessageHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
import static it.auties.whatsapp.util.Spec.Signal.*;

class MessageHandler {
private static final int HISTORY_SYNC_TIMEOUT = 10;
private static final int HISTORY_SYNC_TIMEOUT = 25;

private final SocketHandler socketHandler;
private final Map<ContactJid, List<PastParticipant>> pastParticipantsQueue;
Expand Down Expand Up @@ -144,15 +144,15 @@ private CompletableFuture<Node> encodeConversation(MessageSendRequest request) {
}

var encodedMessage = BytesHelper.messageToBytes(request.info().message());
var knownDevices = getRecipients(request, sender);
var chatJid = request.info().chatJid();
if(request.peer()){
var chatJid = request.info().chatJid();
var peerNode = createMessageNode(request, chatJid, encodedMessage, true);
var encodedMessageNode = createEncodedMessageNode(request, List.of(peerNode), null);
return socketHandler.send(encodedMessageNode);
}

var deviceMessage = new DeviceSentMessage(request.info().chatJid(), request.info().message(), null);
var knownDevices = getRecipients(request, sender);
var deviceMessage = new DeviceSentMessage(request.info().chatJid(), request.info().message(), Optional.empty());
var encodedDeviceMessage = BytesHelper.messageToBytes(deviceMessage);
return getDevices(knownDevices, true)
.thenComposeAsync(allDevices -> createConversationNodes(request, allDevices, encodedMessage, encodedDeviceMessage))
Expand Down Expand Up @@ -454,8 +454,10 @@ private void decodeMessage(Node infoNode, Node messageNode, String businessName)
.orElseThrow(() -> new NoSuchElementException("Missing from"));
var recipient = infoNode.attributes().getJid("recipient").orElse(from);
var participant = infoNode.attributes().getJid("participant").orElse(null);
var messageBuilder = new MessageInfoBuilder();
var keyBuilder = new MessageKeyBuilder();
var messageBuilder = new MessageInfoBuilder()
.status(MessageStatus.PENDING);
var keyBuilder = new MessageKeyBuilder()
.id(MessageKey.randomId());
var receiver = socketHandler.store()
.jid()
.map(ContactJid::toWhatsappJid)
Expand Down
9 changes: 6 additions & 3 deletions src/main/java/it/auties/whatsapp/socket/SocketHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ public class SocketHandler implements SocketListener {
private final Executor socketExecutor;

@NonNull
private SocketState state;
private volatile SocketState state;

@NonNull
private Keys keys;
Expand Down Expand Up @@ -214,6 +214,7 @@ public void onClose() {
disconnect(DisconnectReason.RECONNECTING);
return;
}
System.out.println("State: " + state);
onDisconnected(state.toReason());
onShutdown(state == SocketState.RECONNECTING);
}
Expand Down Expand Up @@ -259,10 +260,10 @@ public CompletableFuture<Void> logoutFuture() {
return logoutFuture;
}

public CompletableFuture<Void> disconnect(DisconnectReason reason) {
public synchronized CompletableFuture<Void> disconnect(DisconnectReason reason) {
var newState = SocketState.of(reason);
if(state == newState) {
return CompletableFuture.completedFuture(null);
return CompletableFuture.completedFuture(null);
}

setState(newState);
Expand Down Expand Up @@ -335,11 +336,13 @@ public CompletableFuture<Void> sendPeerMessage(ContactJid companion, ProtocolMes

var jid = store.jid().orElseThrow(() -> new IllegalStateException("The session isn't connected"));
var key = new MessageKeyBuilder()
.id(MessageKey.randomId())
.chatJid(companion)
.fromMe(true)
.senderJid(jid)
.build();
var info = new MessageInfoBuilder()
.status(MessageStatus.PENDING)
.senderJid(jid)
.key(key)
.message(MessageContainer.of(message))
Expand Down
4 changes: 4 additions & 0 deletions src/main/java/it/auties/whatsapp/socket/StreamHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import it.auties.whatsapp.model.info.MessageInfoBuilder;
import it.auties.whatsapp.model.info.StubType;
import it.auties.whatsapp.model.media.MediaConnection;
import it.auties.whatsapp.model.message.model.MessageKey;
import it.auties.whatsapp.model.message.model.MessageKeyBuilder;
import it.auties.whatsapp.model.message.model.MessageStatus;
import it.auties.whatsapp.model.mobile.PhoneNumber;
Expand Down Expand Up @@ -454,10 +455,12 @@ private void addMessageForGroupStubType(Chat chat, StubType stubType, long times
.orElse(null);
var parameters = getStubTypeParameters(metadata);
var key = new MessageKeyBuilder()
.id(MessageKey.randomId())
.chatJid(chat.jid())
.senderJid(participantJid)
.build();
var message = new MessageInfoBuilder()
.status(MessageStatus.PENDING)
.timestampSeconds(timestamp)
.key(key)
.ignore(true)
Expand Down Expand Up @@ -680,6 +683,7 @@ private void digestError(Node node) {
var statusCode = node.attributes().getInt("code");
switch (statusCode) {
case 515, 503 -> socketHandler.disconnect(DisconnectReason.RECONNECTING);
case 500 -> socketHandler.disconnect(DisconnectReason.LOGGED_OUT);
case 401 -> handleStreamError(node);
default -> node.children().forEach(error -> socketHandler.store().resolvePendingRequest(error, true));
}
Expand Down
Loading

0 comments on commit 9c0cd3b

Please sign in to comment.