Skip to content
Merged
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
29 changes: 11 additions & 18 deletions app/src/org/commcare/connect/MessageManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
import android.util.Log;
import android.widget.Toast;

import com.google.common.base.Strings;

import org.commcare.android.database.connect.models.ConnectMessagingChannelRecord;
import org.commcare.android.database.connect.models.ConnectMessagingMessageRecord;
import org.commcare.android.database.connect.models.ConnectUserRecord;
Expand Down Expand Up @@ -41,6 +43,12 @@ public static ConnectMessagingMessageRecord handleReceivedMessage(Context contex
//Make sure we know and have consented to the channel
ConnectMessagingChannelRecord channel = ConnectDatabaseHelper.getMessagingChannel(context, channelId);
if(channel != null && channel.getConsented()) {
if(Strings.isNullOrEmpty(channel.getKey())) {
//Attempt to get the encryption key now if we don't have it yet
ApiConnectId.retrieveChannelEncryptionKeySync(context, channel);
}

//If we still don't have a key, this will return null and we'll ignore the message
message = ConnectMessagingMessageRecord.fromMessagePayload(payloadData, channel.getKey());
if(message != null) {
ConnectDatabaseHelper.storeMessagingMessage(context, message);
Expand Down Expand Up @@ -204,25 +212,10 @@ public static void getChannelEncryptionKey(Context context, ConnectMessagingChan
new IApiCallback() {
@Override
public void processSuccess(int responseCode, InputStream responseData) {
try {
String responseAsString = new String(
StreamsUtil.inputStreamToByteArray(responseData));
Log.e("DEBUG_TESTING", "processSuccess: " + responseAsString);
ApiConnectId.handleReceivedEncryptionKey(context, responseData, channel);

if(responseAsString.length() > 0) {
JSONObject json = new JSONObject(responseAsString);
channel.setKey(json.getString("key"));
ConnectDatabaseHelper.storeMessagingChannel(context, channel);
}

if(listener != null) {
listener.connectActivityComplete(true);
}
} catch(Exception e) {
Log.e("Error", "Oops", e);
if(listener != null) {
listener.connectActivityComplete(false);
}
if (listener != null) {
listener.connectActivityComplete(true);
}
}

Expand Down
33 changes: 33 additions & 0 deletions app/src/org/commcare/connect/network/ApiConnectId.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import org.commcare.CommCareApplication;
import org.commcare.activities.CommCareActivity;
import org.commcare.android.database.connect.models.ConnectLinkedAppRecord;
import org.commcare.android.database.connect.models.ConnectMessagingChannelRecord;
import org.commcare.android.database.connect.models.ConnectMessagingMessageRecord;
import org.commcare.connect.ConnectConstants;
import org.commcare.connect.ConnectDatabaseHelper;
Expand Down Expand Up @@ -509,6 +510,21 @@ public static boolean updateChannelConsent(Context context, String username, Str
API_VERSION_CONNECT_ID, authInfo, params, false, false, callback);
}

public static void retrieveChannelEncryptionKeySync(Context context, ConnectMessagingChannelRecord channel) {
AuthInfo.TokenAuth auth = ApiConnectId.retrieveConnectIdTokenSync(context);
if(auth != null) {
HashMap<String, Object> params = new HashMap<>();
params.put("channel_id", channel.getChannelId());

ConnectNetworkHelper.PostResult result = ConnectNetworkHelper.postSync(context,
channel.getKeyUrl(), null, auth, params, true, true);

if(result.responseCode >= 200 && result.responseCode < 300) {
handleReceivedEncryptionKey(context, result.responseStream, channel);
}
Comment on lines +522 to +524
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Potential resource leak in response stream handling

The response stream might not be closed if an exception occurs during processing.

Ensure the response stream is properly closed:

if(result.responseCode >= 200 && result.responseCode < 300) {
-    handleReceivedEncryptionKey(context, result.responseStream, channel);
+    try {
+        handleReceivedEncryptionKey(context, result.responseStream, channel);
+    } finally {
+        if(result.responseStream != null) {
+            try {
+                result.responseStream.close();
+            } catch(IOException e) {
+                Logger.exception("Error closing response stream", e);
+            }
+        }
+    }
}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if(result.responseCode >= 200 && result.responseCode < 300) {
handleReceivedEncryptionKey(context, result.responseStream, channel);
}
if(result.responseCode >= 200 && result.responseCode < 300) {
try {
handleReceivedEncryptionKey(context, result.responseStream, channel);
} finally {
if(result.responseStream != null) {
try {
result.responseStream.close();
} catch(IOException e) {
Logger.exception("Error closing response stream", e);
}
}
}
}

}
}

public static void retrieveChannelEncryptionKey(Context context, String channelId, String channelUrl, IApiCallback callback) {
ConnectSsoHelper.retrieveConnectTokenAsync(context, token -> {
HashMap<String, Object> params = new HashMap<>();
Expand All @@ -520,6 +536,23 @@ public static void retrieveChannelEncryptionKey(Context context, String channelI
});
}

public static void handleReceivedEncryptionKey(Context context, InputStream stream, ConnectMessagingChannelRecord channel) {
try {
String responseAsString = new String(
StreamsUtil.inputStreamToByteArray(stream));

if(responseAsString.length() > 0) {
JSONObject json = new JSONObject(responseAsString);
channel.setKey(json.getString("key"));
ConnectDatabaseHelper.storeMessagingChannel(context, channel);
}
} catch(JSONException e) {
throw new RuntimeException(e);
} catch(IOException e) {
Logger.exception("Parsing return from key request", e);
}
}

public static void confirmReceivedMessages(Context context, String username, String password,
List<String> messageIds, IApiCallback callback) {
AuthInfo authInfo = new AuthInfo.ProvidedAuth(username, password, false);
Expand Down