Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import io.kommunicate.devkit.api.account.user.MobiComUserPreference;
import io.kommunicate.devkit.api.account.user.User;
import io.kommunicate.devkit.api.conversation.Message;
import io.kommunicate.devkit.api.conversation.MobiComMessageService;
import io.kommunicate.devkit.api.conversation.SyncCallService;
import io.kommunicate.devkit.api.notification.MobiComPushReceiver;
import io.kommunicate.devkit.broadcast.EventManager;
Expand Down Expand Up @@ -109,12 +110,14 @@ private CoreMqttClient connect() {
@Override
public void onSuccess(IMqttToken asyncActionToken) {
Utils.printLog(context, TAG, "Mqtt Connection successfull to : " + client.getServerURI());
MobiComMessageService.markMqttStateChanged();
BroadcastService.sendUpdate(context, BroadcastService.INTENT_ACTIONS.MQTT_CONNECTED.toString());
}

@Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Utils.printLog(context, TAG, "Mqtt Connection failed");
MobiComMessageService.markMqttStateChanged();
BroadcastService.sendUpdate(context, BroadcastService.INTENT_ACTIONS.MQTT_DISCONNECTED.toString());
}
});
Expand Down Expand Up @@ -193,6 +196,7 @@ public synchronized void subscribeToConversation(boolean useEncrypted) {
if (client != null && client.isConnected()) {
Utils.printLog(context, TAG, "Subscribing to conversation topic : " + (useEncrypted ? MQTT_ENCRYPTION_TOPIC : "") + userKeyString);
client.subscribe((useEncrypted ? MQTT_ENCRYPTION_TOPIC : "") + userKeyString, 0);
MobiComMessageService.markMqttStateChanged();
}
} catch (Exception e) {
e.printStackTrace();
Expand Down Expand Up @@ -226,6 +230,7 @@ public synchronized void subscribeToCustomTopic(String customTopic, boolean useE
String topic = (useEncrypted ? MQTT_ENCRYPTION_TOPIC : "") + customTopic;
Utils.printLog(context, TAG, "Subscribing to topic : " + topic);
client.subscribe(topic, 0);
MobiComMessageService.markMqttStateChanged();
}
} catch (Exception e) {
e.printStackTrace();
Expand Down Expand Up @@ -290,6 +295,7 @@ public synchronized void subscribeToSupportGroup(boolean useEncrypted) {
String topic = (useEncrypted ? MQTT_ENCRYPTION_TOPIC : "") + SUPPORT_GROUP_TOPIC + "-" + getApplicationKey(context);
Utils.printLog(context, TAG, "Subscribing to support group topic : " + topic);
client.subscribe(topic, 0);
MobiComMessageService.markMqttStateChanged();
}
} catch (Exception e) {
e.printStackTrace();
Expand Down Expand Up @@ -328,6 +334,7 @@ public synchronized void subscribeToTeamTopic(boolean useEncrypted, List<String>
String topic = (useEncrypted ? MQTT_ENCRYPTION_TOPIC : "") + TEAM_TOPIC + "-" + team;
Utils.printLog(context, TAG, "Subscribing to team topic : " + topic);
client.subscribe(topic, 0);
MobiComMessageService.markMqttStateChanged();
}
}
} catch (Exception e) {
Expand Down Expand Up @@ -373,6 +380,7 @@ public void disconnect() {
if (client != null && client.isConnected()) {
try {
client.disconnect();
MobiComMessageService.markMqttStateChanged();
} catch (Exception e) {
e.printStackTrace();
}
Expand All @@ -386,6 +394,7 @@ private static boolean isMqttResponseForLoggedInUserDelete(Context context, Mqtt

@Override
public void connectionLost(Throwable throwable) {
MobiComMessageService.markMqttStateChanged();
BroadcastService.sendUpdate(context, BroadcastService.INTENT_ACTIONS.MQTT_DISCONNECTED.toString());
}

Expand Down Expand Up @@ -438,6 +447,9 @@ public void run() {
return;
}
Message message = messageResponse.getMessage();
if (MobiComMessageService.isStreamingTokenMessage(message)) {
return;
}
if (message.getGroupId() != null) {
Channel channel = ChannelService.getInstance(context).getChannelByChannelKey(message.getGroupId());

Expand All @@ -456,10 +468,10 @@ public void run() {
syncCallService.deleteChannelConversationThread(message.getGroupId());
BroadcastService.sendConversationDeleteBroadcast(context, BroadcastService.INTENT_ACTIONS.DELETE_CONVERSATION.toString(), null, message.getGroupId(), SUCCESS);
}
syncCallService.syncMessages(null);
syncCallService.processOrSyncMessages(message);
}
} else {
syncCallService.syncMessages(null);
syncCallService.processOrSyncMessages(message);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ public class ChatIntentService extends CoreJobIntentService {
private MessageClientService messageClientService;
public static final String AL_SYNC_ON_CONNECTIVITY = "AL_SYNC_ON_CONNECTIVITY";
public static final String AL_TIME_CHANGE_RECEIVER = "AL_TIME_CHANGE_RECEIVER";
public static final String AL_SKIP_MESSAGE_AND_STATUS_SYNC = "AL_SKIP_MESSAGE_AND_STATUS_SYNC";
MobiComConversationService conversationService;

/**
Expand Down Expand Up @@ -60,10 +61,15 @@ protected void onHandleWork(@NonNull Intent intent) {
boolean timeChangeReceiver = intent.getBooleanExtra(AL_TIME_CHANGE_RECEIVER, false);

if (connectivityChange) {
SyncCallService.getInstance(ChatIntentService.this).syncMessages(null);
boolean skipMessageAndStatusSync = intent.getBooleanExtra(AL_SKIP_MESSAGE_AND_STATUS_SYNC, false);
Comment thread
adarshmishra marked this conversation as resolved.
Resolved
if (!skipMessageAndStatusSync) {
SyncCallService.getInstance(ChatIntentService.this).syncMessages(null);
}
messageClientService.syncPendingMessages(true);
messageClientService.syncDeleteMessages(true);
conversationService.processLastSeenAtStatus();
if (!skipMessageAndStatusSync) {
conversationService.processLastSeenAtStatus();
}
UserService.getInstance(ChatIntentService.this).processSyncUserBlock();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -208,15 +208,24 @@ public String reportMessage(String messageKey) {
}

public void updateDeliveryStatus(String messageKeyString, String userId, String receiverNumber) {
sendDeliveryReport(messageKeyString, userId);
}

/**
* @return true only if the server answered the delivery report request.
*/
public boolean sendDeliveryReport(String messageKeyString, String userId) {
try {
//Note: messageKeyString comes as null for the welcome message as it is inserted directly.
if (TextUtils.isEmpty(messageKeyString) || TextUtils.isEmpty(userId)) {
return;
return false;
}
httpRequestUtils.getResponse(getMtextDeliveryUrl() + "?key=" + messageKeyString
String response = httpRequestUtils.getResponse(getMtextDeliveryUrl() + "?key=" + messageKeyString
+ "&userId=" + userId, txt_plain, txt_plain);
return !TextUtils.isEmpty(response);
} catch (Exception ex) {
Utils.printLog(context, TAG, "Exception while updating delivery report for MT message");
return false;
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import android.os.Parcelable;
import android.os.SystemClock;
import android.text.TextUtils;

import io.kommunicate.devkit.SettingsSharedPreference;
Expand Down Expand Up @@ -50,6 +51,13 @@ public class MobiComMessageService {

public static final long DELAY = 60000L;
private static final String TAG = "MobiComMessageService";
private static final String STREAMING_TOKEN_KEY_PREFIX = "tokenized_response";
private static final long SYNC_PENDING_TIMEOUT_MS = 30 * 1000L;
private static final long SYNC_FRESH_TIMEOUT_MS = 60 * 1000L;
private static long syncPendingSince;
private static long mqttChangedAt;
private static long lastSyncStartedAt;
private static final Object MESSAGE_INGEST_LOCK = new Object();
public static Map<String, Uri> map = new HashMap<String, Uri>();
public static Map<String, Message> mtMessages = new LinkedHashMap<String, Message>();
protected Context context;
Expand Down Expand Up @@ -193,8 +201,11 @@ public Contact addMTMessage(Message message, int index, boolean showNotification
}

// Message sync can return messages that are already stored (e.g. after they are marked read); don't count or notify them again.
boolean isAlreadyStored = !TextUtils.isEmpty(message.getKeyString()) && messageDatabaseService.isMessagePresent(message.getKeyString());
messageDatabaseService.createMessage(message);
boolean isAlreadyStored;
synchronized (MESSAGE_INGEST_LOCK) {
isAlreadyStored = !TextUtils.isEmpty(message.getKeyString()) && messageDatabaseService.isMessagePresent(message.getKeyString());
messageDatabaseService.createMessage(message);
Comment thread
adarshmishra marked this conversation as resolved.
Resolved
}

//Check if we are........container is already opened...don't send broadcast
boolean isContainerOpened;
Expand All @@ -210,12 +221,16 @@ public Contact addMTMessage(Message message, int index, boolean showNotification
Utils.printLog(context, TAG, "Got notifications for Video call...");
BroadcastService.sendMessageUpdateBroadcast(context, BroadcastService.INTENT_ACTIONS.SYNC_MESSAGE.toString(), message);

VideoCallNotificationHelper helper = new VideoCallNotificationHelper(context);
helper.handleVideoCallNotificationMessages(message);
if (!isAlreadyStored) {
VideoCallNotificationHelper helper = new VideoCallNotificationHelper(context);
Comment thread
adarshmishra marked this conversation as resolved.
Resolved
helper.handleVideoCallNotificationMessages(message);
}

} else if (message.isVideoCallMessage()) {
BroadcastService.sendMessageUpdateBroadcast(context, BroadcastService.INTENT_ACTIONS.SYNC_MESSAGE.toString(), message);
VideoCallNotificationHelper.buildVideoCallNotification(context, message, index);
if (!isAlreadyStored) {
VideoCallNotificationHelper.buildVideoCallNotification(context, message, index);
}
} else if (!isContainerOpened) {

if (message.isConsideredForCount() && !message.hasHideKey()) {
Expand Down Expand Up @@ -264,7 +279,81 @@ public void processOpenGroupAttachmentMessage(Message message) {
processMessage(message, message.getTo(), 0);
}

/**
* @return false if a full sync is already queued and has not started yet, so another one is redundant.
* The pending mark expires so a dropped job can never block syncs for good.
*/
public static synchronized boolean markSyncPending() {
long now = SystemClock.elapsedRealtime();
if (syncPendingSince != 0 && now - syncPendingSince < SYNC_PENDING_TIMEOUT_MS) {
return false;
}
syncPendingSince = now;
return true;
}

private static synchronized void clearSyncPending() {
syncPendingSince = 0;
}

/**
* Call on every MQTT connect, disconnect and subscribe. Messages published around such an event may never reach
* MQTT, so only a sync that starts after it can be trusted to have everything.
*/
public static synchronized void markMqttStateChanged() {
mqttChangedAt = SystemClock.elapsedRealtime();
}

private static synchronized void markSyncStarted(long startedAt) {
lastSyncStartedAt = startedAt;
}

private static synchronized boolean isSyncedSinceMqttChange() {
return lastSyncStartedAt > mqttChangedAt && SystemClock.elapsedRealtime() - lastSyncStartedAt < SYNC_FRESH_TIMEOUT_MS;
}

public static boolean isStreamingTokenMessage(Message message) {
return message.getKeyString() != null && message.getKeyString().startsWith(STREAMING_TOKEN_KEY_PREFIX);
}

/**
* Processes a message received over MQTT the same way a sync would, without calling the sync API.
* Only done when a recent sync already covers everything before the current MQTT connection and the message needs
* nothing the sync does beyond processMessage (user details, channel info, block list, metadata service).
*
* @return false if the caller still has to sync.
*/
public boolean processMqttMessageWithoutSync(Message message) {
if (!isSyncedSinceMqttChange() || TextUtils.isEmpty(message.getKeyString())
|| isStreamingTokenMessage(message)
|| !TextUtils.isEmpty(SettingsSharedPreference.getInstance(context).getMessageMetaDataServiceName())
|| Message.ContentType.CHANNEL_CUSTOM_MESSAGE.getValue().equals(message.getContentType())
|| Message.ContentType.BLOCK_NOTIFICATION_IN_GROUP.getValue().equals(message.getContentType())) {
return false;
}
try {
boolean isKnownConversation = message.getGroupId() != null
? ChannelService.getInstance(context).getChannelByChannelKey(message.getGroupId()) != null
: baseContactService.isContactPresent(message.getContactIds());
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
if (!isKnownConversation) {
return false;
}
if (SettingsSharedPreference.getInstance(context).isHandleDisplayName()
&& !TextUtils.isEmpty(message.getContactIds())
&& !baseContactService.isContactPresent(message.getContactIds())) {
return false;
}
processMessage(message, message.getTo(), 0);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
return messageClientService.sendDeliveryReport(message.getKeyString(), MobiComUserPreference.getInstance(context).getUserId());
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
} catch (Exception e) {
Utils.printLog(context, TAG, "In-place MQTT processing failed, falling back to sync: " + e.getMessage());
return false;
}
}

public synchronized void syncMessages() {
clearSyncPending();
long startedAt = SystemClock.elapsedRealtime();
final MobiComUserPreference userpref = MobiComUserPreference.getInstance(context);
boolean syncChannel = false;
boolean syncChannelForMetadata = false;
Expand Down Expand Up @@ -332,6 +421,7 @@ public synchronized void syncMessages() {
}
}
userpref.setLastSyncTime(String.valueOf(syncMessageFeed.getLastSyncTime()));
markSyncStarted(startedAt);
updateDeliveredStatus(syncMessageFeed.getDeliveredMessageKeys());
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,10 @@ public synchronized void syncMessages(String key, Message message) {
);
}
} else {
if (message == null && !MobiComMessageService.markSyncPending()) {
Utils.printLog(context, TAG, "Full sync already queued, skipping duplicate request.");
return;
}
if (Utils.isDeviceInIdleState(context)) {
new ConversationRunnables(context, message, false, true, false);
} else {
Expand All @@ -140,6 +144,15 @@ public synchronized void syncMessages(String key, Message message) {
}
}

/**
* For a message received over MQTT: processes it in place when that is safe, otherwise falls back to a full sync.
*/
public void processOrSyncMessages(Message message) {
if (!mobiComMessageService.processMqttMessageWithoutSync(message)) {
syncMessages(null);
}
}

public synchronized void syncMessageMetadata() {
if (Utils.isDeviceInIdleState(context)) {
new ConversationRunnables(context, null, false, false, true);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1255,10 +1255,7 @@ public void deleteChannelConversation(Integer channelKey) {
public void updateContactUnreadCount(String userId) {
try {
SQLiteDatabase db = dbHelper.getWritableDatabase();
int unreadCount = getUnreadMessageCountForContact(userId);
ContentValues values = new ContentValues();
values.put("unreadCount", unreadCount + 1);
db.update("contact", values, "userId = ?", new String[]{userId});
Comment thread
adarshmishra marked this conversation as resolved.
Resolved
db.execSQL("UPDATE contact SET unreadCount = COALESCE(unreadCount, 0) + 1 WHERE userId = ?", new String[]{userId});
} catch (Exception e) {
e.printStackTrace();
}
Expand All @@ -1267,10 +1264,7 @@ public void updateContactUnreadCount(String userId) {
public synchronized void updateChannelUnreadCount(Integer channelKey) {
try {
SQLiteDatabase db = dbHelper.getWritableDatabase();
int unreadCount = getUnreadMessageCountForChannel(channelKey);
ContentValues values = new ContentValues();
values.put("unreadCount", unreadCount + 1);
db.update("channel", values, "channelKey = ?", new String[]{String.valueOf(channelKey)});
db.execSQL("UPDATE channel SET unreadCount = COALESCE(unreadCount, 0) + 1 WHERE channelKey = ?", new String[]{String.valueOf(channelKey)});
} catch (Exception e) {
e.printStackTrace();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ public void onReceive(@NonNull final Context context, @NonNull Intent intent) {
firstConnect = false;
Intent connectivityIntent = new Intent(context, ChatIntentService.class);
connectivityIntent.putExtra(ChatIntentService.AL_SYNC_ON_CONNECTIVITY, true);
connectivityIntent.putExtra(ChatIntentService.AL_SKIP_MESSAGE_AND_STATUS_SYNC, isInitialStickyBroadcast());
ChatIntentService.enqueueWork(context, connectivityIntent);
}
}
Expand Down
Loading
Loading